2025-04-11 15:04:22 +08:00
|
|
|
from collections.abc import AsyncGenerator
|
2025-04-15 16:36:23 +08:00
|
|
|
from typing import Any, TextIO
|
2025-04-11 15:04:22 +08:00
|
|
|
|
2025-04-09 16:54:34 +08:00
|
|
|
from app import App
|
|
|
|
|
from app.components.http import HTTPComponent
|
2025-04-11 15:04:22 +08:00
|
|
|
from app.components.lifespan import LifespanComponent
|
2025-04-09 16:54:34 +08:00
|
|
|
from app.subroutines.http import HTMLResponse
|
|
|
|
|
|
|
|
|
|
app = App()
|
|
|
|
|
|
2025-04-11 15:04:22 +08:00
|
|
|
lifespan = app.use_component(LifespanComponent())
|
2025-04-09 16:54:34 +08:00
|
|
|
http = app.use_component(HTTPComponent())
|
|
|
|
|
|
|
|
|
|
|
2025-04-11 15:04:22 +08:00
|
|
|
@lifespan.on_context
|
|
|
|
|
async def my_context() -> AsyncGenerator[Any, None]:
|
|
|
|
|
try:
|
|
|
|
|
print("Start!")
|
|
|
|
|
yield
|
|
|
|
|
finally:
|
|
|
|
|
print("Stop!")
|
|
|
|
|
|
|
|
|
|
|
2025-04-15 16:36:23 +08:00
|
|
|
lifespan.add_managed_context(open("teapot.log", "w"), name="teapot_log")
|
2025-04-11 15:04:22 +08:00
|
|
|
|
|
|
|
|
|
2025-04-09 16:54:34 +08:00
|
|
|
@http.route("/teapot", get=True, post=True, put=True, delete=True)
|
|
|
|
|
async def teapot() -> HTMLResponse:
|
|
|
|
|
resp = """
|
|
|
|
|
<!DOCTYPE html>
|
|
|
|
|
<html>
|
|
|
|
|
<head>
|
|
|
|
|
<title>I'm a Teapot!!!</title>
|
|
|
|
|
</head>
|
|
|
|
|
<body>
|
|
|
|
|
<h1>I'm a Teapot!!!</h1>
|
|
|
|
|
<p>I've already told you I'm a teapot.</p>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|
|
|
|
|
"""
|
2025-04-15 16:36:23 +08:00
|
|
|
log = lifespan.get_context("teapot_log", TextIO)
|
|
|
|
|
_ = log.write("teapot\n")
|
|
|
|
|
log.flush()
|
2025-04-09 16:54:34 +08:00
|
|
|
return HTMLResponse(status=418, content=resp)
|