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'])
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With