获取Twitter个人资料以在模板

时间:2015-09-11 13:45:33

标签: python twitter flask python-twitter

我使用下面的代码在页面上显示用户的Twitter个人资料。在下面的示例中,我尝试显示用户名' dogculture'的个人资料。为什么这不起作用?

__init__.py

def get_user_profile(twitter_api, screen_names=None, user_ids=None):
    items_to_info = {}
    items = screen_names or user_ids

    while len(items) > 0:
        # Process 100 items at a time per the API specifications for /users/lookup.
        items_str = ','.join([str(item) for item in items[:100]])
        items = items[100:]

        if screen_names:
            response = make_twitter_request(twitter_api.users.lookup, screen_name=items_str)
        else: # user_ids
            response = make_twitter_request(twitter_api.users.lookup, user_id=items_str)

        for user_info in response:
            if screen_names:
                items_to_info[user_info['screen_name']] = user_info
            else: # user_ids
                items_to_info[user_info['id']] = user_info

    return items_to_info

profile.html

{% block body %}
<body>
<div class="container">
twitter_api = oauth_login()
response = make_twitter_request(twitter_api.users.lookup, screen_name="dogculture")
print json.dumps(response, indent=1)
</div>
</body>
{% endblock %}

1 个答案:

答案 0 :(得分:2)

您需要编写视图以获取Twitter数据并呈现模板。您可以将配置文件数据传递给模板,而不是在其中编写Python代码。

@app.route('/profile/<username>')
def profile(username):
    twitter_api = oauth_login()
    profiles = get_user_profile(twitter_api, screen_names=(username,))
    profile = profiles.get(username)

    if profile is None:
        abort(404)

    return render_template('profile.html', profile=profile)
{% block body %}
Render the contents of the profile dict here.
For example, here's the username.
{{ profile['username'] }}
{% endblock %}