CodexBloom - Programming Q&A Platform

Flask application not recognizing async route handlers in Python 3.10

πŸ‘€ Views: 68 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-20
Flask asyncio Python 3.10 Python

I'm learning this framework and I've searched everywhere and can't find a clear answer... I'm working on a Flask application using Python 3.10 and recently tried to implement asynchronous route handlers using `async def`. However, when I run the application, I receive the following behavior: `RuntimeError: Working outside of request context`. My Flask version is 2.0.1 and I have set the app to run in debug mode. Here’s the relevant snippet of my code: ```python from flask import Flask, jsonify import asyncio app = Flask(__name__) @app.route('/async-endpoint') async def async_endpoint(): await asyncio.sleep(1) return jsonify({'message': 'Hello from async endpoint!'}) if __name__ == '__main__': app.run(debug=True) ``` I've also tried using `quart`, which is an async-compatible alternative to Flask, but I really want to keep using Flask for this project. I ensured that I have the `flask` and `hypercorn` packages installed to handle async requests. When I start the server using `hypercorn`, it seems to work, but I'm unsure how to properly integrate async functions with Flask's built-in server. Has anyone else faced this scenario? Is there a specific configuration or method to correctly utilize async/await with Flask 2.0.1? Any help would be greatly appreciated! This is part of a larger application I'm building. My development environment is Debian. Any pointers in the right direction? Any help would be greatly appreciated!