[英]Python decorator to check for POST parameters on Django
I have code that read like this to check if POST parameters are included on the request: 我有这样读取的代码,以检查请求中是否包含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()
When the list of required POST parameters is big, this code gets messy. 当所需的POST参数列表很大时,此代码将变得混乱。 What I would like to do is something like:
我想做的是这样的:
@required_POST_params('email', 'password')
def login(request):
# 'email' and 'password' are here always!
pass
Then I'm confident that both 'email' and 'password' POST parameters are included in the request, because if not, the request would automatically return HttpResponseBadRequest()
. 然后,我有信心在请求中同时包含“ email”和“ password” POST参数,因为如果没有,则请求将自动返回
HttpResponseBadRequest()
。
Is there a way that Django allows me to do this, and if it doesn't, how can I do it by myself with a decorator? Django是否有办法允许我执行此操作,如果不允许,我如何可以自己使用装饰程序来执行此操作?
You would need a custom decorator, but you can take require_http_methods
as a base example: 您将需要一个自定义装饰器,但是您可以将
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
Example usage: 用法示例:
@require_post_params(params=['email', 'password'])
def login(request):
# 'email' and 'password' are here always!
pass
FYI, require_http_methods
source code . 仅供参考,
require_http_methods
源代码 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.