[Python] Simplest way to prevent "RuntimeError: Event loop is closed" when using Flask

Discussão em 'Python' iniciado por Stack, Agosto 10, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using Flask with the async flag for my (very simple) web server. (Note that I'm aware of Quart but I don't need it yet) I have a few endpoints, and I accidentally threw a RuntimeError in a service that I didn't catch in the endpoint handler:

    @app.route("/webhook", methods=["POST"])
    async def webhook():
    try:
    # ...
    await my_service.my_method()
    # ^^^--- RuntimeException is thrown here

    except (HTTPException, ValidationError) as e:
    # ^^^--- no catchy catchy here


    and because of this I got a "RuntimeError: Event loop is closed" error and my server started doing all sorts of weird things. I'm new to how coroutines work in Python (I've used them in Kotlin though) so I'm not sure how to properly handle this kind of problem. I've added a global HTTP error handler just in case:

    @app.errorhandler(Exception)
    def handle_exception(e):
    app.logger.error(f"Unhandled exception: {str(e)}")

    # Return JSON response
    return jsonify({
    "error": "Internal server error",
    "message": str(e)
    }), 500


    but will this solve the event loop problem or do I need to manually handle it? I read in the Flask docs that asynchrony is not properly supported, but there weren't much details in there.

    Continue reading...

Compartilhe esta Página