Search code examples
pythondatetimeflaskurl-parameters

Passing a date as a URL parameter to a flask route


I want to filter some database results, for a given url with some date parameter (like this url.com?start=2018-12-12). The normal way to read a parameter is with request.args.get, accessing the value of the underlying ImmutableMultiDict, which gives me the optional arguments default and type.

My first attempt now was this:

@app.route()
def event():
   ektempo = request.args.get('start', default = datetime.date.today(), type = datetime.date)
   ...

Which works for the default parameter, but not for the passed date string, since datetime.date needs three integers as parameters. Normally I would get my date object by datetime.datetime.strptime and a format string. Is there a way to pass a datetime string as a url parameter to flask and cast it pythonicly to datetime.date.

I like the way request.args.get works, but it seems I can not get a datetime.date object from it easily with a given url parameter. Is there another way to acheive it by flask bult-in methods, which verifies the parameter and on no parameter or ValueError gives me the default?


Solution

  • As pointed out by Daniel Roseman, you can pass any function to type, so I just defined a little helper function to do the conversion of the date-string and here is it:

    def toDate(dateString): 
        return datetime.datetime.strptime(dateString, "%Y-%m-%d").date()
    
    @app.route()
    def event():
        ektempo = request.args.get('start', default = datetime.date.today(), type = toDate)
        ...
    

    Yeah, very cool, thanks a lot Daniel, just what I searched for! :)