问题
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