为什么 urllib 会出现这个错误?

发布于 2024-12-20 02:05:11 字数 2325 浏览 3 评论 0原文

我在使用 urllib 时遇到一个奇怪的错误:

INFO     2011-12-07 07:02:45,101 main.py:884] urlhttp://maps.googleapis.com/maps/api/geocode/json?latlng=59.3333,18.05&sensor=false
WARNING  2011-12-07 07:02:45,103 urlfetch_stub.py:428] Stripped prohibited headers from URLFetch request: ['Host']
ERROR    2011-12-07 07:02:45,210 main.py:346] HTTPResponse instance has no attribute 'readline': 
Traceback (most recent call last):
  File "/media/Lexar/montao/lib/webapp2/webapp2.py", line 545, in dispatch
    return method(*args, **kwargs)
  File "/media/Lexar/montao/montaoproject/main.py", line 885, in get
    jsondata = json.load(urllib2.urlopen(url))
  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 391, in open
    response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 409, in _open
    '_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1185, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1176, in do_open
    resp = addinfourl(fp, r.msg, req.get_full_url())
  File "/media/Lexar/montao/google/appengine/dist27/urllib.py", line 978, in __init__
    addbase.__init__(self, fp)
  File "/media/Lexar/montao/google/appengine/dist27/urllib.py", line 926, in __init__
    self.readline = self.fp.readline
AttributeError: HTTPResponse instance has no attribute 'readline'

过去工作的代码是

  url = 'http://maps.googleapis.com/maps/api/geocode/json' + \
    '?latlng={},{}&sensor=false'.format(entity.geopt.lat, entity.geopt.lon)
  logging.info('url%s' % url)
  jsondata = json.load(urllib2.urlopen(url))

你能告诉我这里出了什么问题吗?我在某处读到响应对象没有“get”方法,那么它是如何工作的呢?我认为区别在于我从 SDK 1.6 升级到了 1.6.1 预发布。正在运行的代码与生成错误消息的代码之间可能存在一些其他差异。

谢谢

更新

正如答案中所述,可以使用以下 urlfetch 代替:

  url = 'http://maps.googleapis.com/maps/api/geocode/json' + \
    '?latlng={},{}&sensor=false'.format(entity.geopt.lat, entity.geopt.lon)
  logging.info('url%s' % url)

  from google.appengine.api import urlfetch
  result = urlfetch.fetch(url)
  jsondata = json.loads(result.content)

I get a strange error when using urllib:

INFO     2011-12-07 07:02:45,101 main.py:884] urlhttp://maps.googleapis.com/maps/api/geocode/json?latlng=59.3333,18.05&sensor=false
WARNING  2011-12-07 07:02:45,103 urlfetch_stub.py:428] Stripped prohibited headers from URLFetch request: ['Host']
ERROR    2011-12-07 07:02:45,210 main.py:346] HTTPResponse instance has no attribute 'readline': 
Traceback (most recent call last):
  File "/media/Lexar/montao/lib/webapp2/webapp2.py", line 545, in dispatch
    return method(*args, **kwargs)
  File "/media/Lexar/montao/montaoproject/main.py", line 885, in get
    jsondata = json.load(urllib2.urlopen(url))
  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 391, in open
    response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 409, in _open
    '_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1185, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1176, in do_open
    resp = addinfourl(fp, r.msg, req.get_full_url())
  File "/media/Lexar/montao/google/appengine/dist27/urllib.py", line 978, in __init__
    addbase.__init__(self, fp)
  File "/media/Lexar/montao/google/appengine/dist27/urllib.py", line 926, in __init__
    self.readline = self.fp.readline
AttributeError: HTTPResponse instance has no attribute 'readline'

The code that used to work is

  url = 'http://maps.googleapis.com/maps/api/geocode/json' + \
    '?latlng={},{}&sensor=false'.format(entity.geopt.lat, entity.geopt.lon)
  logging.info('url%s' % url)
  jsondata = json.load(urllib2.urlopen(url))

Could you tell me what's wrong here? I read somewhere that the response object does not have a "get" method then how come it used to work? I think the difference is that I upgraded from SDK 1.6 to 1.6.1 pre-release. There might be some other difference between the code that is working and what is generating the error message.

Thank you

Update

