Awani
Awani

Reputation: 19

Configuring my Python Flask app to call a function every 30 seconds

I have a flask app that returns a JSON response. However, I want it to call that function every 30 seconds without clicking the refresh button on the browser. Here is what I did

Using apscheduler

. This code in application.py

from apscheduler.schedulers.background import BachgroundScheduler

def create_app(config_filname):  
    con = redis.StrictRedis(host= "localhost", port=6379, charset ="utf-8", decode_responses=True, db=0)
    application = Flask(__name__)
    CORS(application)
    sched = BackgroundScheduler()

    @application.route('/users')
    @cross_origin()
    @sched.scheduled_job('interval', seconds = 20)
    def get_users():
        //Some code...
        return jsonify(users)
    sched.start()
    return application

Then in my wsgi.py

from application import create_app
application = create_app('application.cfg')

with application.app_context():
    if __name__ == "__main__":   
        application.run()

When I run this appliaction, I get the json output but it does not refresh instead after 20 seconds it throws

RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed to interface with the current application object in some way. To solve this, set up an application context with app.app_context(). See the documentation for more information.

What am I doing wrong? I would appreciate any advise.

Upvotes: 0

Views: 1213

Answers (1)

Jake Lawrence
Jake Lawrence

Reputation: 296

Apologies if this in a way subverting the question, but if you want the users to be sent every 30 seconds, this probably shouldn't be done in the backend. The backend should only ever send out data when a request is made. In order for the data to be sent at regular intervals the frontend needs to be configured to make requests at regular intervals

Personally I'd recommend doing this with a combination of i-frames and javascript, as described in this stack overflow question: Auto Refresh IFrame HTML

Lastly, when it comes to your actual code, it seems like there is an error here:

if __name__ == "__main__":   
application.run()

The "application.run()" line should be indented as it is inside the if statement

Upvotes: 1

Related Questions