首页 > 解决方案 > 从烧瓶应用程序将列表发送回html页面时如何避免在分配之前被引用

问题描述

我正在尝试使用搜索词使用 twitter api 获取推文。html 表单请求用户输入搜索词,flask 应用程序使用 request 方法获取它并从 API 收集所有推文。问题是当我需要将推文发送回 HTML 页面进行打印时。我在分配错误之前被引用。这是我的烧瓶应用程序。

@app.route('/realtime')
def realtime():
  tweetCount=0
  s=[]
  if request.method == 'POST':
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True,
               wait_on_rate_limit_notify=True)
    search = request.form.get('word')
    public_tweets = api.search(q=search, lang="te", count=100)
    for tweet in public_tweets:

                Tweet = tweet.text
                Tweet = re.sub('((www\.[\s]+)|(https?://[^\s]+))','URL',Tweet)
                Tweet = re.sub('@[^\s]+','TWITTER_USER',Tweet)
                Tweet = re.sub('[\s]+', ' ', Tweet)
                Tweet = re.sub(r'#([^\s]+)', r'\1', Tweet)
                Tweet = Tweet.strip('\'"')
                a = ':)'
                b = ':('
                Tweet = Tweet.replace(a,'')
                Tweet = Tweet.replace(b,'')
                tag = 'TWITTER_USER' 
                rt = 'RT'
                url = 'URL'
                Tweet = Tweet.replace(tag,'')
                tweetCount+=1
                if rt in Tweet:
                  continue
                Tweet = Tweet.replace(rt,'')
                Tweet = Tweet.replace(url,'')
                s.append(Tweet) 
  return render_template('home.html',
                          tweets=s) 

这是我的带有 python 块的 html 代码,用于打印我们从应用程序获得的推文。

<!DOCTYPE html>
<html>
<head>
    <title>Flask Tweepy Tutorial</title>
</head>
<body>
    <div>
        <form class="form-inline" method="GET" action="{{ url_for('realtime') }}">
            <input class="form-control" type="text" name="word">
            <button class="btn btn-primary" type="submit">search</button>
        </form>
    </div>
    <br>
    <div>
        {% for tweet in tweets %}
        {{ tweet}}   
        {% endfor %}  
   </div>
</body>
</html>

有没有其他方法可以将该推文发送到 html 页面而不在分配之前被引用。

标签: pythonhtmlpython-3.xflasktweepy

解决方案


推荐阅读