File: marshmallow_example.py

package info (click to toggle)
python-hug 2.6.0-2.4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,072 kB
  • sloc: python: 8,938; sh: 99; makefile: 17
file content (38 lines) | stat: -rw-r--r-- 965 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"""Example API using marshmallow fields as type annotations.


Requires marshmallow and dateutil.

    $ pip install marshmallow python-dateutil


To run the example:

    $ hug -f examples/marshmallow_example.py

Example requests using HTTPie:

    $ http :8000/dateadd value==1973-04-10 addend==63
    $ http :8000/dateadd value==2015-03-20 addend==525600 unit==minutes
"""
import datetime as dt

import hug
from marshmallow import fields
from marshmallow.validate import Range, OneOf


@hug.get("/dateadd", examples="value=1973-04-10&addend=63")
def dateadd(
    value: fields.DateTime(),
    addend: fields.Int(validate=Range(min=1)),
    unit: fields.Str(validate=OneOf(["minutes", "days"])) = "days",
):
    """Add a value to a date."""
    value = value or dt.datetime.utcnow()
    if unit == "minutes":
        delta = dt.timedelta(minutes=addend)
    else:
        delta = dt.timedelta(days=addend)
    result = value + delta
    return {"result": result}