socketify.py/examples/middleware_router.py

52 wiersze
1.4 KiB
Python
Czysty Zwykły widok Historia

from socketify import App, MiddlewareRouter, middleware
2022-11-16 19:28:46 +00:00
async def get_user(authorization):
if authorization:
2022-11-16 19:28:46 +00:00
# you can do something async here
return {"greeting": "Hello, World"}
return None
2022-11-16 19:28:46 +00:00
async def auth(res, req, data=None):
2022-11-16 19:28:46 +00:00
user = await get_user(req.get_header("authorization"))
if not user:
res.write_status(403).end("not authorized")
2022-11-16 19:28:46 +00:00
# returning Falsy in middlewares just stop the execution of the next middleware
return False
2022-11-16 19:28:46 +00:00
# returns extra data
return user
2022-11-16 19:28:46 +00:00
def another_middie(res, req, data=None):
2022-11-16 19:28:46 +00:00
# now we can mix sync and async and change the data here
if isinstance(data, dict):
2022-11-16 19:28:46 +00:00
gretting = data.get("greeting", "")
data["greeting"] = f"{gretting} from another middie ;)"
return data
2022-11-16 19:28:46 +00:00
def home(res, req, user=None):
res.cork_end(user.get("greeting", None))
app = App()
2022-11-16 19:28:46 +00:00
# you can use an Middleware router to add middlewares to every route you set
auth_router = MiddlewareRouter(app, auth)
auth_router.get("/", home)
2022-11-16 19:28:46 +00:00
# you can also mix middleware() with MiddlewareRouter
auth_router.get("/another", middleware(another_middie, home))
2022-11-16 19:28:46 +00:00
# you can also pass multiple middlewares on the MiddlewareRouter
other_router = MiddlewareRouter(app, auth, another_middie)
other_router.get("/another_way", home)
2022-11-16 19:28:46 +00:00
app.listen(
3000,
lambda config: print("Listening on port http://localhost:%d now\n" % config.port),
)
app.run()