简体   繁体   中英

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:

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. 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() .

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?

You would need a custom decorator, but you can take require_http_methods as a base example:

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 .

Try with this .

Instead of require.POST() , try with require.POST('email', 'password') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM