我正在尝试为六角颜色代码添加过滤器(应该采用:0xff0000或ff0000的格式)到我的瓶子应用程序。
我跟随这个瓶子教程https://bottlepy.org/docs/dev/routing.html:
您可以将自己的过滤器添加到路由器中。您需要的只是一个返回三个元素的函数:正则表达式字符串,可将URL片段转换为python值的可呼叫,以及相反的可可。使用配置字符串将过滤器函数调用为唯一的参数,并可以根据需要解析:
但是每次我调用我的功能:
@app.route('/<color:hexa>')
def call(color):
....
我收到404:
Not found: '/0x0000FF'
也许我是盲人,但我只是不知道我缺少什么。这是我的过滤器:
def hexa_filter(config):
regexp = r'^(0[xX])?[a-fA-F0-9]+$'
def to_python(match):
return int(match, 0)
def to_url(hexNum):
return str(hexNum)
return regexp, to_python, to_url
app.router.add_filter('hexa', hexa_filter)
问题使^
(最终$
)。
您的正则表达式可以用作检查完整URL的较大正则义务 - 因此,较大的正则义务中的^
(有时是$
)没有任何意义。
from bottle import *
app = Bottle()
def hexa_filter(config):
regexp = r'(0[xX])?[a-fA-F0-9]+'
def to_python(match):
return int(match, 16)
def to_url(hexNum):
return str(hexNum)
return regexp, to_python, to_url
app.router.add_filter('hexa', hexa_filter)
@app.route('/<color:hexa>')
def call(color):
return 'color: ' + str(color)
app.run(host='localhost', port=8000)