在Django中显示来自Tweepy Python文件的数据



我整天都在玩Tweepy Package。我将其在.py文件中工作,但是我想显示我从Tweepy中获得的Twitter数据,以在表中显示信息。我对此非常陌生,我不确定要在我的django环境中现场绘制testingtwepy.py文件的架构。这是我想在django中显示的代码,作为testingtweepy.py:

import tweepy
from tweepy.auth import OAuthHandler
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
public_tweets = api.home_timeline()
for tweet in public_tweets:
    print(tweet.text)

目标是从public_tweets获取数据并将其存储在Django数据库中,以便我可以在将来显示数据。

感谢您的帮助!

消耗API非常简单。除非要保存响应数据,否则您无需创建任何模型或表格。

  1. views.py

    中创建视图
    def home_timeline(request):
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        api = tweepy.API(auth)
        public_tweets = api.home_timeline()
        return render(request, 'public_tweets.html', {'public_tweets': public_tweets})
    
  2. 创建HTML模板public_tweets.html

    <html>
      <body>
        {% for tweet in public_tweets %}
          <p>{{ tweet.text }}</p>
        {% endfor %}
      </body>
    </html>
    

    这只是一个基本示例。它将从https://api.twitter.com/1.1/statuses/home_timeline.json

  3. 渲染text字段
  4. 将URL添加到urls.py

    url(r'^home_timeline/$',views.home_timeline, name='home_timeline')
    

最新更新