简体   繁体   English

引发请求错误的最佳方法是什么?

[英]What is the best way to raise request errors?

I'm reading some source code which raises errors for bad requests in the following way: 我正在阅读一些源代码,该源代码通过以下方式针对错误的请求引发错误:

import requests

response = requests.get("www.google.com")   # This won't work because it's missing the http://
if response.ok is False or response.json()['status'] != 'success':
    raise Exception("API error: {}".format(response.json()['message']))

I was thinking that the last two lines could be replaced with 我当时认为最后两行可以替换为

response.raise_for_status()

I actually don't see any difference in the error returned. 我实际上在返回的错误中看不到任何差异。 In both cases it is 在两种情况下都是

Traceback (most recent call last):
  File "/home/kurt/Documents/Scratch/requests_test.py", line 3, in <module>
    response = requests.get("www.google.com")   # This won't work because it's missing the http://
  File "/home/kurt/.local/lib/python2.7/site-packages/requests/api.py", line 69, in get
    return request('get', url, params=params, **kwargs)
  File "/home/kurt/.local/lib/python2.7/site-packages/requests/api.py", line 50, in request
    response = session.request(method=method, url=url, **kwargs)
  File "/home/kurt/.local/lib/python2.7/site-packages/requests/sessions.py", line 451, in request
    prep = self.prepare_request(req)
  File "/home/kurt/.local/lib/python2.7/site-packages/requests/sessions.py", line 382, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/home/kurt/.local/lib/python2.7/site-packages/requests/models.py", line 304, in prepare
    self.prepare_url(url, params)
  File "/home/kurt/.local/lib/python2.7/site-packages/requests/models.py", line 362, in prepare_url
    to_native_string(url, 'utf8')))
requests.exceptions.MissingSchema: Invalid URL 'www.google.com': No schema supplied. Perhaps you meant http://www.google.com?

It seems to me that raise_for_status() is more succinct and perhaps also doesn't lose information on the original exception (cf. Use of "except Exception" vs. "except ... raise" in Python ). 在我看来, raise_for_status()更为简洁,也许也不会丢失有关原始异常的信息(请参阅Python中“ except Exception”与“ except ... raise”的使用 )。 Would this indeed be a better approach? 这确实是更好的方法吗?

response.raise_for_status() only raises an exception if the response status code is not a 200 response. response.raise_for_status()仅在响应状态代码不是200响应时引发异常。 The second case, where response.json()['status'] != 'success' is true, is not covered. 第二种情况,其中response.json()['status'] != 'success'为真时, 覆盖。

You have a different error, however. 但是,您有一个不同的错误。 You never get to the if test, because the exception is raised by the requests.get() call. 您永远不会进入if测试,因为requests.get()调用会引发异常。 You failed to pass in a schema (no http:// or https:// at the start). 您无法传递模式(开始时没有http://https:// )。 Because the exception is raised in the requests.get() expression, the next line is simply never executed. 因为在requests.get()表达式中引发了异常,所以根本不会执行下一行。 No request is even sent, so you can't make any assertions about the response either. 甚至没有请求被发送,因此您也不能对响应做出任何断言。

The test has more problems: 该测试存在更多问题:

  • requests.ok is False is not idiomatic Python; requests.ok is False不是惯用的Python; you'd use not requests.ok instead 您将not requests.ok使用not requests.ok代替
  • If requests.ok is False is true, then the requests.json() call will most likely fail altogether, so the next line using response.json()['message']) will produce a different exception. 如果requests.ok is False则为true,则requests.json()调用很可能会完全失败,因此使用response.json()['message'])的下一行将产生不同的异常。

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

相关问题 收集错误和发送摘要的最佳方法是什么? - What is the best way to collect errors and send a summary? 管理 django 请求类型的最佳方法是什么? - What is the best way to manage django request types? 当测试未在 Python 中引发错误时,执行代码的最佳方法是什么? - What is the best way to execute code when a test does not raise an error in Python? 更改Python的多处理引发错误的方式 - Change the way Python's multiprocessing raise errors python:验证条件和引发异常的最佳方法 - python: best way to verify conditions and raise Exception 错误的发布请求正文会引发什么错误? - What error to raise with wrong post request body? 什么是在Python中引发错误的非常优雅的方法 - What will be a very elegant way to raise an error in Python GAE / Python-将请求从控制器传递到模型的最佳方法是什么? - GAE/Python - What is the best way to pass the request from the controller to the model? Python中适当的方法在设置变量时引发错误 - Proper way in Python to raise errors while setting variables 将数据从 pandas 数据帧导入 SQL 服务器时忽略错误的最佳方法是什么? - What is the best way to ignore errors when importing data from a pandas data frame to SQL Server?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM