Python错误模块没有属性标记
我试图用这段代码查找推文,但结果是回溯 请帮我解决这个问题Python错误模块没有属性标记,python,json,pycurl,Python,Json,Pycurl,我试图用这段代码查找推文,但结果是回溯 请帮我解决这个问题 import time import pycurl import urllib import json import oauth2 as oauth API_ENDPOINT_URL = 'https://stream.twitter.com/1.1/statuses/filter.json' USER_AGENT = 'TwitterStream 1.0' # This can be anything really # You n
import time
import pycurl
import urllib
import json
import oauth2 as oauth
API_ENDPOINT_URL = 'https://stream.twitter.com/1.1/statuses/filter.json'
USER_AGENT = 'TwitterStream 1.0' # This can be anything really
# You need to replace these with your own values
OAUTH_KEYS = {'consumer_key': 'ABC',
'consumer_secret': 'ABC',
'access_token_key': 'ABC',
'access_token_secret': 'ABC'}
# These values are posted when setting up the connection
POST_PARAMS = {'include_entities': 0,
'stall_warning': 'true',
'track': 'iphone,ipad,ipod'}
# twitter streaming is here
class TwitterStream:
def __init__(self, timeout=False):
self.oauth_token = oauth.Token(key=OAUTH_KEYS['access_token_key'], secret=OAUTH_KEYS['access_token_secret'])
self.oauth_consumer = oauth.Consumer(key=OAUTH_KEYS['consumer_key'], secret=OAUTH_KEYS['consumer_secret'])
self.conn = None
self.buffer = ''
self.timeout = timeout
self.setup_connection()
def setup_connection(self):
""" Create persistant HTTP connection to Streaming API endpoint using cURL.
"""
if self.conn:
self.conn.close()
self.buffer = ''
self.conn = pycurl.Curl()
# Restart connection if less than 1 byte/s is received during "timeout" seconds
if isinstance(self.timeout, int):
self.conn.setopt(pycurl.LOW_SPEED_LIMIT, 1)
self.conn.setopt(pycurl.LOW_SPEED_TIME, self.timeout)
self.conn.setopt(pycurl.URL, API_ENDPOINT_URL)
self.conn.setopt(pycurl.USERAGENT, USER_AGENT)
# Using gzip is optional but saves us bandwidth.
self.conn.setopt(pycurl.ENCODING, 'deflate, gzip')
self.conn.setopt(pycurl.POST, 1)
self.conn.setopt(pycurl.POSTFIELDS, urllib.urlencode(POST_PARAMS))
self.conn.setopt(pycurl.HTTPHEADER, ['Host: stream.twitter.com',
'Authorization: %s' % self.get_oauth_header()])
# self.handle_tweet is the method that are called when new tweets arrive
self.conn.setopt(pycurl.WRITEFUNCTION, self.handle_tweet)
def get_oauth_header(self):
""" Create and return OAuth header.
"""
params = {'oauth_version': '1.0',
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': int(time.time())}
req = oauth.Request(method='POST', parameters=params, url='%s?%s' % (API_ENDPOINT_URL,
urllib.urlencode(POST_PARAMS)))
req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), self.oauth_consumer, self.oauth_token)
return req.to_header()['Authorization'].encode('utf-8')
def start(self):
""" Start listening to Streaming endpoint.
Handle exceptions according to Twitter's recommendations.
"""
backoff_network_error = 0.25
backoff_http_error = 5
backoff_rate_limit = 60
while True:
self.setup_connection()
try:
self.conn.perform()
except:
# Network error, use linear back off up to 16 seconds
print 'Network error: %s' % self.conn.errstr()
print 'Waiting %s seconds before trying again' % backoff_network_error
time.sleep(backoff_network_error)
backoff_network_error = min(backoff_network_error + 1, 16)
continue
# HTTP Error
sc = self.conn.getinfo(pycurl.HTTP_CODE)
if sc == 420:
# Rate limit, use exponential back off starting with 1 minute and double each attempt
print 'Rate limit, waiting %s seconds' % backoff_rate_limit
time.sleep(backoff_rate_limit)
backoff_rate_limit *= 2
else:
# HTTP error, use exponential back off up to 320 seconds
print 'HTTP error %s, %s' % (sc, self.conn.errstr())
print 'Waiting %s seconds' % backoff_http_error
time.sleep(backoff_http_error)
backoff_http_error = min(backoff_http_error * 2, 320)
def handle_tweet(self, data):
""" This method is called when data is received through Streaming endpoint.
"""
self.buffer += data
if data.endswith('\r\n') and self.buffer.strip():
# complete message received
message = json.loads(self.buffer)
self.buffer = ''
msg = ''
if message.get('limit'):
print 'Rate limiting caused us to miss %s tweets' % (message['limit'].get('track'))
elif message.get('disconnect'):
raise Exception('Got disconnect: %s' % message['disconnect'].get('reason'))
elif message.get('warning'):
print 'Got warning: %s' % message['warning'].get('message')
else:
print 'Got tweet with text: %s' % message.get('text')
if __name__ == '__main__':
ts = TwitterStream()
ts.setup_connection()
ts.start()
回溯呼叫:
Traceback (most recent call last):
File "C:\Python27\nytimes\2062014\pycurltweets.py", line 115, in <module>
ts = TwitterStream()
File "C:\Python27\nytimes\2062014\pycurltweets.py", line 23, in __init__
self.oauth_token = oauth.token(key=OAUTH_KEYS['access_token_key'], secret=OAUTH_KEYS['access_token_secret'])
AttributeError: 'module' object has no attribute 'Token'
回溯(最近一次呼叫最后一次):
文件“C:\Python27\nytimes\2062014\pycurltweets.py”,第115行,在
ts=TwitterStream()
文件“C:\Python27\nytimes\2062014\pycurltweets.py”,第23行,在\uuu init中__
self.oauth\u token=oauth.token(key=oauth\u KEYS['access\u token\u key'],secret=oauth\u KEYS['access\u token\u secret']))
AttributeError:“模块”对象没有属性“令牌”
您确定oauth2安装正确/版本正确吗
看
打开一个python REPL shell并
import oauth2 as oauth
print oauth.OAUTH_VERSION
dir(oauth)
发布结果我想猜测一下,
oauth.token
中的token
应该大写,最后一行在回溯中实际说的是'token'
,而不是'token'
。这是在编辑过程中发生的。在这两种情况下,它显示相同的错误请测试您发布的代码的确切版本,并发布代码版本产生的确切回溯。如果您弄乱了错误信息,我们将很难为您提供帮助。对于给您带来的不便,我们深表歉意。您可以考虑任何情况下小写令牌或大写令牌。它正在还原相同的错误“module”对象没有属性“token”或“token”。是否有名为oauth2.py的本地文件?回溯(最近一次调用):文件“C:/Python27/nytimes/2062014/aiwehetest.py”,第2行,在print oauth.oauth_VERSION AttributeError中:“module”对象没有属性“oauth_VERSION”,这是恢复上述错误回溯卸载并重新安装oauth版本;确保您的设置中有正确版本的oauth..Wingston我是python新手。请指导我卸载并重新安装。