Match an arbitrary path, or the empty string, without adding multiple Flask route decorators

吃可爱长大的小学妹 提交于 2019-12-18 08:59:03

问题


I want to capture all urls beginning with the prefix /stuff, so that the following examples match: /users, /users/, and /users/604511/edit. Currently I write multiple rules to match everything. Is there a way to write one rule to match what I want?

@blueprint.route('/users')
@blueprint.route('/users/')
@blueprint.route('/users/<path:path>')
def users(path=None):
    return str(path)

回答1:


It's reasonable to assign multiple rules to the same endpoint. That's the most straightforward solution.


If you want one rule, you can write a custom converter to capture either the empty string or arbitrary data beginning with a slash.

from flask import Flask
from werkzeug.routing import BaseConverter

class WildcardConverter(BaseConverter):
    regex = r'(|/.*?)'
    weight = 200

app = Flask(__name__)
app.url_map.converters['wildcard'] = WildcardConverter

@app.route('/users<wildcard:path>')
def users(path):
    return path

c = app.test_client()
print(c.get('/users').data)  # b''
print(c.get('/users-no-prefix').data)  # (404 NOT FOUND)
print(c.get('/users/').data)  # b'/'
print(c.get('/users/400617/edit').data)  # b'/400617/edit'

If you actually want to match anything prefixed with /users, for example /users-no-slash/test, change the rule to be more permissive: regex = r'.*?'.



来源:https://stackoverflow.com/questions/33283869/match-an-arbitrary-path-or-the-empty-string-without-adding-multiple-flask-rout

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