使用Python和Flask流式传输数据会引发RuntimeError:在请求上下文之外工作

jun*_*une 5 python http flask python-2.7

从问题:

使用Python和Flask流式传输数据

代码运行正常,我想修改函数g(),但请求参数不能传入g(),它引发了一个RuntimeError: working outside of request context.

我已经调试了很长时间,我不知道如何修改它,你能帮助查看代码并解释错误背后的原因吗?

谢谢.

我的代码是:

@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)))
Run Code Online (Sandbox Code Playgroud)

小智 5

您需要使用stream_with_context(). 参考