As stated in the answer, the following use of urlfetch works instead:

  url = 'http://maps.googleapis.com/maps/api/geocode/json' + \
    '?latlng={},{}&sensor=false'.format(entity.geopt.lat, entity.geopt.lon)
  logging.info('url%s' % url)

  from google.appengine.api import urlfetch
  result = urlfetch.fetch(url)
  jsondata = json.loads(result.content)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

故乡的云 2024-12-27 02:05:11

这似乎是 SDK 的一个错误。我能够复制完全相同的行为。您使用 urllib2 而不是 urllib 有何原因?

使用Python2.7和SDK 1.6.1,我测试了以下内容:

import urllib  
url = 'http://maps.googleapis.com/maps/api/geocode/json' + \
        '?latlng={},{}&sensor=false'.format(entity.geopt.lat, entity.geopt.lon)
logging.info('url%s' % url)
jsondata = json.load(urllib.urlopen(url))

并且它按预期工作。

如果我可以确定导致文件读取错误的原因,我将跟进/提交错误。

注意:我测试了 KJuly 建议的代码,但它失败并出现相同的错误。看来 urllib2 在不应该依赖的情况下依赖了 urllib 。进一步挖掘。

编辑:由于 urlliburllib2 只是 urlfetch 的包装器,我可能还建议以下内容:

from google.appengine.api import urlfetch
result = urlfetch.fetch(url)
jsondata = json.loads(result.content)

第二次编辑:在任何一种情况下,我们都使用urllib2 的本地版本 (/usr/lib/python2.7/urllib2.py),然后尝试与 GAE 特定版本的 urllib 进行交互 (google/appengine/dist27/urllib.py)。

This seems to be a bug with the SDK. I was able to replicate the exact same behavior. Is there any reason you are using urllib2 instead of urllib?

Using Python2.7 and SDK 1.6.1, I tested the following:

import urllib  
url = 'http://maps.googleapis.com/maps/api/geocode/json' + \
        '?latlng={},{}&sensor=false'.format(entity.geopt.lat, entity.geopt.lon)
logging.info('url%s' % url)
jsondata = json.load(urllib.urlopen(url))

and it worked as expected.

I'll follow up/file a bug if I can determine what's causing the file read error.

NOTE: I tested the code suggested by KJuly and it failed with the same error. It seems urllib2 is relying on urllib when it shouldn't be. Digging further.

EDIT: Since urllib and urllib2 are just wrappers for urlfetch, I might also suggest the following:

from google.appengine.api import urlfetch
result = urlfetch.fetch(url)
jsondata = json.loads(result.content)

Second EDIT: In either case, we are using a local version of (/usr/lib/python2.7/urllib2.py) of urllib2, which then tries to interact with a GAE specific version of urllib (google/appengine/dist27/urllib.py).

盗心人 2024-12-27 02:05:11

丢失 Request() 方法?也许它会起作用。

headers = { 'Content-Type' : 'application/json' } // Maybe 'application/xml'
data = None
req  = urllib2.Request(url, data, headers)    
resp = urllib2.urlopen(req)         
data = resp.read()
jsondata = json.load(data)

我在 python 控制台中尝试过:

>>> 导入 urllib2
>>> headers = { 'Content-Type' : 'application/json' }
>>> 数据 = 无
>>> req = urllib2.Request("http://maps.googleapis.com/maps/api/geocode/json?latlng=59.3333,18.05&sensor=false"、数据、标头)
>>> 响应 = urllib2.urlopen(req)
>>> data = response.read()
>>>数据

,它将正确打印数据。这是我的结果:

Lose Request() method? Maybe it will works.

headers = { 'Content-Type' : 'application/json' } // Maybe 'application/xml'
data = None
req  = urllib2.Request(url, data, headers)    
resp = urllib2.urlopen(req)         
data = resp.read()
jsondata = json.load(data)

I tried in python console:

>>> import urllib2
>>> headers = { 'Content-Type' : 'application/json' }
>>> data = None
>>> req = urllib2.Request("http://maps.googleapis.com/maps/api/geocode/json?latlng=59.3333,18.05&sensor=false", data, headers)
>>> response = urllib2.urlopen(req)
>>> data = response.read()
>>> data

and it'll print the data correctly. Here is my result:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文