抽离公共方法

master
BINGWU 8 months ago
parent 4901734d9d
commit 9956fcf469

@ -0,0 +1,93 @@
from datetime import datetime
from django.http import JsonResponse
from django.urls import path
from serve.utils.connectdb import connectdb
from bson.objectid import ObjectId
from serve.middleware.handleErrorMethod import handleErrorMethod
from serve.middleware.handleEmpty import handleEmpty
from serve.utils.pyjwt import get_jwt_token, decode_jwt_token
from serve.utils.decodeBody import decodeBody
def delete(request, collection):
result = handleErrorMethod(request.method, 'DELETE')
if result[0]:
ret = decode_jwt_token(request.META.get('HTTP_AUTHORIZATION'))
if ret['code'] == 2000:
data = decodeBody(request)
_ids = list(data['_ids'])
filter_criteria = {'_id': {'$in': [ObjectId(_id) for _id in _ids]}}
deleteResult = collection.delete_many(filter_criteria)
res = handleEmpty(deleteResult.deleted_count, '删除')
return JsonResponse(res)
else:
return JsonResponse(ret)
else:
return JsonResponse(result[1])
def getAll(request, collection):
result = handleErrorMethod(request.method, 'GET')
if result[0]:
ret = decode_jwt_token(request.META.get('HTTP_AUTHORIZATION'))
if ret['code'] == 2000:
pageSize = int(request.GET.get('pageSize', None))
pageIndex = int(request.GET.get('pageIndex', None))
# 计算要跳过的文档数量
skip_count = (pageIndex - 1) * pageSize
# 执行分页查询
cursor = collection.find().skip(skip_count).limit(pageSize)
# 将查询结果转换为列表
result = [{**doc, '_id': str(doc['_id'])} for doc in cursor]
# 构建JSON格式的响应
response_data = {
'total': collection.count_documents({}), # 获取总文档数
'data': result,
'code': 2000
}
return JsonResponse(response_data)
else:
return JsonResponse(ret)
else:
return JsonResponse(result[1])
def create(request, collection, useDate=False):
result = handleErrorMethod(request.method, 'POST')
if result[0]:
ret = decode_jwt_token(request.META.get('HTTP_AUTHORIZATION'))
if ret['code'] == 2000:
data = decodeBody(request)
if useDate:
data['date'] = datetime.now()
collection.insert_one(data)
return JsonResponse({"code": 2000, "msg": "添加成功"})
else:
return JsonResponse(ret)
else:
return JsonResponse(result[1])
def update(request, collection, useDate=False):
result = handleErrorMethod(request.method, 'PUT')
if result[0]:
ret = decode_jwt_token(request.META.get('HTTP_AUTHORIZATION'))
if ret['code'] == 2000:
data = decodeBody(request)
if useDate:
data['date'] = datetime.now()
_id = data['_id']
update_data = data['data']
print(_id)
updateResult = collection.update_one({'_id': ObjectId(_id)}, {"$set": update_data})
res = handleEmpty(updateResult.modified_count, '更新')
return JsonResponse(res)
else:
return JsonResponse(ret)
else:
return JsonResponse(result[1])

@ -0,0 +1,10 @@
from datetime import datetime
from mongoengine import Document, EmbeddedDocument, fields, DateTimeField
class RequestModel(Document):
content = fields.StringField(max_length=30)
employeeName = fields.StringField(max_length=30)
status = fields.StringField(max_length=30)
date = DateTimeField(default=datetime.now)

@ -0,0 +1,8 @@
import json
# 解码字节字符串并解析为 JSON 数据
def decodeBody(request):
body_str = request.body.decode('utf-8')
data = json.loads(body_str)
return data

@ -9,7 +9,7 @@ def get_jwt_token(username, password, role_data='default'):
生成jwt-token 生成jwt-token
""" """
payload = { payload = {
'exp': datetime.utcnow() + timedelta(seconds=300), # 单位秒 'exp': datetime.utcnow() + timedelta(seconds=999999999), # 单位秒
'iat': datetime.utcnow(), 'iat': datetime.utcnow(),
'data': {'username': username, 'password': password, 'role_data': role_data} 'data': {'username': username, 'password': password, 'role_data': role_data}
} }

@ -1,5 +1,7 @@
from serve.views.user import user_url from serve.views.user import user_url
from serve.views.request import request_url
def initUrls(urlpatterns): def initUrls(urlpatterns):
urlpatterns += user_url urlpatterns += user_url
urlpatterns += request_url

