python - How to respond with 400 in Django on `MultiValueDictKeyError`? -
coming flask, request.args[key]
, request.form[key]
responds 400 if key doesn't exist. has nice property of failing fast.
in django, request.get[key]
, request.form[key]
raises httpresponsebadrequest
if key doesn't exist, causes api respond 500 status if unhandled. i've seen other answers recommending request.get.get(key)
, inadvertently loosens api contract allow client-side bugs slip (e.g. query parameter typo, forgetting include param, etc).
i manually check required query params:
arg1 = request.post.get('arg1') if not arg1: raise httpbadrequest('"arg1" not provided.') arg2 = request.post.get('arg2') if not arg2: raise httpbadrequest('"arg1" not provided.') arg3 = request.post.get('arg3') if not arg3: raise httpbadrequest('"arg3" not provided.')
but leaves lot of room error. (did notice typo?)
i manually handle httpresponsebadrequest
:
def my_view(request): try: arg1 = request.post['arg1'] arg2 = request.post['arg2'] arg3 = request.post['arg3'] except multivaluedictkeyerror ex: raise httpbadrequest('"{}" not provided.'.format(ex))
but have thing remember when writing views.
compare above examples flask's equivalent:
arg1 = request.form['arg1'] arg2 = request.form['arg2'] arg3 = request.form['arg3']
how can write same thing in django without boilerplate in views , have respond 400
when param missing?
this should use django forms. validation framework checks user input , returns errors when not valid.
(note, it's not accessing of nonexistent key raises badrequest; raises multivaluedictkeyerror, 1 of snippet notes, , if unhandled response middleware return badrequest.)
Comments
Post a Comment