forked from 0b01001001/spectree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
starlette_demo.py
86 lines (69 loc) · 1.94 KB
/
starlette_demo.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import uvicorn
from pydantic import BaseModel, Field
from starlette.applications import Starlette
from starlette.endpoints import HTTPEndpoint
from starlette.responses import JSONResponse
from starlette.routing import Mount, Route
from examples.common import File, FileResp, Query
from spectree import Response, SpecTree
spec = SpecTree("starlette")
class Resp(BaseModel):
label: int = Field(
...,
ge=0,
le=9,
)
score: float = Field(
...,
gt=0,
lt=1,
)
class Data(BaseModel):
uid: str
limit: int
vip: bool
@spec.validate(query=Query, json=Data, resp=Response(HTTP_200=Resp), tags=["api"])
async def predict(request):
"""
async api
descriptions about this function
"""
print(request.path_params)
print(request.context)
return JSONResponse({"label": 5, "score": 0.5})
# return PydanticResponse(Resp(label=5, score=0.5))
@spec.validate(form=File, resp=Response(HTTP_200=FileResp), tags=["file-upload"])
async def file_upload(request):
"""
post multipart/form-data demo
demo for 'form'
"""
file = request.context.form.file
return JSONResponse({"filename": file.filename, "type": file.type})
class Ping(HTTPEndpoint):
@spec.validate(tags=["health check", "api"])
def get(self, request):
"""
health check
"""
return JSONResponse({"msg": "pong"})
if __name__ == "__main__":
"""
cmd:
http :8000/ping
http ':8000/api/predict/233?text=hello' vip=true uid=admin limit=1
"""
app = Starlette(
routes=[
Route("/ping", Ping),
Mount(
"/api",
routes=[
Route("/predict/{luck:int}", predict, methods=["POST"]),
Route("/file-upload", file_upload, methods=["POST"]),
],
),
]
)
spec.register(app)
uvicorn.run(app, log_level="info")