1

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()

2 Answers 2

1

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()

Get HTTP response code

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I just had to return the response but now i can't figure out how to get the response code from the thread.
@RickyWilson this, I guess, doesn't fit to the same question. But you can find a detailed discussion on how to handle responses from thread here: stackoverflow.com/questions/6893968/…
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.