接受传来的值后进行判断的问题.
在 HttpRequest
对象中,属性 GET 和 POST 得到的都是 django.http.QueryDict
所创建的实例。这是一个 django 自定义的类似字典的类,用来处理同一个键带多个值的情况。所以需要判断 这些内容中是否包含我们需要的数值.
- demo
test_args = {'code': 1, 'data': 2} # 传来的值 这是字典
must_args = {'code', 'data', 'msg'} # 必须要的参数 这是 集合
get_args = {} # 用来存放的字典
if must_args.issubset(set(test_args)):
for item in must_args: # 进行 for 循环 must_args 字典
get_args[item] = test_args[item] # 让 item 填充到 get_args 字典 中
# 此时的结果为{} 空的
# 我们可以通过 前端传来的值 进行 判断 看我们需要的值 是否都存在 .
这里就需要解释下了.
set(test_args) # 输出的结果 为 {'code', 'data'}
issubset : 如果集合 must_args 中存在集合 test_args 中的所有项目,则返回 True, 反则返回False .
这里简单的写个demo
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
class User(APIView):
def get(self, request):
response = {'msg': "禁止错误请求.", 'code': 200}
return Response(response, status=status.HTTP_200_OK)
def post(self, request):
check_data = {"account_number"}
if check_data.issubset(set(request.data)):
accept_rec_data = {}
for item in check_data:
accept_rec_data[item] = request.data[item]
if not accept_rec_data:
return Response({"msg": '异常查询', "code": 200}, status=status.HTTP_200_OK)
return Response({"data": accept_rec_data, "code": 200}, status=status.HTTP_200_OK)
整理成方法
def Handle_Web_result(give_args: dict, must_args: set):
"""
内容中是否包含我们需要的值,Whether the content contains the values we need,
:param give_args:前端传递的值,需要整理成为字典格式.
:param must_args:必要的key值.
:return:
"""
give_args = give_args
must_args = must_args
if not must_args.issubset(set(give_args)):
return
get_args = {}
for item in must_args:
get_args[item] = give_args[item]
return get_args
从数据库读取出来的内容,后端进行操作自己需要使用的数据.
# ---------------------------------------------------
# 从mongodb中读取数据.取出自己想要的部分.
# 根据need_set进行返回
def ret_must_value(need_sets: set, dict_item: dict):
get_args = {}
if need_sets.issubset(set(dict_item)):
for item_a in need_sets:
get_args[item_a] = dict_item[item_a]
return get_args
else:
for item_a in need_sets:
get_args[item_a] = dict_item[item_a] if item_a in dict_item else None
return get_args
# 想要的key值
need_set = {
'name',
'age',
'sex',
'sku'
}
# 假设得mongodb数据结果
transmit_values = [
{"name": 123, "age": 123, 'sex': 123, "work": 123, 'sku': {"name": 123, "age": 123, 'sex': 123, "work": 123}},
{"name": 999, "age": 123, 'sex': 999},
]
for item in transmit_values:
res_a = (ret_must_value(need_set, item))
print(res_a)
# ---------------------------------------------------