本文介绍了匹配任意路径或空字符串,而无需添加多个Flask路由装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想捕获所有以前缀/stuff开头的URL,以便以下示例匹配:/users/users//users/604511/edit.目前,我编写了多个规则以匹配所有内容.有没有办法写一个规则来匹配我想要的?

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)

推荐答案

将多个规则分配给同一端点是合理的.这是最直接的解决方案.

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'

如果您实际上想匹配以/users为前缀的任何,例如/users-no-slash/test,请将规则更改为更宽松:regex = r'.*?'.

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'.*?'.

这篇关于匹配任意路径或空字符串,而无需添加多个Flask路由装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:28