Python Django:request.GET 和 KeyError
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3845582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django: request.GET and KeyError
提问by glss
Code:
代码:
# it's an ajax request, so parameters are passed via GET method
def my_view(request):
my_param = request.GET['param'] // should I check for KeyError exception?
In PHP Frameworks I typically have to check for parameter to exists and redirect user somewhere if it does not. But in Django unexisted parameter results in 500 error page and it seems desired behaviour. So is it ok to leave code as is or there is a better practic? Should I always use standard params passing like /myaction/paramvalue/ instead of /myaction?param_name=param_value (it's kinda hard to build such URLs for ajax requests)?
在 PHP 框架中,我通常必须检查参数是否存在,如果不存在,则将用户重定向到某个地方。但是在 Django 中不存在的参数会导致 500 错误页面,这似乎是理想的行为。那么可以保持代码不变还是有更好的做法?我应该总是使用像 /myaction/paramvalue/ 这样的标准参数而不是 /myaction 吗?param_name=param_value(为 ajax 请求构建这样的 URL 有点困难)?
采纳答案by Ned Batchelder
Your server should never produce a 500 error page.
您的服务器不应产生 500 错误页面。
You can avoid the error by using:
您可以使用以下方法避免错误:
my_param = request.GET.get('param', default_value)
or:
或者:
my_param = request.GET.get('param')
if my_param is None:
return HttpResponseBadRequest()
回答by Mike DeSimone
Yes, you should check for KeyErrorin that case. Or you could do this:
是的,KeyError在这种情况下你应该检查一下。或者你可以这样做:
if 'param' in request.GET:
my_param = request.GET['param']
else:
my_param = default_value
回答by Srikanth Chundi
How about passing default value if param doesn't exist ?
如果 param 不存在,如何传递默认值?
my_param = request.GET.get('param', 'defaultvalue')

