0

我正在尝试获取一些代码来创建一个访问 twitter 流的变量“pyresponse”。我必须使用的代码已经过时,因为它不适用于 oauth2。我已收到有关如何更新它的建议,但它仍然无法正常工作。

这是代码(我在这里删除了我的访问和消费者密钥,但它们在我的工作代码中):

import oauth2 as oauth
import urllib2 as urllib
import json

access_token_key = "..."
access_token_secret = "..."

consumer_key = "..."
consumer_secret = "..."

_debug = 0

oauth_token    = oauth.Token(key=access_token_key, secret=access_token_secret)
oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)

signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()

http_method = "GET"


http_handler  = urllib.HTTPHandler(debuglevel=_debug)
https_handler = urllib.HTTPSHandler(debuglevel=_debug)

'''
Construct, sign, and open a twitter request
using the hard-coded credentials above.
'''
def twitterreq(url, method, parameters):
  req = oauth.Request.from_consumer_and_token(oauth_consumer,
                                             token=oauth_token,
                                             http_method=http_method,
                                             http_url=url, 
                                             parameters=parameters)

  req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token)

  headers = req.to_header()

  if http_method == "POST":
    encoded_post_data = req.to_postdata()
  else:
    encoded_post_data = None
    url = req.to_url()

  opener = urllib.OpenerDirector()
  opener.add_handler(http_handler)
  opener.add_handler(https_handler)

  response = opener.open(url, encoded_post_data)

  return response

def fetchsamples():
  url = "https://api.twitter.com/1.1/search/tweets.json?q=microsoft"
  parameters = []
  response = twitterreq(url, "GET", parameters)
  return json.load(response)
#  for line in response:
#    print line.strip()

#if __name__ == '__main__':
#   fetchsamples()

pyresponse =  json.load(fetchsamples()) 
print pyresponse.keys()

当我尝试运行它时,我得到了这个错误:

AttributeError: 'dict' object has no attribute 'read'

附录:这是完整的错误:

Traceback (most recent call last):
  File "new.py", line 65, in <module>
    pyresponse =  json.load(fetchsamples()) 
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 274, in load
AttributeError: 'dict' object has no attribute 'read'
4

1 回答 1

1

您的fetchsamples()方法已返回解码值

def fetchsamples():
  url = "https://api.twitter.com/1.1/search/tweets.json?q=microsoft"
  parameters = []
  response = twitterreq(url, "GET", parameters)
  return json.load(response)

但是您然后尝试再次解码结果:

pyresponse =  json.load(fetchsamples()) 

json.load()然后抱怨fetchsamples()返回了一个python字典。只需json.load()从该行中删除呼叫:

pyresponse =  fetchsamples()
print pyresponse.keys()
于 2013-07-19T09:13:04.297 回答