Flask: Handle catch all url different if path is directory or file

扶醉桌前 提交于 2019-12-08 03:06:29

问题


How can I make a catch all route, that only handles directories and one that handles files?

Below is a simple example

from flask import Flask
app = Flask(__name__)

@app.route('/foo')
def foo_file():
    return 'Queried: foo file'

@app.route('/foo/')
def foo_dir():
    return 'Queried:  foo dir'

@app.route('/<path:path>')
def file(path):
    return 'Queried file: {0}'.format(path)

@app.route('/')
@app.route('/<path:path>/')
def folder(path):
    return 'Queried folder: {0}'.format(path)

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

When I access http:\\127.0.0.1:5000\foo It calls foo_file() and for http:\\127.0.0.1:5000\foo\ it calls foo_dir(). But querying http:\\127.0.0.1:5000\bar and http:\\127.0.0.1:5000\bar\ both call file(). How can I change that?

I know I can check the trailing slash and reroute manually, I was just wondering if there's another way.


回答1:


You could just do this...

@app.route('/<path:path>')
def catch_all(path):
    if path.endswith('/'):
        return handle_folder(path)
    else:
        return handle_file(path)


来源:https://stackoverflow.com/questions/14444769/flask-handle-catch-all-url-different-if-path-is-directory-or-file

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