在flask(python)中发送post请求时出错

时间:2017-03-31 19:02:00

标签: python-3.x flask

我发送了一个帖子请求到函数,这是一个协程,但我收到了以下错误。

    Traceback (most recent call last):
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1994, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1615, in full_dispatch_request
    return self.finalize_request(rv)
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1630, in finalize_request
    response = self.make_response(rv)
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1740, in make_response
    rv = self.response_class.force_type(rv, request.environ)
  File "/usr/local/lib/python3.4/site-packages/werkzeug/wrappers.py", line 885, in force_type
    response = BaseResponse(*_run_wsgi_app(response, environ))
  File "/usr/local/lib/python3.4/site-packages/werkzeug/wrappers.py", line 57, in _run_wsgi_app
    return _run_wsgi_app(*args)
  File "/usr/local/lib/python3.4/site-packages/werkzeug/test.py", line 884, in run_wsgi_app
    app_rv = app(environ, start_response)
TypeError: 'generator' object is not callable

以下是提交按钮后调用的功能: 函数f()从get请求中获取一些数据,并从响应中返回json。

    @app.route('/submit', methods=['POST'])
    @asyncio.coroutine
    def submit():
       result = yield from f()
       return  render_template('test.html', result=result)


def f()
  response = yield from request('get',...)
  ....

1 个答案:

答案 0 :(得分:0)

您不能将协同程序用作Flask路由,而不是Flask或WSGI协议的工作方式。 WSGI处理每个线程/进程/ eventlet的一个请求/响应。如果您需要执行后台任务,则生成一个线程或使用像Celery这样的任务队列。

可以将包含生成器的响应返回给stream the response。它仍将在一个线程中同步运行。

def stream():
    yield 'thing one'
    yield from other_thing()
    yield 'thing two'

return current_app.response_class(stream())

如果你使用gevent,你可以use eventlets instead of threads来处理每个请求,在这种情况下你可以产生其他的eventlet。这带来了它自身的性能问题,因为所有的eventlet都在一个线程的循环中运行(这也适用于asyncio)。 Gunicorn也支持aiohttp,但Flask没有,尽管它可以让它工作。