gpt4 book ai didi

python - 为什么我获取不到这个http_response的状态码?

转载 作者:可可西里 更新时间:2023-11-01 17:27:03 24 4
gpt4 key购买 nike

为什么会出现这个错误:

Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib/python2.7/urllib2.py", line 435, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 542, in http_response
code, msg, hdrs = response.code, response.msg, response.info()
AttributeError: 'str' object has no attribute 'code'

import urllib2
import threading

class MyHandler(urllib2.HTTPHandler):
def http_response(self, req, response):
return response.getcode()

o = urllib2.build_opener(MyHandler())
t = threading.Thread(target=o.open, args=('http://www.google.com/',))
t.start()
t.join()

最佳答案

在您的处理程序中,您应该返回response

import urllib2
import threading

class MyHandler(urllib2.HTTPHandler):
def http_response(self, req, response):
return response

o = urllib2.build_opener(MyHandler())
t = threading.Thread(target=o.open, args=('http://www.google.com/',))
t.start()
t.join()

因为,如错误所述,http_response 应返回三个值:code、msg、hdrs

  File "/usr/lib/python2.7/urllib2.py", line 542, in http_response
code, msg, hdrs = response.code, response.msg, response.info()

但是您正在使用 response.getcode()

覆盖它以仅返回一个值

获取HTTP响应码

要获取响应代码,您需要处理从线程获取返回结果。 This SO讨论提出了几种方法来做到这一点。

以下是您将如何更改代码以使用队列:

import urllib2
import threading
import Queue


class MyHandler(urllib2.HTTPHandler):
def http_response(self, req, response):
return response

que = Queue.Queue()
o = urllib2.build_opener(MyHandler())
t = threading.Thread(target=lambda q, arg1: q.put(o.open(arg1)), args=(que, 'http://www.google.com/'))
t.start()
t.join()
result = que.get()
print result.code

代码打印200

关于python - 为什么我获取不到这个http_response的状态码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45259302/

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