socketify.py/examples/async.py

48 wiersze
1.3 KiB
Python
Czysty Zwykły widok Historia

from socketify import App, AppOptions, AppListenOptions
import asyncio
app = App()
2022-11-16 19:28:46 +00:00
async def delayed_hello(delay, res):
2022-11-16 19:28:46 +00:00
await asyncio.sleep(delay) # do something async
2022-10-27 12:51:15 +00:00
res.cork_end("Hello with delay!")
2022-11-16 19:28:46 +00:00
def home(res, req):
2022-11-16 19:28:46 +00:00
# request object only lives during the life time of this call
# get parameters, query, headers anything you need here
delay = req.get_query("delay")
delay = 0 if delay == None else float(delay)
2022-11-16 19:28:46 +00:00
# tell response to run this in the event loop
# abort handler is grabbed here, so responses only will be send if res.aborted == False
res.run_async(delayed_hello(delay, res))
2022-11-16 19:28:46 +00:00
async def json(res, req):
2022-11-16 19:28:46 +00:00
# request object only lives during the life time of this call
# get parameters, query, headers anything you need here before first await :)
user_agent = req.get_header("user-agent")
2022-11-16 19:28:46 +00:00
# req maybe will not be available in direct attached async functions after await
await asyncio.sleep(2) # do something async
res.cork_end({"message": "I'm delayed!", "user-agent": user_agent})
def not_found(res, req):
res.write_status(404).end("Not Found")
2022-11-16 19:28:46 +00:00
app.get("/", home)
app.get("/json", json)
app.any("/*", not_found)
2022-11-16 19:28:46 +00:00
app.listen(
3000,
lambda config: print(
"Listening on port http://localhost:%s now\n" % str(config.port)
),
)
2022-11-16 19:28:46 +00:00
app.run()