python - pycurl 在异常后恢复

标签 python pycurl

我创建了一个网络服务 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/

相关文章:

python - 如何在执行前通过 python 程序显式配置命令提示符?

python - 为什么在 scikit-learn 中使用 make_pipeline 时出现 'last step of pipeline' 错误?

python - 无法解析的参数 : 5PL getting this error while trying to post the file through pycurl in python

python - HTTPS 请求 CurlAsyncHTTPClient 内存泄漏

python - 如何删除字符串值上的 '\n' 或将 ByteIO 正确转换为列表?

python - 压缩文件并保留修改时间戳

python - 那一年有人在 Pandas 呆了几个月?

python - 在python中用逗号作为小数点分隔符编写csv

python - 如何在python中正确处理多个二进制文件?

python - 安装包之间的pycurl版本冲突