【问题标题】:bottle: global routing filter瓶子:全局路由过滤器
【发布时间】: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)

【问题讨论】:

    标签: python routes bottle


    【解决方案1】:

    我建议不要创建重复的路由,而是强制执行严格的 url 架构,其中 url 以斜杠结尾,并鼓励客户端通过从不以斜杠结尾的 url 重定向来使用它,例如使用以下路由:

    @route('<path:re:.+[^/]$>')
    def add_slash(path):
        return redirect(path + "/")
    

    (顺便说一句,这是 django 的 default behavior)。

    【讨论】:

    • 谢谢!将redirect 添加到导入后它起作用了
    • 使用 HTTP 代码 301(永久重定向):return redirect(path + '/', 301)
    【解决方案2】:

    Bottle 文档提到了您的问题,他们的建议如下:

    添加一个 WSGI 中间件,从所有 URL 中去除尾部斜杠

    添加一个before_request 钩子以去除尾部斜杠

    两者的示例都可以是found in the docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-20
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      相关资源
      最近更新 更多