python - Flask URL 中的日期

标签 python flask

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

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

我需要这样的东西:

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

最佳答案

不是开箱即用的,但您可以注册自己的 custom converter :

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

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

  • 您现在可以使用 url_for() 轻松构建 URL;只需为该参数传入一个 datedatetime 对象:

      url_for('news', selected_date=date.today())
    
  • 格式不正确的日期会导致 URL 出现 404;例如/news/2015-02-29 不是有效日期(今年没有 2 月 29 日),因此路由不匹配,Flask 返回 NotFound 响应。

关于python - Flask URL 中的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31669864/

相关文章:

python - 类和实例上的描述符行为差异

python - 如何使用 CSV 文件中的元素填充 QComboBox

python 对象列表获取对象而不是值?

python - Flask-SQLAlchemy ORM/GeoAlchemy2 结果为字典,最终为 JSON

html - 代码镜像生成的textarea难以居中

python-3.x - Python Flask 分页错误 :paginated page returned 404

python - 用于客户端 python 接口(interface)/raw_input 的 Twisted Reactor

python - 在 SymPy 中自动填充矩阵元素

python - 如何在 Flask 中跨 View 函数/ session 传递复杂对象

python - 导入错误 : No module named Coreapp (Flask and Google App Engine)