19

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.

TukeV
  • 641
  • 2
  • 6
  • 13
  • 1
    I just noticed that documentation on flask-restful web page seems to be ahead on it's time and therefore it's possible that the datetime parser hasn't been implemented yet (I'm using version 0.2.12). I can't say for sure. – TukeV Oct 31 '14 at 14:50
  • If you are following documentation, then it might be for the latest build which is not yet in pip, You can clone the github project and check if the problem persist. – Harsh Daftary Nov 25 '14 at 11:19

2 Answers2

29

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.

Seanny123
  • 8,776
  • 13
  • 68
  • 124
eyscode
  • 326
  • 4
  • 7
6

Just an update on Flask-Restful (0.3.5): it is possible to use the own library date and datetime functionality parsing, if ISO 8601 or RFC 822 suffices:

from flask_restful import inputs

parser.add_argument('date', type=inputs.datetime_from_iso8601)

So the request would be,

curl --data "date=2012-01-01T23:30:00+02:00" localhost:5000/myGet

From the docs

null
  • 404
  • 6
  • 12