【发布时间】:2015-10-26 04:14:36
【问题描述】:
我将瓶子用于显示日历并允许用户指定年份和月份的简单应用程序。定义了以下路线:
'/' # 当前年份和月份
'/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)
【问题讨论】: