{"id":864,"library":"flask-sqlalchemy","title":"Flask-SQLAlchemy","description":"Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. It simplifies using SQLAlchemy with Flask by setting up common objects and patterns for using those objects, such as a session tied to each web request, models, and engines. The current version is 3.1.1, and it maintains an active development status with regular patch and minor releases.","status":"active","version":"3.1.1","language":"python","source_language":"en","source_url":"https://github.com/pallets-eco/flask-sqlalchemy","tags":["flask","sqlalchemy","orm","database","extension"],"install":[{"cmd":"pip install Flask-SQLAlchemy","lang":"bash","label":"Install Flask-SQLAlchemy"}],"dependencies":[{"reason":"Required Flask web framework; minimum version 2.2 for Flask-SQLAlchemy 3.x.","package":"Flask","optional":false},{"reason":"Required SQLAlchemy ORM; minimum version 2.0.16 for Flask-SQLAlchemy 3.1.x, 1.4.18 for 3.0.x.","package":"SQLAlchemy","optional":false}],"imports":[{"symbol":"SQLAlchemy","correct":"from flask_sqlalchemy import SQLAlchemy"}],"quickstart":{"code":"import os\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column\nfrom sqlalchemy import Integer, String\n\n# Configure a basic Flask app\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URI', 'sqlite:///project.db')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Recommended to disable\n\nclass Base(DeclarativeBase):\n    pass\n\ndb = SQLAlchemy(model_class=Base)\ndb.init_app(app)\n\n# Define a simple model\nclass User(db.Model):\n    id: Mapped[int] = mapped_column(Integer, primary_key=True)\n    username: Mapped[str] = mapped_column(String, unique=True, nullable=False)\n    email: Mapped[str] = mapped_column(String)\n\n    def __repr__(self):\n        return f'<User {self.username}>'\n\nwith app.app_context():\n    db.create_all()\n\n    # Example usage: create, add, commit\n    if not User.query.filter_by(username='testuser').first():\n        new_user = User(username='testuser', email='test@example.com')\n        db.session.add(new_user)\n        db.session.commit()\n        print(f\"Added user: {new_user.username}\")\n\n    # Example usage: query all users\n    users = db.session.execute(db.select(User)).scalars().all()\n    print(\"Current users:\")\n    for user in users:\n        print(f\"- {user.id}: {user.username} ({user.email})\")\n\n    # Example usage: update a user\n    user_to_update = User.query.filter_by(username='testuser').first()\n    if user_to_update:\n        user_to_update.email = 'updated@example.com'\n        db.session.commit()\n        print(f\"Updated user: {user_to_update.username}'s email to {user_to_update.email}\")\n\n    # Example usage: delete a user\n    # user_to_delete = User.query.filter_by(username='testuser').first()\n    # if user_to_delete:\n    #     db.session.delete(user_to_delete)\n    #     db.session.commit()\n    #     print(f\"Deleted user: {user_to_delete.username}\")\n\n    # Verify changes\n    remaining_users = db.session.execute(db.select(User)).scalars().all()\n    print(\"Users after operations:\")\n    for user in remaining_users:\n        print(f\"- {user.id}: {user.username} ({user.email})\")\n","lang":"python","description":"This quickstart demonstrates how to initialize Flask-SQLAlchemy, define a simple ORM model, create database tables, and perform basic CRUD (Create, Read, Update, Delete) operations within a Flask application context. It uses SQLite for simplicity and disables SQLALCHEMY_TRACK_MODIFICATIONS for better performance."},"warnings":[{"fix":"Ensure an active Flask application context (e.g., `with app.app_context():`) when interacting with `db.session` or `db.engine`. Explicitly set `SQLALCHEMY_DATABASE_URI` in your Flask config. Update Flask to >=2.2 and SQLAlchemy to >=1.4.18.","message":"Flask-SQLAlchemy 3.0 introduced significant breaking changes. The session is now scoped to the current application context (instead of thread-local), requiring an active application context for `db.session` and `db.engine` access. `SQLALCHEMY_DATABASE_URI` no longer defaults to an in-memory SQLite database if unset. Minimum Flask version is 2.2, and minimum SQLAlchemy is 1.4.18.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Upgrade Python to 3.8+ and SQLAlchemy to 2.0.16+. Remove any usage of `SQLALCHEMY_COMMIT_ON_TEARDOWN` from your configuration.","message":"Flask-SQLAlchemy 3.1 dropped support for Python 3.7 and bumped the minimum required SQLAlchemy version to 2.0.16. It also removed previously deprecated code and the `SQLALCHEMY_COMMIT_ON_TEARDOWN` configuration key.","severity":"breaking","affected_versions":">=3.1.0"},{"fix":"Use `importlib.metadata.version(\"flask-sqlalchemy\")` or feature detection instead of `db.__version__`.","message":"The `__version__` attribute of the Flask-SQLAlchemy extension instance is deprecated.","severity":"deprecated","affected_versions":">=3.1.1"},{"fix":"Always use `db.session.commit()` to commit changes within a Flask-SQLAlchemy application.","message":"Attempting to call `commit()` directly on a SQLAlchemy session object (e.g., `session.commit()`) instead of the Flask-SQLAlchemy `db.session` object will result in an `AttributeError`.","severity":"gotcha","affected_versions":"All"},{"fix":"Ensure `db.create_all()` is called within an application context when your app starts (e.g., in a CLI command or a 'first run' check). If models have changed, consider using a migration tool like Flask-Migrate instead of repeatedly calling `create_all()`.","message":"Encountering 'OperationalError: (sqlite3.OperationalError) no such table' often indicates a mismatch between your database schema and SQLAlchemy models, or that `db.create_all()` was not called (or failed).","severity":"gotcha","affected_versions":"All"},{"fix":"For counting, use SQLAlchemy's `func.count()`. For example: `db.session.execute(db.select(func.count(User.id))).scalar_one()`.","message":"Using `len(Model.query.all())` to count records is inefficient as it fetches all data into memory before counting. This can lead to performance issues, especially with large tables.","severity":"gotcha","affected_versions":"All"}],"env_vars":null,"last_verified":"2026-05-12T20:31:56.609Z","next_check":"2026-06-27T00:00:00.000Z","problems":[{"fix":"Install the package using pip: `pip install Flask-SQLAlchemy` (or `pip3 install Flask-SQLAlchemy` for Python 3 specific environments). Ensure your IDE or terminal is using the correct Python interpreter and virtual environment.","cause":"This error occurs when the `flask-sqlalchemy` package is not installed in the Python environment being used, or there's an issue with the virtual environment or Python interpreter selection.","error":"ModuleNotFoundError: No module named 'flask_sqlalchemy'"},{"fix":"Wrap the code that interacts with `db` within an application context. For instance, `with app.app_context(): db.create_all()` for standalone scripts or ensure the code runs within a request context in a Flask application.","cause":"This error happens when you try to use Flask-SQLAlchemy's `db` object (or related functionalities like `db.create_all()`) without an active Flask application context, which is required for the extension to know which application it's associated with.","error":"RuntimeError: Working outside of application context."},{"fix":"Ensure your models are correctly defined and then create the database tables by calling `db.create_all()` within an application context. For schema changes in a production environment, use a migration tool like Flask-Migrate.","cause":"This error typically indicates a mismatch between your SQLAlchemy models and the actual database schema; the table referenced in your code does not exist in the connected database, often because `db.create_all()` was not run or migration tools were not used after model changes.","error":"OperationalError: (sqlite3.OperationalError) no such table"},{"fix":"Use the Flask-SQLAlchemy session to commit changes: `db.session.commit()`.","cause":"This error occurs when attempting to call the `commit()` method directly on a raw SQLAlchemy session object, rather than through the Flask-SQLAlchemy `db.session` object.","error":"AttributeError: 'Session' object has no attribute 'commit'"},{"fix":"Ensure you are using Flask-SQLAlchemy version 3.0.2 or later, which includes fixes for SQLAlchemy 2.0 compatibility. If the issue persists, consider temporarily pinning your SQLAlchemy version to `sqlalchemy<2.0`.","cause":"This error usually stems from a compatibility issue between Flask-SQLAlchemy and a newly installed or upgraded SQLAlchemy 2.0+, as the `__all__` attribute was removed in SQLAlchemy 2.0.","error":"AttributeError: module 'sqlalchemy' has no attribute '__all__'"}],"ecosystem":"pypi","meta_description":null,"install_score":100,"install_tag":"verified","quickstart_score":null,"quickstart_tag":null,"pypi_latest":"3.1.1","cli_name":"","install_checks":{"last_tested":"2026-05-12","tag":"verified","tag_description":"installs cleanly on critical runtimes, fast import, recently tested","installed_version":"3.1.1","pypi_latest":"3.1.1","is_stale":false,"results":[{"runtime":"python:3.10-alpine","python_version":"3.10","os_libc":"alpine (musl)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":"wheel","failure_reason":null,"import_side_effects":"clean","install_time_s":null,"import_time_s":1,"mem_mb":26.6,"disk_size":"47.3M"},{"runtime":"python:3.10-alpine","python_version":"3.10","os_libc":"alpine (musl)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":null,"failure_reason":null,"import_side_effects":null,"install_time_s":null,"import_time_s":1,"mem_mb":26.6,"disk_size":"47.3M"},{"runtime":"python:3.10-slim","python_version":"3.10","os_libc":"slim (glibc)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":"wheel","failure_reason":null,"import_side_effects":"clean","install_time_s":4.1,"import_time_s":0.79,"mem_mb":26.6,"disk_size":"46M"},{"runtime":"python:3.10-slim","python_version":"3.10","os_libc":"slim (glibc)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":null,"failure_reason":null,"import_side_effects":null,"install_time_s":null,"import_time_s":0.74,"mem_mb":26.6,"disk_size":"46M"},{"runtime":"python:3.11-alpine","python_version":"3.11","os_libc":"alpine (musl)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":"wheel","failure_reason":null,"import_side_effects":"clean","install_time_s":null,"import_time_s":1.37,"mem_mb":30,"disk_size":"53.2M"},{"runtime":"python:3.11-alpine","python_version":"3.11","os_libc":"alpine (musl)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":null,"failure_reason":null,"import_side_effects":null,"install_time_s":null,"import_time_s":1.5,"mem_mb":30,"disk_size":"53.2M"},{"runtime":"python:3.11-slim","python_version":"3.11","os_libc":"slim (glibc)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":"wheel","failure_reason":null,"import_side_effects":"clean","install_time_s":3.8,"import_time_s":1.26,"mem_mb":30,"disk_size":"52M"},{"runtime":"python:3.11-slim","python_version":"3.11","os_libc":"slim (glibc)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":null,"failure_reason":null,"import_side_effects":null,"install_time_s":null,"import_time_s":1.17,"mem_mb":30,"disk_size":"52M"},{"runtime":"python:3.12-alpine","python_version":"3.12","os_libc":"alpine (musl)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":"wheel","failure_reason":null,"import_side_effects":"clean","install_time_s":null,"import_time_s":1.43,"mem_mb":29.5,"disk_size":"44.3M"},{"runtime":"python:3.12-alpine","python_version":"3.12","os_libc":"alpine (musl)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":null,"failure_reason":null,"import_side_effects":null,"install_time_s":null,"import_time_s":1.49,"mem_mb":29.5,"disk_size":"44.3M"},{"runtime":"python:3.12-slim","python_version":"3.12","os_libc":"slim (glibc)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":"wheel","failure_reason":null,"import_side_effects":"clean","install_time_s":3.4,"import_time_s":1.35,"mem_mb":29.5,"disk_size":"43M"},{"runtime":"python:3.12-slim","python_version":"3.12","os_libc":"slim (glibc)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":null,"failure_reason":null,"import_side_effects":null,"install_time_s":null,"import_time_s":1.46,"mem_mb":29.5,"disk_size":"43M"},{"runtime":"python:3.13-alpine","python_version":"3.13","os_libc":"alpine (musl)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":"wheel","failure_reason":null,"import_side_effects":"clean","install_time_s":null,"import_time_s":1.35,"mem_mb":29.7,"disk_size":"43.9M"},{"runtime":"python:3.13-alpine","python_version":"3.13","os_libc":"alpine (musl)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":null,"failure_reason":null,"import_side_effects":null,"install_time_s":null,"import_time_s":1.39,"mem_mb":29.7,"disk_size":"43.7M"},{"runtime":"python:3.13-slim","python_version":"3.13","os_libc":"slim (glibc)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":"wheel","failure_reason":null,"import_side_effects":"clean","install_time_s":3.5,"import_time_s":1.29,"mem_mb":29.7,"disk_size":"42M"},{"runtime":"python:3.13-slim","python_version":"3.13","os_libc":"slim (glibc)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":null,"failure_reason":null,"import_side_effects":null,"install_time_s":null,"import_time_s":1.42,"mem_mb":29.7,"disk_size":"42M"},{"runtime":"python:3.9-alpine","python_version":"3.9","os_libc":"alpine (musl)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":"wheel","failure_reason":null,"import_side_effects":"clean","install_time_s":null,"import_time_s":0.92,"mem_mb":27.5,"disk_size":"46.1M"},{"runtime":"python:3.9-alpine","python_version":"3.9","os_libc":"alpine (musl)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":null,"failure_reason":null,"import_side_effects":null,"install_time_s":null,"import_time_s":0.99,"mem_mb":27.5,"disk_size":"46.1M"},{"runtime":"python:3.9-slim","python_version":"3.9","os_libc":"slim (glibc)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":"wheel","failure_reason":null,"import_side_effects":"clean","install_time_s":4.8,"import_time_s":0.88,"mem_mb":27.5,"disk_size":"45M"},{"runtime":"python:3.9-slim","python_version":"3.9","os_libc":"slim (glibc)","variant":"Flask-SQLAlchemy","exit_code":0,"wheel_type":null,"failure_reason":null,"import_side_effects":null,"install_time_s":null,"import_time_s":0.81,"mem_mb":27.5,"disk_size":"45M"}]},"quickstart_checks":{"last_tested":"2026-04-24","tag":null,"tag_description":null,"results":[{"runtime":"python:3.10-alpine","exit_code":0},{"runtime":"python:3.10-slim","exit_code":0},{"runtime":"python:3.11-alpine","exit_code":0},{"runtime":"python:3.11-slim","exit_code":0},{"runtime":"python:3.12-alpine","exit_code":0},{"runtime":"python:3.12-slim","exit_code":0},{"runtime":"python:3.13-alpine","exit_code":0},{"runtime":"python:3.13-slim","exit_code":0},{"runtime":"python:3.9-alpine","exit_code":0},{"runtime":"python:3.9-slim","exit_code":0}]}}