需求:基于Python提取Django API所有请求参数及值的通用方法
通用获取并校验所有请求参数的方法(支持GET/POST)
一、获取所有非空请求参数
下面的方法可以自动兼容GET和POST请求,合并所有参数并过滤掉无实际值的参数(空字符串、None、空列表等):
def get_all_non_empty_params(request): all_params = {} # 处理GET请求的URL查询参数 if request.method == 'GET': all_params.update(request.query_params.dict()) else: # 处理POST请求的不同数据格式 if request.content_type == 'application/json': # JSON格式的请求体 all_params.update(request.data) else: # 表单格式(form-data/x-www-form-urlencoded) all_params.update(request.POST.dict()) # 过滤掉空值参数 return {k: v for k, v in all_params.items() if v not in [None, '', []]}
二、参数有效性校验
搭配自定义校验函数,可根据业务规则对参数进行校验,支持必填、类型、长度、数值范围等规则:
def validate_params(params, validation_rules): errors = {} for param_name, rules in validation_rules.items(): # 校验必填参数 if rules.get('required', False) and param_name not in params: errors[param_name] = '该参数为必填项' continue if param_name not in params: continue value = params[param_name] # 校验参数类型 expected_type = rules.get('type') if expected_type and not isinstance(value, expected_type): errors[param_name] = f"参数类型错误,期望{expected_type.__name__},实际为{type(value).__name__}" # 校验字符串长度 if isinstance(value, str): min_len = rules.get('min_length') max_len = rules.get('max_length') if min_len and len(value) < min_len: errors[param_name] = f"参数长度不能小于{min_len}" if max_len and len(value) > max_len: errors[param_name] = f"参数长度不能大于{max_len}" # 校验数值范围 if isinstance(value, (int, float)): min_val = rules.get('min_value') max_val = rules.get('max_value') if min_val is not None and value < min_val: errors[param_name] = f"参数值不能小于{min_val}" if max_val is not None and value > max_val: errors[param_name] = f"参数值不能大于{max_val}" return errors
三、在API视图中使用示例
以Django REST Framework为例,在视图中整合上述两个方法:
from rest_framework.response import Response from rest_framework import status def sample_api_view(request): # 获取所有非空参数 valid_params = get_all_non_empty_params(request) # 定义业务所需的校验规则 validation_rules = { 'username': {'type': str, 'required': True, 'min_length': 3, 'max_length': 20}, 'age': {'type': int, 'min_value': 18, 'max_value': 100}, 'email': {'type': str, 'required': True} } # 执行校验 validation_errors = validate_params(valid_params, validation_rules) if validation_errors: return Response({'errors': validation_errors}, status=status.HTTP_400_BAD_REQUEST) # 参数校验通过,执行后续业务逻辑 return Response({ 'message': '参数校验通过', 'received_params': valid_params })
补充说明
- 如果使用Flask框架,只需替换request对象的对应属性:GET参数用
request.args,POST表单用request.form,JSON请求体用request.get_json()。 - 校验函数可根据需求扩展,比如添加正则匹配(如邮箱、手机号格式)、枚举值校验等逻辑。
内容的提问来源于stack exchange,提问作者BetaTester
相关产品推荐
相关产品推荐

