1. 程式人生 > >gunicorn+gevent實現 flask web 應用的並行訪問

gunicorn+gevent實現 flask web 應用的並行訪問

1、  安裝 gevent 和 gunicorn

pip install gevent

pip install gunicorn

2、  建立 gunicorn的配置檔案(.py)

#!/usr/bin/env python

#coding:utf-8

import multiprocessing

bind = "0.0.0.0:5000"

#64-2048

backlog = 2048

workers = multiprocessing.cpu_count()*3

worker_class = "gevent"

#同步響應最長處理時間

timeout = 60

pidfile = "/usr/local/bin/ gunicorn.pid"

accesslog = "/var/log/ gunicorn_access.log"

errorlog = "/var/log/error_msg.log"

capture_output = True

gunicorn 配置見

3、  程式碼

3.1 僅gevent 時(server.py)

from gevent.wsgi import WSGIServer

import gevent

import multiprocessing

from flask import Flask

from flask.ext.restful import Api, Resource, reqparse

def api_construct():

    app = Flask(__name__)

    @app.after_request

    def after_request(response):

        response.headers['Access-Control-Allow-Origin'] = '*'

        return response

    api = Api(app)

api.add_resource(fun, '/v1/', endpoint = 'so')

return app

def main():

    #單程序。不能並行處理請求。

    http_server = WSGIServer(('0.0.0.0',5000), api_construct(), spawn=2, environ={'wsgi.multiprocess': False})

http_server.serve_forever()

if __name__ == "__main__":

    main()

python server.py 即可執行。

僅用gevent 時發現,並未實現併發,如果有一個 url 卡住,其它 url 也不能訪問。網上說 gevent 可以實現併發,有哪位同學知道是怎麼回事,歡迎留言交流。

3.2 改為 gunicorn+gevent方式:

from gevent.wsgi import WSGIServer

import gevent

import multiprocessing

from flask import Flask

from flask.ext.restful import Api, Resource, reqparse

def api_construct():

    app = Flask(__name__)

    @app.after_request

    def after_request(response):

        response.headers['Access-Control-Allow-Origin'] = '*'

        return response

    api = Api(app)

api.add_resource(fun, '/v1/', endpoint = 'so')

return app

application = api_construct()

gunicorn -c config.py server:application

多個程序處理請求,實現併發。

如果所有程序均卡住,那麼服務就不可以用了。有同學知道這種情況怎麼解決嘛?