Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the datetime format for flask-restful parser?

Let's say that I have following parser inside my get method:

from flask.ext.restful import reqparse

parser = reqparse.RequestParser()
parser.add_argument('when', type=datetime, help='Input wasn\'t valid!')

And then I want to test the said get method with curl...

curl --data "when=[WHAT SHOULD I WRITE HERE?]" localhost:5000/myGet

So the question is, how I should call the get method? I've tried numerous different formats, tried to read rfc228 standard, etc. but I can't figure out the right format.

like image 550
TukeV Avatar asked Oct 30 '14 20:10

TukeV


People also ask

What is Reqparse in flask-RESTful?

Don't worry, if you have code using that now and wish to continue doing so, it's not going to go away any time too soon. Flask-RESTful's request parsing interface, reqparse , is modeled after the argparse interface. It's designed to provide simple and uniform access to any variable on the flask.

What is parser in Flask?

Parsers are responsible for taking the content of the request body as a bytestream, and transforming it into a native Python data representation. Flask API includes a few built-in parser classes and also provides support for defining your own custom parsers.


1 Answers

Kinda late, but I've just been in the same problem, trying to parse a datetime with RequestParser, and sadly the docs are not so helpful for this scenario, so after seeing and testing RequestParser and Argument code, I think I found the problem:

When you use type=datetime in the add_argument method, under the hood it just calls datetime with the arg, like this: datetime(arg), so if your param is a string like this: 2016-07-12T23:13:3, the error will be an integer is required.

In my case, I wanted to parse a string with this format %Y-%m-%dT%H:%M:%S into a datetime object, so I thought to use something like type=datetime.strptime but as you know this method needs a format parameter, so I finally used this workaround:

parser.add_argument('date', type=lambda x: datetime.strptime(x,'%Y-%m-%dT%H:%M:%S'))

As you can see in this way you can use whatever format datetime you want. Also you can use partial functool instead of lambda to get the same result or a named function.

This workaround is in the docs.

like image 80
eyscode Avatar answered Oct 29 '22 21:10

eyscode