date in Flask URL

A simple example that works for me:

@app.route('/news/<selected_date>', methods=['GET'])
def my_view(selected_date):

    selected_date = datetime.strptime(selected_date, "%Y-%m-%d").date()

Not out-of-the-box, but you can register your own 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

Using a custom converter has two advantages:

  • You can now trivially build the URL with url_for(); just pass in a date or datetime object for that parameter:

      url_for('news', selected_date=date.today())
    
  • Malformed dates result in a 404 for the URL; e.g. /news/2015-02-29 is not a valid date (there is no February 29th this year), so the route won't match and Flask returns a NotFound response instead.

Tags:

Python

Flask