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()
cs95
  • 379,657
  • 97
  • 704
  • 746
Ricky Wilson
  • 3,187
  • 4
  • 24
  • 29

2 Answers2

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.

Mohamed Ali JAMAOUI
  • 14,275
  • 14
  • 73
  • 117
  • I just had to return the response but now i can't figure out how to get the response code from the thread. – Ricky Wilson Jul 22 '17 at 21:52
  • @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: https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python – Mohamed Ali JAMAOUI Jul 22 '17 at 22:01
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.

verisimilidude
  • 475
  • 6
  • 9