简体   繁体   English

如何在Django的MultiValueDictKeyError上以400响应?

[英]How to respond with 400 in Django on `MultiValueDictKeyError`?

Coming from Flask, request.args[key] and request.form[key] responds with 400 if the key doesn't exist. 如果不存在该密钥,则来自Flask的request.args[key]request.form[key] 响应为400 This has a nice property of failing fast . 这具有快速失败的良好特性。

In Django, request.GET[key] and request.FORM[key] raises HttpResponseBadRequest if the key doesn't exist, which causes your API to respond with a 500 status if unhandled. 在Django中,如果密钥不存在,则request.GET[key]request.FORM[key]会引发HttpResponseBadRequest ,如果未处理,则会导致您的API响应500状态。 I've seen other answers recommending request.GET.get(key) , but that inadvertently loosens the API contract that could allow client-side bugs to slip by (eg a query parameter typo, forgetting to include a param, etc). 我还看到了其他一些建议request.GET.get(key) 答案 ,但这无意间松开了API协定,该协定可能会使客户端的错误溜走(例如,查询参数错字,忘记包含参数等)。

I could manually check for required query params: 我可以手动检查所需的查询参数:

arg1 = request.POST.get('arg1')
if not arg1:
    raise HttpBadRequest('"arg1" was not provided.')

arg2 = request.POST.get('arg2')
if not arg2:
    raise HttpBadRequest('"arg1" was not provided.')

arg3 = request.POST.get('arg3')
if not arg3:
    raise HttpBadRequest('"arg3" was not provided.')

But that leaves a lot of room for error. 但这留下了很多错误的余地。 (Did you notice the typo?) (您注意到错字了吗?)

I could manually handle HttpResponseBadRequest : 我可以手动处理HttpResponseBadRequest

def my_view(request):
    try:
        arg1 = request.POST['arg1']
        arg2 = request.POST['arg2']
        arg3 = request.POST['arg3']
    except MultiValueDictKeyError as ex:
        raise HttpBadRequest('"{}" was not provided.'.format(ex))

But now you have an extra thing to remember when writing views. 但是现在在编写视图时,您还需要记住一件事。

Compare the above examples to Flask's equivalent: 将以上示例与Flask的等效示例进行比较:

arg1 = request.form['arg1']
arg2 = request.form['arg2']
arg3 = request.form['arg3']

How can I write the same thing in Django without extra boilerplate in my views and have it respond with 400 when a param is missing? 如何在Django中编写相同的内容而又没有多余的样板,并在缺少参数时以400响应?

This is exactly you should use Django forms . 正是您应该使用Django表单 They are the validation framework that checks the user input and returns errors when it is not valid. 它们是验证框架,用于检查用户输入并在输入无效时返回错误。

(Note, it's not the accessing of the nonexistent key that raises BadRequest; it raises MultiValueDictKeyError, as one of your snippet notes, and if that is unhandled the response middleware will return BadRequest.) (请注意,不是访问不存在的键会引发BadRequest;它会引发MultiValueDictKeyError,这是您的摘录内容之一,如果未处理,则响应中间件将返回BadRequest。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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