python - 单击按钮停止 stream.filter()

标签 python flask tweepy

我正在使用 tweepy 来流式传输推文并将其存储在文件中。我正在使用 python 和 flask 。单击一个按钮,流开始获取推文。我想要的是,只需单击一个按钮,流就会停止。 我知道与计数器变量相关的答案,但我不想获取特定数量的推文。

提前致谢

def fetch_tweet():
    page_type = "got"



    lang_list = request.form.getlist('lang') 

    print lang_list
    #return render_template("index.html",lang_list=lang_list,page_type=page_type)
    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, l)

    with open('hashtags.txt') as hf:
        hashtag = [line.strip() for line in hf]
        print hashtag

    print request.form.getlist('fetchbtn')
    if (request.form.getlist('stopbtn')) == ['stop']:
        print "inside stop"
        stream.disconnect()
        return render_template("analyse.html")
    elif (request.form.getlist('fetchbtn')) == ['fetch']:
        stream.filter(track=lang_list, async=True)
        return render_template("fetching.html")

最佳答案

所以我假设您的初始按钮链接到 tweepy 流的初始化(即调用 stream.filter())。

如果您要允许您的应用程序在推文收集过程中运行,您将需要异步(线程化)收集推文。否则,一旦您调用 stream.filter(),它会在收集推文时锁定您的程序,直到它达到您提供的某个条件或您按 ctrl-c 退出等。

要利用 tweepy 的内置线程,您只需将 async 参数添加到您的流初始化中,如下所示:

stream.filter(track=['your_terms'], async=True)

这将线程化您的推文集合并允许您的应用程序继续运行。

最后,要停止您的推文收集,请将 Flask 调用链接到在您的 stream 对象上调用 disconnect() 的函数,如下所示:

stream.disconnect()

这将断开您的流并停止推文收集。 Here是在更面向对象的设计中使用这种方法的示例(请参阅 Pyckaxe 对象中的 gather()stop() 方法) .


编辑 - 好的,我现在可以看到您的问题,但我将把我原来的答案留给可能发现这个问题的其他人。你的问题是你在哪里创建你的 stream 对象。

每次通过 flask 调用 fetch_tweet() 时,您都会创建一个新的 stream 对象,因此当您第一次调用它以启动您的流时,它会创建一个初始对象,但第二次它在不同 流对象上调用disconnect()。创建流的单个实例将解决问题:

l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)

def fetch_tweet():
    with open('hashtags.txt') as hf:
        hashtag = [line.strip() for line in hf]
        print hashtag

    print request.form.getlist('fetchbtn')
    if (request.form.getlist('stopbtn')) == ['stop']:
        print "inside stop"
        stream.disconnect()
        return render_template("analyse.html")
    elif (request.form.getlist('fetchbtn')) == ['fetch']:
        stream.filter(track=lang_list, async=True)
        return render_template("fetching.html")

长话短说,您需要在 fetch_tweets()外部 创建您的stream 对象。祝你好运!

关于python - 单击按钮停止 stream.filter(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28693960/

相关文章:

python - 通过 Python 抓取 Twitter 嵌入 URL

twitter - 为什么 Twitter API 返回错误 'If you need access to this endpoint, you may need a different access level?'

python - tensorflow 二维直方图

python - IPython.display.display_markdown() 函数的目的是什么?

python - Flask Redis 队列 (RQ) worker 无法导入名为 app 的模块

python-2.7 - 如何从flask API返回401身份验证?

python - Python 3 中导入错误,但适用于 Python 2

python - 迭代pandas数据框中的多列和行

python - 尝试使用 Flask-Admin 设置模型 View 会导致 ImportError

python - 如何使用 tweepy/Python 在 Twitter 上关注某人?