我有下一个代码:
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
import tweepy
consumer_key=""
consumer_secret=""
access_key = ""
access_secret = ""
def twitterfeed():
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
statuses = tweepy.Cursor(api.friends_timeline).items(20)
for status in statuses:
return list(str(status.text))
这个 Twitter feed() 方法在 bash/console 上工作,并显示我和我的订阅者的最新推文。但是当我想在页面上显示这条推文时:
if __name__ == '__main__':
config = Configurator()
config.add_route('hello', '{name}')
config.add_view(twitterfeed(), route_name='hello')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 8080, app)
server.serve_forever()
它向我显示pyramid.exceptions.ConfigurationExecutionError: <type 'exceptions.AttributeError'>: 'list' object has no attribute '__module__'
in:
Line 24
错误
我该如何修复它? 如果你有来自 Django 的工作示例,它可以帮助我。
你应该注册函数,而不是函数的结果:
config.add_view(twitterfeed, route_name='hello')
否则,您将尝试将 twitterfeed
返回的列表注册为视图。
请注意,你的函数也需要接受一个request
参数;它也必须返回一个响应对象。将其更改为:
from pyramid.response import Response
def twitterfeed(request):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
statuses = tweepy.Cursor(api.friends_timeline).items(20)
return Response('n'.join([s.text.encode('utf8') for s in statuses]))
我冒昧地将推文编码为 UTF8,而不是让 Python 为它们选择默认编码(如果您的推文中有任何国际字符,这将导致 UnicodeEncodeError 异常)。
在继续之前,您确实想阅读金字塔视图。
顺便说一句,您的命令行版本仅返回第一条推文作为单个字符的列表(return list(str(status.text))
)。