Reputation: 3359
Why do i get this error:
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()
Upvotes: 1
Views: 171
Reputation: 14699
In your handler you should return the 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()
Because, as the error is stating, http_response is expected to return three values: code, msg, hdrs
File "/usr/lib/python2.7/urllib2.py", line 542, in http_response
code, msg, hdrs = response.code, response.msg, response.info()
But you are overriding it to return only one value with response.getcode()
To get response code, you need to handle getting return results from the Thread. This SO discussion presents several methods to do that.
Here is how you would change your code to use Queue:
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
The code prints 200
.
Upvotes: 1
Reputation: 475
What the error message is saying is that response
is a str
and there is no code
attribute in a str
. I suspect that response
needs to be parsed to pull out the code.
Upvotes: 0