-
Notifications
You must be signed in to change notification settings - Fork 1
/
types_path.py
65 lines (44 loc) · 1.47 KB
/
types_path.py
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#
# Types demo
#
from FlaskSimpleAuth import Blueprint, JsonData, jsonify as json
import pydantic as pyda
types = Blueprint("types", __name__)
@types.get("/scalars", authorize="OPEN")
def get_scalars(i: int = 0, f: float = 0.0, b: bool = False, s: str = ""):
return f"i={i}, f={f}, b={b}, s={s}", 200
@types.get("/json", authorize="OPEN")
def get_json(j: JsonData):
return f"{type(j).__name__}: {j}", 200
# define a constrained int type
class nat(int):
def __new__(cls, val):
if val < 0:
raise ValueError(f"nat value must be positive: {val}")
return super().__new__(cls, val)
@types.get("/nat", authorize="OPEN")
def get_nat(i: nat, j: nat):
return json(i + j), 200
class Character(pyda.BaseModel):
name: str
age: int
@pyda.dataclasses.dataclass
class Personnage:
name: str
# age: nat # DOES NOT WORK
age: int
@types.post("/char", authorize="OPEN")
def post_char(char: Character):
return {"name": char.name, "age": char.age}, 201
@types.post("/pers", authorize="OPEN")
def post_pers(pers: Personnage):
return {"name": pers.name, "age": pers.age}, 201
class ListOfStr(list):
"""A list of strings."""
def __init__(self, l: list[str]):
if not isinstance(l, list) or not all(isinstance(i, str) for i in l):
raise ValueError("expecting list[str]")
super().__init__(l)
@types.get("/ls", authorize="OPEN")
def post_ls(l: ListOfStr):
return {"len": len(l), "all": "/".join(l)}, 200