Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple event loops in custom handlers #260

Open
jordaneremieff opened this issue Apr 26, 2022 Discussed in #256 · 1 comment
Open

Multiple event loops in custom handlers #260

jordaneremieff opened this issue Apr 26, 2022 Discussed in #256 · 1 comment
Labels
help wanted Extra attention is needed improvement Improve an existing feature

Comments

@jordaneremieff
Copy link
Collaborator

Discussed in #256

Originally posted by jrobbins-LiveData March 20, 2022
The Mangum doc shows this example of how one might handle a custom event:

def handler(event, context):
    if event.get("some-key"):
        # Do something or return, etc.
        return

    asgi_handler = Mangum(app)
    response = asgi_handler(event, context) # Call the instance with the event arguments

    return response

I need to handle an incoming AWS EventBridge event. I want to invoke the same method that my HTTP API handler is also invoking -- and it is an async method.

Here's what I am using

def handler(event: LambdaEvent, context: LambdaContext) -> dict:
    if "requestContext" in event:
        logger.debug("HTTP API")
        response = fastapi_handler(event, context)
    else:
        logger.debug("Not HTTP API")
        loop = asyncio.get_event_loop()
        response = loop.run_until_complete(app_logic())
    return response

My question(s): Is this the correct pattern to use? In the Mangum source, I see code like this, so I am trying to fit in. My code seems to work, but I read in the Python docs that get_event_loop() is

Deprecated since version 3.10: Deprecation warning is emitted if there is no running event loop. In future Python releases, this function will be an alias of get_running_loop().

Which made me wonder if I were doing this correctly?

@jordaneremieff jordaneremieff added help wanted Extra attention is needed improvement Improve an existing feature labels Apr 26, 2022
@jrobbins-LiveData
Copy link

To be clear, in the simplest case of a Lambda function with a Mangum-based app (e.g. using FastAPI), there only needs to be one event loop, not multiple event loops. The only issue is making it explicit as to whom is responsible for creating the asyncio event loop. The discussion has details of how we might address this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed improvement Improve an existing feature
Projects
None yet
Development

No branches or pull requests

2 participants