Using Flask with CherryPy to serve static files

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 13:04:43

Option 1 is high-level CherryPy

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
    },
})

Option 2 is low-level CherryPy

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})

If you want to replace the development server provided inside Werkzeug, I use the following in Flask-Script to replace runserver(). This will however in __main__

def runserver():
    """
    Overwriting the Flask Script runserver() default.
    CherryPy is much more stable than the built-in Flask dev server
    """
    debug_app = DebuggedApplication(app, True)
    cherrypy.tree.graft(debug_app, '/')
    cherrypy.config.update({
        'engine.autoreload_on': True,
        'server.socket_port': 5000,
        'server.socket_host': '0.0.0.0'
    })
    try:
        cherrypy.engine.start()
        cherrypy.engine.block()
    except KeyboardInterrupt:
        cherrypy.engine.stop()

If you do not have DebuggedApplication wrapper the DEBUG = True will not work. You may need to adjust this slightly based on your application. It will also provide Ctrl+C

Joe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!