【问题标题】:Streaming data with Python and Flask raise RuntimeError: working outside of request context使用 Python 和 Flask 流式传输数据引发 RuntimeError:在请求上下文之外工作
【发布时间】:2013-11-14 08:29:09
【问题描述】:

来自问题:

Streaming data with Python and 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)))

【问题讨论】:

  • copy_current_request_context() doesn't help 在生成器中获取请求上下文。您可以尝试创建多个生成器:一个用于GET,另一个用于POST,它们不使用request并将必要的数据作为参数传递,例如if request.method=='POST': def ggg_post(url_list): yield "something" return Response(ggg_post(url_list=request.form['username'].splitlines())) else: return ...

标签: python http python-2.7 flask


【解决方案1】:

您需要使用stream_with_context()Reference

【讨论】:

  • 这解决了我在生成器函数中使用flask.g 的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-17
  • 2023-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-17
相关资源
最近更新 更多