Python decorator to check for POST parameters on Django -


i have code read check if post parameters included on request:

def login(request):     required_params = frozenset(('email', 'password'))     if required_params <= frozenset(request.post):         # 'email' , 'password' included in post request         # continue normal         pass     else:         return httpresponsebadrequest() 

when list of required post parameters big, code gets messy. like:

@required_post_params('email', 'password') def login(request):     # 'email' , 'password' here always!     pass 

then i'm confident both 'email' , 'password' post parameters included in request, because if not, request automatically return httpresponsebadrequest().

is there way django allows me this, , if doesn't, how can myself decorator?

you need custom decorator, can take require_http_methods 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 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' , 'password' here always!     pass 

fyi, require_http_methods source code.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -