2022-11-15 12:36:07 +00:00
|
|
|
from socketify import App, middleware
|
2022-11-16 19:28:46 +00:00
|
|
|
|
|
|
|
|
2022-11-15 12:22:09 +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"}
|
2022-11-14 15:46:53 +00:00
|
|
|
return None
|
|
|
|
|
2022-11-16 19:28:46 +00:00
|
|
|
|
2022-11-15 12:22:09 +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:
|
2022-11-14 15:46:53 +00:00
|
|
|
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
|
2022-11-14 15:46:53 +00:00
|
|
|
return False
|
|
|
|
|
2022-11-16 19:28:46 +00:00
|
|
|
# returns extra data
|
2022-11-14 15:46:53 +00:00
|
|
|
return user
|
|
|
|
|
2022-11-16 19:28:46 +00:00
|
|
|
|
2022-11-15 12:22:09 +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
|
2022-11-15 12:22:09 +00:00
|
|
|
if isinstance(data, dict):
|
2022-11-16 19:28:46 +00:00
|
|
|
gretting = data.get("greeting", "")
|
|
|
|
data["greeting"] = f"{gretting} from another middie ;)"
|
2022-11-15 12:22:09 +00:00
|
|
|
return data
|
|
|
|
|
2022-11-16 19:28:46 +00:00
|
|
|
|
2022-11-14 15:46:53 +00:00
|
|
|
def home(res, req, user=None):
|
2022-11-16 19:28:46 +00:00
|
|
|
res.cork_end(user.get("greeting", None))
|
|
|
|
|
2022-11-14 15:46:53 +00:00
|
|
|
|
|
|
|
app = App()
|
2022-11-15 12:22:09 +00:00
|
|
|
app.get("/", middleware(auth, another_middie, 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),
|
|
|
|
)
|
2022-11-16 11:06:26 +00:00
|
|
|
app.run()
|
|
|
|
|
2022-11-16 19:28:46 +00:00
|
|
|
# You can also take a loop on MiddlewareRouter in middleware_router.py ;)
|