1

Sorry for the poorly worded title.

My goal is to set up a Flask Page using AJAX so that I can add dynamic content to a page as the Python Program is running.

I am using flask_oauthlib to get an access token to a REST API, and then querying that REST API for paginated content.

I want to show "progress" as we repeat the REST call to get the different pages of content from the API. The REST API access token is stored in the user's session variable.

I have followed these steps to get a basic dynamic page up and running. However, when I start modifying the "progress" function, to add access to the session variable, everything starts to fail.

I get the error: RuntimeError: Working outside of request context. which tells me I am not in the right session context.

My guess is because this endpoint is being called from javascript using a new EventSource... How would I be able to get access to the session context in this way?

Am I going down the right path, or is there a better option available?

Here is the various code blocks I have:

<!DOCTYPE html>
<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    <script>

    var source = new EventSource("/progress");
    source.onmessage = function(event) {
        $('.text').text(event.data);
    }
    </script>
</head>
<body>
        <p class="text"></p>
</body>
</html>

@app.route('/sentMail')
def sentMail():  
    return render_template('progress.html')

@app.route('/progress')
def progress():
    def generate():
        #code using trying to use session here
    return Response(generate(), mimetype= 'text/event-stream')
Shawn Tabrizi
  • 12,206
  • 1
  • 38
  • 69

1 Answers1

3

Once web server started processing Response you can't access to request context but thankfully Flask comes with stream decorator @stream_with_context that you can use to access the request context in the streaming...

Modify your code to something below...

from flask import stream_with_context


@app.route('/progress')
def progress():
    @stream_with_context
    def generate():
        ...
        Your remaining code
        ...
Raja Simon
  • 10,126
  • 5
  • 43
  • 74