scob_
scob_

Reputation: 287

Why aren't global variables working here?

I'm trying to use the Twitter API to create my own private API just to run locally on my PC

See the code below:

from flask import Flask
import tweepy, json
from tweepy import Stream
from tweepy.streaming import StreamListener

app = Flask(__name__)


@app.route('/')
def example():
    global clean_data

    class StdOutListener(StreamListener):
        def on_data(self, data):
            global clean_data
            clean_data = json.loads(data) 
            return clean_data
        
    def setUpAuth():
        # authentication and stuff here

    def followStream():
        api, auth = setUpAuth()
        listener = StdOutListener()
        stream = Stream(auth, listener)
        stream.filter(track=["@user"], is_async=True, stall_warnings=True)

    followStream()

    return clean_data

if __name__ == '__main__':
    app.run()

clean_data is the JSON that twitter returns, aand is what I want to display on flask, but it keeps returning a 500 error, and the console outputs clean_data is not defined

This is a very simplified version of my code, but it's suffiecient to demonstrate the error I'm getting. What am I doing wrong?

The same thing happens if I was just to define clean_data as a random string.

Upvotes: 0

Views: 122

Answers (1)

ilov3
ilov3

Reputation: 427

The problem is that StdOutListener.on_data is a sort of a callback function in asynchronous code, so you don't know when(concrete time) exactly it would be called, it would be called when some data will be received, so you need to rethink and redesign your code through promises or another callback/async functions if you want process that data which you receiving inside StdOutListener.on_data

Upvotes: 1

Related Questions