使用cherrpy部署flask

2018-07-09  本文已影响0人  沐辰老爹

引自博客

option1

新建一个hello.py的flask应用文件

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

通过cherrpy部署

from cherrypy import wsgiserver
from hello import app

d = wsgiserver.WSGIPathInfoDispatcher({'/': app})
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8080), d)

if __name__ == '__main__':
   try:
      server.start()
   except KeyboardInterrupt:
      server.stop()

option2

另从github找到Cherrypy server with Flask application

from hello import app
import cherrypy
cherrypy.tree.graft(app.wsgi_app, '/')
cherrypy.config.update({'server.socket_host': '0.0.0.0',
    'server.socket_port': 5000,
    'engine.autoreload.on': False,
})
if __name__ == '__main__':
    cherrypy.engine.start()

总结

以下引用自github的Using Flask with CherryPy to serve static files

假设我们定义第一种方式为option1:option_1 actually uses the entirety of the CherryPy web framework (which their documentation refers to as the APPLICATION layer) to mount your WSGI application - plugins, tools, etc. can be utilized fully. To serve static files with CherryPy you would want to change your commented out code to be something like this:

cherrypy.tree.mount(None, '/static', config={
    '/': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': app.static_folder
    },
})

定义第二种方式为option2:option_2, on the other hand, simply makes use of CherryPy's WSGI server implementation (the CORE layer) to serve your Flask app - it does not use any of the more framework-like aspects of CherryPy. If you are fine with serving your static files through Flask's routing layer as well, you can even remove the WSGIPathInfoDispatcher middleware and directly mount app under the CherryPyWSGIServer. If you want CherryPy to manage the /static route serving then you will want to mount an instance of cherrypy.tools.staticdir.handler under the /static route, like so:

static_handler = tools.staticdir.handler(section='/', dir=app.static_folder)
d = wsgiserver.WSGIPathInfoDispatcher({'/': app, '/static': static_handler})

目前我们尝试用option2!

此外可以尝试nginx+cherrpy+flask的架构在windows下部署服务器,请参考Deploying Nginx + Cherrypy + Flask in Windows platform

上一篇下一篇

猜你喜欢

热点阅读