5

From the question:

Streaming data with Python and Flask

The code is running normal, and I want to modify the function g(), but the request parameter can not be passed into g() and it raises a RuntimeError: working outside of request context.

I have been debugging for a long time, and I don't know how to modify it, can you help review the code and explain the reason behind the error?

Thanks.

My code is:

@app.route('/username', methods=['GET', 'POST'])
def index():
    req =request
    print req
    print "111------------"  + req.method + "\n"
    def ggg1(req):
        print req  # the req not my pass into the req....
        print "444------------" + req.method + "\n"
        if req.method == 'POST':
            if request.form['username']:
                urlList = request.form['username'].splitlines()
                i = 0
                for url in urlList():
                    i += 1
                    resultStr = chkListPageContent(url, getUrlContent(url), "script")
                    print i, resultStr
                    yield i, resultStr
    print req
    print "222------------" + req.method + "\n"
    return Response(stream_template('index.html', data=ggg1(req)))
Community
  • 1
  • 1
june
  • 51
  • 3
  • [`copy_current_request_context()` doesn't help](https://gist.github.com/6d2150f0eaf793320f6d) to get a request context inside the generator. You could try to create several generators: one for `GET`, another for `POST` that do not use `request` and pass necessary data as parameters e.g., `if request.method=='POST': def ggg_post(url_list): yield "something" return Response(ggg_post(url_list=request.form['username'].splitlines())) else: return ...` – jfs Nov 08 '13 at 11:50

1 Answers1

5

You need to use stream_with_context(). Reference

Suraj Singh
  • 4,041
  • 1
  • 21
  • 36
akg
  • 51
  • 1
  • This solved my issue of using [flask.g](https://flask.palletsprojects.com/en/1.1.x/api/#flask.g) in generator function. – Aamir Rizwan Jun 03 '20 at 14:58