运行Flask + Gevent + Requests时无法“并发”服务

13

我这样启动我的 Flask 应用程序:

#!flask/bin/python
from app import app_instance
from gevent.pywsgi import WSGIServer

#returns and instance of the application - using function to wrap configuration
app = app_instance()
http_server = WSGIServer(('',5000), app)
http_server.serve_forever()

然后当我尝试执行这段代码时,请求调用会一直阻塞,直到原始请求超时。我基本上是在同一个flask应用程序中调用webservice。我对gevent的理解有什么误解吗?线程不会在发生i/o事件时进行切换吗?

@webapp.route("/register", methods=['GET', 'POST'])
def register():
    form = RegistrationForm(request.form, csrf_enabled=False)
    data = None
    if request.method == 'POST' and form.validate():
        data= {'email': form.email, 'auth_token': form.password,
                'name' : form.name, 'auth_provider' : 'APP'}
        r = requests.post('http://localhost:5000', params=data)
        print('status' + str(r.status_code))
        print(r.json())
    return render_template('register.html', form=form)
1个回答

23

我相信问题很可能是你忘记了进行猴子补丁。这将使所有通常的阻塞调用变成利用greenlets的非阻塞调用。要做到这一点,只需在调用任何其他代码之前放置此代码。

from gevent import monkey; monkey.patch_all()

请访问http://www.gevent.org/intro.html#monkey-patching了解更多相关信息。


顺便说一下..我是Python和Monkey Patching的新手。为什么服务器本身不能monkey patch everything?或者这只是一个风格问题,因为Monkey Patching应该显式地而不是隐式地发生? - fansonly
@user1924221,gevent 不知道你需要猴子补丁什么。有时候你可能不想打猴子补丁到所有的地方。Gevent 和 Flask 也是独立的,所以你必须手动处理这些事情。当然,你可以编写自己的库来完成它,这样你就不必再手动操作了。 - ravenac95

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接