socketify.py
socketify.py copied to clipboard
on_start and on_shutdown not work
Describe the bug The code can work, but on_start and on_shutdown not running
Could you please inline code here?
from socketify import App
import asyncio
app = App(lifespan=False)
router = app.router()
@app.on_start
async def on_start():
print("wait...")
await asyncio.sleep(1)
print("start!")
@app.on_shutdown
async def on_shutdown():
print("wait...")
await asyncio.sleep(1)
print("shutdown!")
@router.get("/")
def home(res, req, data=None):
res.send({"Hello": "World!"}, headers=(("X-Rate-Limit-Remaining", "10"), (b'Another-Headers', b'Value')))
app.listen(
3000,
lambda config: print("Listening on port http://localhost:%d now\n" % config.port),
)
app.run()
the startup function on_start() don't print wait... and start! words
from socketify import App
import asyncio
def run(app: App):
@app.on_start
async def on_start():
print("wait...")
await asyncio.sleep(1)
print("start!")
@app.on_shutdown
async def on_shutdown():
print("wait...")
await asyncio.sleep(1)
print("shutdown!")
router = app.router()
@router.get("/")
def home(res, req):
res.send("Hello, World!")
when i running above code , the display the ERROR as below:
pypy3 -m socketify xx:run --host 0.0.0.0 --port 8080
wait...
ERROR:root:Uncaught Exception: no running event loop
Listening on http://0.0.0.0:8080 now
Thanks for reporting, I probably break this trying to fix lifespan, I really need to push more fixes and CI/CD tests
I'm testing socketify==0.0.27
.
I'm not sure if this is related to my issue, but probably. I'm using hypercorn + fastapi, but trying to improve performance, so I started looking for alternatives to hypercorn. I tried uvicorn (which works fine, and gets me 2x req/s), and socketify (which breaks the lifespan).
This is a simplified version of my lifespan
, which I pass into fastapi.
@asynccontextmanager
async def lifespan(app):
await asyncio.wait([cb(app) for cb in startup_cbs])
try:
yield
finally:
await asyncio.wait([cb(app) for cb in shutdown_cbs])
I noticed that when I use asyncio
functions (like the wait
above), I get the no running event loop
error.
Indeed, get_running_loop()
raises "RuntimeError: no running event loop"
and get_event_loop()
gives me a <_UnixSelectorEventLoop running=False closed=False debug=False>
.