pet*_*urg 7 python werkzeug flask
我想定义一个包含三个变量组件的url规则,例如:
@app.route('/<var_1>/<var_2>/<var3>/')
Run Code Online (Sandbox Code Playgroud)
但我发现开发服务器在尝试匹配静态文件之前会评估这些规则.所以像:
/static/images/img.jpg
Run Code Online (Sandbox Code Playgroud)
将被我的url规则捕获,而不是转发到内置的静态文件处理程序.有没有办法强制开发服务器首先匹配静态文件?
PS如果规则有两个以上的变量组件,这只是一个问题.
tbi*_*icr 18
这是werkzeug路由优化功能.看Map.add,Map.update和Rule.match_compare_key:
def match_compare_key(self):
"""The match compare key for sorting.
Current implementation:
1. rules without any arguments come first for performance
reasons only as we expect them to match faster and some
common ones usually don't have any arguments (index pages etc.)
2. The more complex rules come first so the second argument is the
negative length of the number of weights.
3. lastly we order by the actual weights.
:internal:
"""
return bool(self.arguments), -len(self._weights), self._weights
Run Code Online (Sandbox Code Playgroud)
有self.arguments- 当前参数,self._weights- 路径深度.
因为'/<var_1>/<var_2>/<var3>/'我们有(True, -3, [(1, 100), (1, 100), (1, 100)]).有(1, 100)- 默认字符串参数,最大长度为100.
因为'/static/<path:filename>'我们有(True, -2, [(0, -6), (1, 200)]).有(0, 1)- 路径非参数字符串长度static,(1, 200)- 路径字符串参数最大长度200.
所以我没有找到任何美妙的方法来设置自己的Map实现Flask.url_map或设置地图规则的优先级.解决方案:
Flask应用程序为app = Flask(static_path='static', static_url_path='/more/then/your/max/variables/path/depth/static').@app.route('/<var_1>/<var_2>/<var3>/')到@app.route('/prefix/<var_1>/<var_2>/<var3>/').@app.route('/<no_static:var_1>/<var_2>/<var3>/').werkzeug.routing,创建自己的地图实现,更改werkzeug.routing.Map为自己的实现,导入flask.因此,正如所tbicr指出的,这种行为是在Werkzeug中深入设置的,并且从Flask处理它并不是一种优雅的方式.我能想到的最好的解决方法是:
定义补充静态文件处理程序,如:
@app.route('/static/<subdir>/<path:filename>/')
def static_subdir(subdir=None, filename=None):
directory = app.config['STATIC_FOLDER'] + subdir
return send_from_directory(directory, filename)
Run Code Online (Sandbox Code Playgroud)
这app.config['STATIC_FOLDER']是运行应用程序的计算机上静态文件夹的完整路径.
现在,这个处理程序捕获了类似的东西/static/images/img.jpg,让我的视图只包含三个变量组件.