Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

date in Flask URL

Tags:

python

flask

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'])
like image 543
Eugene Soldatov Avatar asked Jul 28 '15 07:07

Eugene Soldatov


2 Answers

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.

like image 162
Martijn Pieters Avatar answered Sep 24 '22 17:09

Martijn Pieters


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()
like image 32
Matt Healy Avatar answered Sep 21 '22 17:09

Matt Healy