Python无法发送请求
我在使用我的oauth库(Django socialauth)连接Twitter时,遇到了一个“CannotSendRequest”的错误。
Traceback:
File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/me/webfaction/project/socialauth/views.py" in twitter_login
94. request_token = twitter.fetch_request_token(callback=request.build_absolute_uri(reverse('socialauth_twitter_login_done')))
File "/Users/me/webfaction/project/socialauth/lib/oauthtwitter2.py" in fetch_request_token
50. return oauth.OAuthToken.from_string(oauth_response(oauth_request))
File "/Users/me/webfaction/project/socialauth/lib/oauthtwitter2.py" in oauth_response
33. connection().request(req.http_method, req.to_url())
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/httplib.py" in request
914. self._send_request(method, url, body, headers)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/httplib.py" in _send_request
931. self.putrequest(method, url, **skips)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/httplib.py" in putrequest
818. raise CannotSendRequest()
Exception Type: CannotSendRequest at /accounts/twitter_login/
Exception Value:
这是我创建HTTP连接的地方。
def connection():
try:
return connection._connection
except AttributeError:
connection._connection = httplib.HTTPSConnection(TWITTER_URL)
return connection._connection
def oauth_response(req):
connection().request(req.http_method, req.to_url())
return connection().getresponse().read()
我在StackOverflow上搜索过,找到了这些链接,但我还是不太确定怎么去实现解决方案。我尝试过但没有成功。任何帮助都非常感谢。
1 个回答
5
你提到的那篇帖子说这个错误发生在你重用那些已经出错的连接时,而这些连接还没有到达获取响应的阶段。
确实,当你执行 connection.request("GET", "/")
两次时,会出现这个错误。
建议的解决办法是每次都重新创建连接。你想这样做吗?我对这个问题没有个人看法,你只是问我如何实现那些帖子里的内容。
如果是这样的话,去掉你的 connection()
函数,然后总是执行
connection = httplib.HTTPSConnection(TWITTER_URL)
connection.request(req.http_method, req.to_url())
response = connection.getresponse().read()
connection.close()
return response