sanic icon indicating copy to clipboard operation
sanic copied to clipboard

Signal event to return context

Open ahopkins opened this issue 3 years ago • 8 comments

Dispatching a signal event can provide a context to pass data into the handler:

    await request.app.dispatch(
        "user.registration.created",
        context={"email": request.json.email}
    )

However, currently if I wait on that same event, I only know that it happened. None of that context is provided.

await app.event("user.registration.created")

To make it more useful, we could instead have that context as a return value:

context = await app.event("user.registration.created")

Or, available in a context manager:

async with await app.event("user.registration.created") as context:
    ...

I am leaning more towards the second option because I think it might make more sense if the object returned has other details about the signal (the path, matched params, etc).

ahopkins avatar Mar 24 '21 12:03 ahopkins

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is incorrect, please respond with an update. Thank you for your contributions.

stale[bot] avatar Mar 02 '22 08:03 stale[bot]

...

ahopkins avatar Mar 02 '22 09:03 ahopkins

@ahopkins Can I try to work on this?

ChihweiLHBird avatar Dec 11 '22 04:12 ChihweiLHBird

Sure, but it might be a v23 project.

ahopkins avatar Dec 11 '22 08:12 ahopkins

Sure, but it might be a v23 project.

Yes, of course.

ChihweiLHBird avatar Dec 13 '22 05:12 ChihweiLHBird

During the investigation, I found the underlying mechanism is asyncio.Event, and asyncio.wait_for(some_event) was used by app.event(). I tried to store the context somewhere when the event is set and remove it when the event is clear, but I later discovered that the event can be clear before the wait_for call finished and makes it impossible to access the stored context. I am blocked by this issue and still looking for a solution. Any suggestion?

ChihweiLHBird avatar Jan 17 '23 03:01 ChihweiLHBird

As I couldn't find a workable solution, I unassigned myself from this. Hope we can find a way to implement it later in the future.

ChihweiLHBird avatar Feb 18 '23 15:02 ChihweiLHBird

I've included a potential fix to this in https://github.com/talljosh/sanic alongside my work on #2826 as it made sense to me to address both these things at the same time. (That branch is not quite complete yet, I'll open a PR when it is.)

talljosh avatar Sep 23 '23 13:09 talljosh