P3trus P3trus - 2 months ago 5
Python Question

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

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.

Answer

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