socketify.py icon indicating copy to clipboard operation
socketify.py copied to clipboard

on_start and on_shutdown not work

Open shaohaiyang opened this issue 1 year ago • 4 comments

Could you please inline code here?

eirnym avatar Jan 11 '24 13:01 eirnym

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

shaohaiyang avatar Jan 11 '24 14:01 shaohaiyang

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

shaohaiyang avatar Jan 12 '24 07:01 shaohaiyang

Thanks for reporting, I probably break this trying to fix lifespan, I really need to push more fixes and CI/CD tests

cirospaciari avatar Jan 12 '24 11:01 cirospaciari

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>.

rafaelclp avatar Jun 22 '24 16:06 rafaelclp