在 django 中显示来自 tweepy python 文件的数据

Displaying data from tweepy python file within django

我整天都在摆弄 tweepy package。我让它在 .py 文件中工作,但是我想在视图中显示从 tweepy 获得的推特数据,以在 table 中显示信息。我对此很陌生,我不确定在我的 django 环境中映射我的 testingtweepy.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')