Flask URL中的日期

Eug*_*tov 6 python flask

是否有正确的方法将日期传递(例如,'2015-07-28')作为烧瓶中的url参数,例如整数:

@app.route("/product/<int:product_id>", methods=['GET', 'POST'])
Run Code Online (Sandbox Code Playgroud)

我需要这样的东西:

@app.route("/news/<date:selected_date>", methods=['GET', 'POST'])
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 12

不是开箱即用的,但您可以注册自己的自定义转换器:

from datetime import datetime
from werkzeug.routing import BaseConverter, ValidationError


class DateConverter(BaseConverter):
    """Extracts a ISO8601 date from the path and validates it."""

    regex = r'\d{4}-\d{2}-\d{2}'

    def to_python(self, value):
        try:
            return datetime.strptime(value, '%Y-%m-%d').date()
        except ValueError:
            raise ValidationError()

    def to_url(self, value):
        return value.strftime('%Y-%m-%d')


app.url_map.converters['date'] = DateConverter
Run Code Online (Sandbox Code Playgroud)

使用自定义转换器有两个优点:

  • 您现在可以通过以下方式轻松构建URL url_for(); 只需为该参数传入一个date或一个datetime对象:

    url_for('news', selected_date=date.today())
    
    Run Code Online (Sandbox Code Playgroud)
  • 格式错误的日期导致URL为404; 例如/news/2015-02-29,不是有效日期(今年2月29日没有),因此路线不匹配,而Flask则返回NotFound响应.