@ -0,0 +1,29 @@
from django.urls import path
from serve.utils.connectdb import connectdb
from serve.commonViews.commonViews import delete, getAll, create, update
collection = connectdb('request_model')
def createRequest(request):
return create(request, collection, True)
def getAllRequest(request):
return getAll(request, collection)
def deleteRequest(request):
return delete(request, collection)
def updateRequest(request):
return update(request, collection, True)
request_url = [
path('request/create', createRequest),
path('request/get-all', getAllRequest),
path('request/delete', deleteRequest),
path('request/update', updateRequest)
]

@ -1,77 +1,25 @@
from django.http import JsonResponse from django.http import JsonResponse
import json
from django.urls import path from django.urls import path
from serve.utils.connectdb import connectdb from serve.utils.connectdb import connectdb
from bson.objectid import ObjectId from bson.objectid import ObjectId
from serve.middleware.handleErrorMethod import handleErrorMethod from serve.middleware.handleErrorMethod import handleErrorMethod
from serve.middleware.handleEmpty import handleEmpty
from serve.utils.pyjwt import get_jwt_token, decode_jwt_token from serve.utils.pyjwt import get_jwt_token, decode_jwt_token
from serve.utils.decodeBody import decodeBody
from serve.commonViews.commonViews import delete, getAll, create, update
collection = connectdb('user_model') collection = connectdb('user_model')
def handleUserData(user):
user['_id'] = str(user['_id'])
return user
# 解码字节字符串并解析为 JSON 数据
def decodeBody(request):
body_str = request.body.decode('utf-8')
data = json.loads(body_str)
return data
def createUser(request): def createUser(request):
result = handleErrorMethod(request.method, 'POST') return create(request, collection)
if result[0]:
ret = decode_jwt_token(request.META.get('HTTP_AUTHORIZATION'))
if ret['code'] == 2000:
data = decodeBody(request)
collection.insert_one(data)
return JsonResponse({"code": 2000, "msg": "添加成功"})
else:
return JsonResponse(ret)
else:
return JsonResponse(result[1])
def deleteUser(request): def deleteUser(request):
result = handleErrorMethod(request.method, 'DELETE') return delete(request, collection)
if result[0]:
ret = decode_jwt_token(request.META.get('HTTP_AUTHORIZATION'))
if ret['code'] == 2000:
data = decodeBody(request)
_ids = list(data['_ids'])
filter_criteria = {'_id': {'$in': [ObjectId(_id) for _id in _ids]}}
deleteResult = collection.delete_many(filter_criteria)
res = handleEmpty(deleteResult.deleted_count, '删除')
return JsonResponse(res)
else:
return JsonResponse(ret)
else:
return JsonResponse(result[1])
def updateUser(request): def updateUser(request):
result = handleErrorMethod(request.method, 'PUT') return update(request, collection)
if result[0]:
ret = decode_jwt_token(request.META.get('HTTP_AUTHORIZATION'))
if ret['code'] == 2000:
data = decodeBody(request)
_id = data['_id']
update_data = data['userData']
print(_id)
updateResult = collection.update_one({'_id': ObjectId(_id)}, {"$set": update_data})
res = handleEmpty(updateResult.modified_count, '更新用户')
return JsonResponse(res)
else:
return JsonResponse(ret)
else:
return JsonResponse(result[1])
def getUser(request): def getUser(request):
@ -94,30 +42,7 @@ def getUser(request):
def getAllUser(request): def getAllUser(request):
result = handleErrorMethod(request.method, 'GET') return getAll(request, collection)
if result[0]:
ret = decode_jwt_token(request.META.get('HTTP_AUTHORIZATION'))
if ret['code'] == 2000:
pageSize = int(request.GET.get('pageSize', None))
pageIndex = int(request.GET.get('pageIndex', None))
# 计算要跳过的文档数量
skip_count = (pageIndex - 1) * pageSize
# 执行分页查询
cursor = collection.find().skip(skip_count).limit(pageSize)
# 将查询结果转换为列表
result = [{**doc, '_id': str(doc['_id'])} for doc in cursor]
# 构建JSON格式的响应
response_data = {
'total': collection.count_documents({}), # 获取总文档数
'data': result,
'code': 2000
}
return JsonResponse(response_data)
else:
return JsonResponse(ret)
else:
return JsonResponse(result[1])
def loginUser(request): def loginUser(request):

Loading…
Cancel
Save