bottle:全局路由过滤器
bottle: global routing filter
我将 bottle 用于一个显示日历并允许用户指定年份和月份的简单应用程序。定义了以下路由:
'/' # 当前年份和当前月份
'/year' # 年份和当前月份
'/year/month'#年月
但是,无法识别末尾带有额外 / 的路由。例如。 '/2015' 可以,但 '/2015/' 不行。为了克服这个问题,我使用了正则表达式 routing filter。这行得通,但让我为每条路线定义一个模式,然后明确检查路线是否以“/”结尾。我想定义一个全局过滤器,它从请求的末尾删除额外的斜杠 url(如果存在)。
from bottle import route, run, template
import calendar
import time
CAL = calendar.HTMLCalendar(calendar.SUNDAY)
Y, M = time.strftime('%Y %m').split()
@route('/')
@route('/<year:re:\d{4}/?>')
@route('/<year>/<month:re:\d{1,2}/?>')
def cal(year = Y, month = M):
y = year if year[-1] != '/' else year[:-1]
m = month if month[-1] != '/' else month[:-1]
return template(CAL.formatmonth(int(y), int(m)))
run(host='localhost', port=8080, debug=True)
与其创建重复的路由,我建议执行一个严格的 url 模式,urls 以斜杠结尾,并鼓励客户通过从 urls 未结束的重定向来使用它使用斜杠,例如使用以下路线:
@route('<path:re:.+[^/]$>')
def add_slash(path):
return redirect(path + "/")
(顺便说一句,这是 django 的 default behavior)。
Bottle 文档提到了您的问题,这是他们的建议:
add a WSGI middleware that strips trailing slashes from all URLs
或
add a before_request
hook to strip the trailing slashes
两者的例子可以是found in the docs.
我将 bottle 用于一个显示日历并允许用户指定年份和月份的简单应用程序。定义了以下路由:
'/' # 当前年份和当前月份
'/year' # 年份和当前月份
'/year/month'#年月
但是,无法识别末尾带有额外 / 的路由。例如。 '/2015' 可以,但 '/2015/' 不行。为了克服这个问题,我使用了正则表达式 routing filter。这行得通,但让我为每条路线定义一个模式,然后明确检查路线是否以“/”结尾。我想定义一个全局过滤器,它从请求的末尾删除额外的斜杠 url(如果存在)。
from bottle import route, run, template
import calendar
import time
CAL = calendar.HTMLCalendar(calendar.SUNDAY)
Y, M = time.strftime('%Y %m').split()
@route('/')
@route('/<year:re:\d{4}/?>')
@route('/<year>/<month:re:\d{1,2}/?>')
def cal(year = Y, month = M):
y = year if year[-1] != '/' else year[:-1]
m = month if month[-1] != '/' else month[:-1]
return template(CAL.formatmonth(int(y), int(m)))
run(host='localhost', port=8080, debug=True)
与其创建重复的路由,我建议执行一个严格的 url 模式,urls 以斜杠结尾,并鼓励客户通过从 urls 未结束的重定向来使用它使用斜杠,例如使用以下路线:
@route('<path:re:.+[^/]$>')
def add_slash(path):
return redirect(path + "/")
(顺便说一句,这是 django 的 default behavior)。
Bottle 文档提到了您的问题,这是他们的建议:
add a WSGI middleware that strips trailing slashes from all URLs
或
add a
before_request
hook to strip the trailing slashes
两者的例子可以是found in the docs.