3、Bottle配置动态路由

  包含通配符的路由称为动态路由,动态路由可以同时匹配多个URL。在Bottle中一个简单的通配符由一个用尖括号括起来的名称组成(如)直到接受到下一个 / 为止。例如路由 /hello/ 支持接受 /hello/bob,/hello/jack 等请求,但当使用 /hello、 /hello/ 和 /hello/bob/index 等请求时则会报404错误。

使用通配符
每个通配符都将URL的覆盖部分作为关键字参数传递给请求函数。函数中参数名要和通配符名称一致。

@route('/')
@route('/hello/')
def greet(name):
    return 'Hello ' + name + ' how are you?'

可以包含多个通配符,函数参数要和通配符一致

@route('//')
def hello(action, name):
    ...

过滤器
可以使用通配符过滤器来对通配符进行过滤,形式如下

<name:filter>

其中filter的值可以是

类型 描述
int 匹配(带符号的)数字。
float 和int相似可以匹配小数。
path 以非贪婪的方式匹配所有字符,包括斜杠字符,并可用于匹配多个路径段。
re[:exp] 是否能够在配置字段中指定一个自定义正则表达式。不修改匹配的值。正则表达式写在exp中。

一些典型的过滤器例子

@route('/object/')
def callback(id):
    assert isinstance(id, int)

@route('/show/')
def callback(name):
    assert name.isalpha()

@route('/static/')
def callback(path):
    return static_file(path, ...)

自定义通配符过滤器
  可以将自己的过滤器添加到路由器。您需要一个返回三个元素的函数:正则表达式字符串、将URL片段转换为python值的可调用函数和执行相反操作的可调用函数。调用filter函数时,配置字符串是唯一的参数。
例如:

app = Bottle()
def list_filter(config):
    ''' 匹配用逗号分隔的数字列表 '''
    delimiter = config or ','
    regexp = r'\d+(%s\d)*' % re.escape(delimiter)
    def to_python(match):
        return map(int, match.split(delimiter))
    def to_url(numbers):
        return delimiter.join(map(str, numbers))
    return regexp, to_python, to_url
app.router.add_filter('list', list_filter)

# 使用自定义的过滤器
@app.route('/follow/')
def follow_users(ids):
    for id in ids:
        ...

你可能感兴趣的:(Bottle)