我有这样读取的代码,以检查请求中是否包含POST参数:
def login(request):
required_params = frozenset(('email', 'password'))
if required_params <= frozenset(request.POST):
# 'email' and 'password' are included in the POST request
# continue as normal
pass
else:
return HttpResponseBadRequest()
当所需的POST参数列表很大时,此代码将变得混乱。我想做的是这样的:
@required_POST_params('email', 'password')
def login(request):
# 'email' and 'password' are here always!
pass
然后,我有信心在请求中同时包含“ email”和“ password” POST参数,因为如果没有,请求将自动返回
HttpResponseBadRequest()
。Django是否有办法允许我执行此操作,如果不允许,我如何可以自己使用装饰器来执行此操作?
最佳答案
您将需要一个自定义装饰器,但是可以使用require_http_methods
作为基本示例:
def require_post_params(params):
def decorator(func):
@wraps(func, assigned=available_attrs(func))
def inner(request, *args, **kwargs):
if not all(param in request.POST for param in params):
return HttpResponseBadRequest()
return func(request, *args, **kwargs)
return inner
return decorator
用法示例:
@require_post_params(params=['email', 'password'])
def login(request):
# 'email' and 'password' are here always!
pass
仅供参考,
require_http_methods
source code。关于python - Python装饰器在Django上检查POST参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23944969/