【问题标题】:Get Twitter profile to display in template获取 Twitter 个人资料以在模板中显示
【发布时间】:2015-09-11 13:45:33
【问题描述】:

我正在使用下面的代码在页面上显示用户的 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 %}

【问题讨论】:

    标签: python twitter flask python-twitter


    【解决方案1】:

    您需要编写一个视图来获取 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 %}
    

    【讨论】:

      猜你喜欢
      • 2013-05-29
      • 1970-01-01
      • 2014-09-15
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多