在 Django 中捕获 KeyError 的正确方法?

发布于 2024-09-15 04:14:44 字数 369 浏览 3 评论 0原文

我正在创建一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最偏执的依靠 2024-09-22 04:14:44

不干净。使用默认值 None 并在之后进行测试。

try:
  username = request.REQUEST.get('username', None)
   ...
except ...:
   ...
else:
  if username is None:
     ...

Not cleanly. Use a default of None and test after.

try:
  username = request.REQUEST.get('username', None)
   ...
except ...:
   ...
else:
  if username is None:
     ...
你怎么敢 2024-09-22 04:14:44

这不行吗?无需例外

if 'username' in request.REQUEST:
    username = request.REQUEST['username']
else:
    #username not found

wouldn't this work? No need for exceptions

if 'username' in request.REQUEST:
    username = request.REQUEST['username']
else:
    #username not found
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文