- python: 3.12
- windows: win11
pyproject.toml
[project]
name = "fastapi-granian-demo"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.116.1",
"granian[pname,reload,rloop]>=2.4.2",
]
main.py
from contextlib import asynccontextmanager
from fastapi import FastAPI
from granian.constants import Interfaces
from granian.server import Server
@asynccontextmanager
async def lifespan(app: FastAPI):
print("Service startup...")
yield
print("Service shutdown...")
# 资源清理逻辑
print("Resources released, service gracefully shut down")
app = FastAPI(title="FastAPIGranianDemo", lifespan=lifespan)
@app.get("/")
async def root():
return {"message": "Hello World"}
def main():
server = Server(
target="main:app", address="127.0.0.1", port=8000, interface=Interfaces.ASGI
)
# server.stop()
# server.reload()
# 启动服务
server.serve()
if __name__ == "__main__":
main()