0

我有下一个代码:

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))

这个 twitterfeed() 方法正在 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 的工作示例,它可以帮助我。

4

1 回答 1

2

您应该注册函数,而不是函数的结果:

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))) 的列表返回。

于 2013-01-27T12:53:51.133 回答