gpt4 book ai didi

python - Flask URL 中的日期

转载 作者:太空狗 更新时间:2023-10-29 22:10:58 25 4
gpt4 key购买 nike

是否有正确的方式将日期(例如,'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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com