CodexBloom - Programming Q&A Platform

Unexpected TypeError when Using Async Function with Flask and SQLAlchemy

πŸ‘€ Views: 102 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-17
Flask SQLAlchemy asyncio Python

I'm following best practices but I'm trying to create an asynchronous endpoint in my Flask application that interacts with a SQLAlchemy database, but I'm working with a `TypeError: 'coroutine' object is not subscriptable`. This scenario arises when trying to retrieve data from the database using an async function. Here’s a simplified version of my code: ```python from flask import Flask, jsonify from flask_sqlalchemy import SQLAlchemy import asyncio app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) async def get_users(): return await db.session.execute(db.select(User)).scalars().all() @app.route('/users', methods=['GET']) async def users(): users_list = await get_users() return jsonify([{'id': user.id, 'username': user.username} for user in users_list]) if __name__ == '__main__': app.run(debug=True) ``` I've ensured that I am using Flask 2.0 and SQLAlchemy 1.4, which supposedly has async support. I’ve also tried running the app with the `quart` library, which is an async variant of Flask, but I get similar errors. Additionally, I’ve checked that the database setup is correct and that my `User` model is defined properly. When I call the `/users` endpoint, I receive the aforementioned TypeError. I suspect that my scenario might be related to using async with the SQLAlchemy session. Does anyone have a suggestion on how to correctly implement async functions with Flask and SQLAlchemy without running into this TypeError? Any guidance on best practices for setting this up would also be appreciated. I'd be grateful for any help.