Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 951
Paul Würtz Avatar asked Nov 24 '18 16:11

Paul Würtz


People also ask

How do you pass parameters in a URL in flask?

In the first one we would use request. args. get('<argument name>') where request is the instance of the class request imported from Flask. Args is the module under which the module GET is present which will enable the retrieve of the parameters.

How do you enter a flask URL?

The url_for() function is used to build a URL to the specific function dynamically. The first argument is the name of the specified function, and then we can pass any number of keyword argument corresponding to the variable part of the URL.

How do I get query parameters in flask?

Check if Query Parameters are Not None This can thankfully easily be done by getting an expected key and checking if it's present in the dictionary! Here - we extract the name and location from the parameter list. If none are present - you may wish to return all of the users, or none at all.

What is URL parameter in flask?

Flask URL parameters is defined as a set of arguments in form of a query string that is passed to a web application through Flask. These parameters get bonded to the URL.

Can you pass a number to a flask route?

So you can pass parameters to your Flask route, can you pass numbers? The example here creates the route /sale/<transaction_id>, where transaction_id is a number. If you want a flask route with multiple parameters that’s possible. For the route /create/<first_name>/<last_name> you can do this: Flask suports HTTP POST requests.

What are routes in flask?

Modern web apps use a technique named routing. This helps the user remember the URLs. For instance, instead of having /booking.php they see /booking/. Instead of /account.asp?id=1234/ they’d see /account/1234/. Routes in Flask are mapped to Python functions. You have already created one route, the ‘/‘ route:

What is an integer path in flask?

integer: This type accepts integers. float: Accepts decimal numbers with decimal points. path: Similar to a string, but with the exception that it permits slashes. What is app route? What are route parameters in Python Flask?


2 Answers

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

like image 137
Paul Würtz Avatar answered Oct 26 '22 05:10

Paul Würtz


The accepted solution does the work for the use case (and got my upvote :); yet if the parameter doesn't conform to the expected format, it will set it to the default value (today) silently, with no feedback to the caller - as this is flask's/werkzeug's intended behavior.

Here's how to use it to validate & return an error if the client has passed an invalid value - piggybacking on OP's solution:

from flask import jsonify

def to_date(date_string): 
    try:
        return datetime.datetime.strptime(date_string, "%Y-%m-%d").date()
    except ValueError:
        raise ValueError('{} is not valid date in the format YYYY-MM-DD'.format(date_string))

@app.route()
def event():
    try:
        ektempo = to_date(request.args.get('start', default = datetime.date.today().isoformat()))
    except ValueError as ex:
        return jsonify({'error': str(ex)}), 400   # jsonify, if this is a json api

like image 42
Todor Minakov Avatar answered Oct 26 '22 03:10

Todor Minakov