I have a flask view which is executed to load some information in a generator (I am using a generator so that I can continuously yield the progress - how much information has loaded). Here is what the view looks like:
@app.route("/progress", methods=['GET'])
def progress():
gen = get_user_saved_tracks(session['token'], session['spotify_id'], session)
return Response(gen, mimetype= 'text/event-stream')
def get_user_saved_tracks(token, id, session):
#load information and keep yielding
session['info'] = info
I would like to store the information which is loaded in a session variable inside the generator (This generator function is defined in a different file, outside the request context). But when I try to access the session variable, I get the following error:
RuntimeError: Working outside of request context.
So, is there a way to write the information to the session in this way? I am using FileSystemSessionInterface right now but willing to use redis sessions if that will solve my issue.
Update:
As suggested by Sraw, I tried the following changes:
from flask import current_app
app = current_app._get_current_object()
def get_user_saved_tracks(token, id,session):
with app.app_context():
session['info'] = info
But I still get the same error.
Update 2:
So, I need to use the actual app instance instead of using current_app (app object is being created in a different file - app.py)
from app import app
def get_user_saved_tracks(token, id,session):
with app.app_context():
session['info'] = info
On doing this, I get the same error:
RuntimeError: Working outside of request context.
Update 3:
Following is the code for get_user_saved_tracks:
def get_user_saved_tracks(token, id, session, j, service):
tracks = []
for i in range(100):
a = service.current_user_saved_tracks(limit=50, offset=i*50)
if len(a['items']) == 0:
break
yield "data:" + "lib" + str((float(i+1)/(j))*100) + "\n\n"
time.sleep(0.5)
tracks.extend(a)
session['tracks'] = tracks
session.modified = True
yield "data:" + "close" + "\n\n"