本文介绍了Flask:如果路径是目录或文件,则句柄捕获所有url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



下面是一个简单的例子

  from flask import Flask 
app = Flask(__ name__)

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

@ app.route('/ foo /')
def foo_dir():
返回'查询:foo dir'

@ app.route('/< path:path>')
def文件(路径):
return'查询文件:{ 0''。format(path)

@ app.route('/')
@ app.route('/< path:path> /')
def格式(路径)
$ b如果__name__ =='__main__':
app.run()$ b文件夹(路径):
返回查询文件夹:{0} $ b

访问 http:\\127.0.0.1:5000 \foo它调用 foo_file() http:\\127.0.0.1:5000 \foo\ 它调用 foo_dir()。但是查询 http:\\127.0.0.1:5000\bar http:\\\\\\\\\\\\\\\\\\\\\\\\\ \ 都会调用
file()。我知道我可以检查结尾的斜杠和手动重新路由,我只是想知道是否有另一种方式。
我怎么能改变这一点?

$ b $ @如果path.endswith('/'):
返回的是handle_folder(path)$ b $,则返回
def catch_all(path) b else:
return handle_file(path)


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 callfile(). 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.

解决方案

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)

这篇关于Flask:如果路径是目录或文件,则句柄捕获所有url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 13:27