-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
57 lines (37 loc) · 1.45 KB
/
example.py
File metadata and controls
57 lines (37 loc) · 1.45 KB
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
import time
from asyncio import sleep
from typing import TypedDict
from nextpress import Anext, Nextpress, Request, Response
from nextpress.middlewares import json_body_parser
app = Nextpress()
class ApiResponsePayload(TypedDict):
message: str
class DataResponsePayload(TypedDict):
message: str
class DataRequestPayload(TypedDict):
name: str
async def root(response: Response[str]):
await response.send_text("Hello, World!")
async def logger(request: Request, response: Response, anext: Anext):
print(f"{request.method} {request.path}")
response.set_header("X-Processed-Time", str(time.time()))
await anext()
await sleep(5)
print("Logger middleware finished")
async def api(response: Response[ApiResponsePayload], request: Request):
method = request.method
await response.send_json({"message": f"API endpoint accessed with {method} method"})
async def data(
request: Request[DataRequestPayload], response: Response[DataResponsePayload]
):
body = request.body
name = body.get("name", "Guest") if body else "Guest"
body = f"Hello, {name}!"
await response.send_json({"message": body})
async def version(request: Request, response: Response):
version = request.route_params.get("version", "unknown")
await response.send_json({"message": f"API Version: {version}"})
app.get("/", root)
app.get("/api", logger, api)
app.post("/data", json_body_parser, data)
app.get("/api/:version/info", version)