gpt4 book ai didi

python - pycurl 在异常后恢复

转载 作者:太空宇宙 更新时间:2023-11-03 17:20:52 26 4
gpt4 key购买 nike

我创建了一个网络服务 bottle并将其用作 JSON 接口(interface)。该例程正在收集信息,检查 URL 的有效性和 http_code。

def get_statuscode(url):
c = pycurl.Curl()
c.setopt(pycurl.URL, "http://"+url)
c.setopt(pycurl.SSL_VERIFYPEER, 0)
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.HEADER, 1)
c.setopt(pycurl.NOBODY, 1)
c.setopt(pycurl.FAILONERROR, 1)
#c.setopt(pycurl.E_)
try:
c.perform()
except pycurl.error:
print "MUH"
return None
pass
temp = c.getinfo(pycurl.HTTP_CODE)
c.close()
return temp

在函数给出一个真正错误的 url 后,如何恢复操作:例如 google.local我的回溯看起来像这样并停止执行:

In[46]: misc.get_statuscode("google.local")
Traceback (most recent call last):
File "PATH\Python\lib\site-packages\IPython\core\interactiveshell.py", line 3035, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-46-c47028d49dc0>", line 1, in <module>
misc.get_statuscode("google.local")
File "PATH\ops\misc.py", line 12, in get_statuscode
c.setopt(pycurl.FOLLOWLOCATION, 1)
error: (6, "Couldn't resolve host 'google.local'")

甚至尝试使用 socket.gethostbyname_ex() 但结果相同。

>>> socket.gethostbyname_ex("google.local")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
socket.gaierror: [Errno -2] Name or service not known

最佳答案

我知道这已经很老了,但我相信答案就是这个

c.setopt(pycurl.FAILONERROR, 1)

更改为:

c.setopt(pycurl.FAILONERROR, 0)

我使用您的代码对此进行了测试,这只是一个小疏忽。

问题在于,当该值设置为 1 时,系统会指示它在出现错误时放弃。

有关 FAILONERROR 的更多信息,我在这里找到:http://manpages.ubuntu.com/manpages/xenial/man3/tclcurl.3.html#contenttoc7

From Docs:

failonerror A 1 parameter tells the extension to fail silently if the HTTP code returned is equal or larger than 400. The default action would be to return the page normally, ignoring that code.

This method is not fail-safe and there are occasions where non- successful response codes will slip through, especially when authentication is involved (response codes 401 and 407).

You might get some amounts of headers transferred before this situation is detected, like for when a "100-continue" is received as a response to a POST/PUT and a 401 or 407 is received immediately afterwards.

关于python - pycurl 在异常后恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33174476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com