[英]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
代替 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.