0

I have a Flask app where I am running Tweepy in the background to stream all live tweets of a certain tag.

My code is as follows:

app.py

from flask import Flask, render_template, jsonify
import tweepy
from settings import TwitterSettings

app = Flask(__name__)


class MyStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        out = f"{status.user.name} has tweeted -> {status.text}"
        print(out)


@app.route("/")
def index():

    # Get settings instance
    settings = TwitterSettings.get_instance()

    # Auths
    auth = tweepy.OAuthHandler(settings.consumer_key, settings.consumer_secret,)
    auth.set_access_token(
        settings.access_token, settings.access_token_secret,
    )

    # Get API
    api = tweepy.API(auth)

    # Live Tweets Streaming
    myStreamListener = MyStreamListener()
    myStream = tweepy.Stream(auth=api.auth, listener=myStreamListener)
    myStream.filter(track=["fortnite"])

    return render_template("Filtering")


if __name__ == "__main__":
    app.run(debug=True)

The tweets are being displayed in real-time in the console.

What I want to achieve here is to be able to display it on the browser in real-time (through an HTML page). Can someone please help to guide me in the steps to implement that ?

davidism
  • 121,510
  • 29
  • 395
  • 339
Mervin Hemaraju
  • 1,921
  • 2
  • 22
  • 71
  • I can't see how this code actually works. Looks like most of the stuff in your `index` function should be declared at the app level, rather than inside that route, as the index function executes and returns the template when the request comes in, so I struggle to see how the `print` call in `MyStreamListener.on_status` continues to run. Either way, I think you probably should look at [Flask-SocketIO](https://flask-socketio.readthedocs.io/en/latest/) for what you're trying to do, with the aim of using `socket.emit` within that `on_status` function, then have some JS update the page. – v25 Nov 21 '20 at 23:11
  • I made a [gist](https://gist.github.com/vulcan25/0c0a99a85f9528e1d66361d95ae0665f) of a tutorial (not my own; linked in readme) for a basic chat app which may help you out. – v25 Nov 21 '20 at 23:17

0 Answers0