在 Django 中捕获 KeyError 的正确方法?
我正在创建一个 API,其中将 URL 发送到服务器。我想从 URL 中获取用户名等。我使用以下代码来执行此操作:
try:
username = request.REQUEST['username']
message = request.REQUEST['message']
time = request.REQUEST['time']
except KeyError:
...
但是,有时 URL 中没有用户名、消息、时间等。在这种情况下,会引发 KeyError。我希望能够捕捉到这一点并知道缺少哪个参数,以便我可以发出错误响应代码来告诉用户缺少哪个参数。在 except 区域,有没有办法确定代码失败的地方?
I am creating an API where a URL is sent to the server. I want to get the username, etc from the URL. I use the following code to do that:
try:
username = request.REQUEST['username']
message = request.REQUEST['message']
time = request.REQUEST['time']
except KeyError:
...
However, there are times when the URL does not have a username, message, time, etc in it. In that case, a KeyError is raised. I want to be able to catch this and know which parameter was missing so I can issue an error response code that tells the user which parameter was missing. In the except area, is there a way to determine where the code failed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不干净。使用默认值
None
并在之后进行测试。Not cleanly. Use a default of
None
and test after.这不行吗?无需例外
wouldn't this work? No need for exceptions