Eugene Soldatov Eugene Soldatov - 3 years ago 108
Python Question

date in Flask URL

Whether there is a correct way to pass date (for, example '2015-07-28') as url parameter in flask, like for integer:

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

I need something like:

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

Answer Source

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):
            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:

  • 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download