| 1 |
Flask-SQLAlchemy |
| 2 |
================ |
| 3 |
|
| 4 |
Flask-SQLAlchemy is an extension for `Flask`_ that adds support for |
| 5 |
`SQLAlchemy`_ to your application. It aims to simplify using SQLAlchemy |
| 6 |
with Flask by providing useful defaults and extra helpers that make it |
| 7 |
easier to accomplish common tasks. |
| 8 |
|
| 9 |
.. _Flask: https://palletsprojects.com/p/flask/ |
| 10 |
.. _SQLAlchemy: https://www.sqlalchemy.org |
| 11 |
|
| 12 |
|
| 13 |
Installing |
| 14 |
---------- |
| 15 |
|
| 16 |
Install and update using `pip`_: |
| 17 |
|
| 18 |
.. code-block:: text |
| 19 |
|
| 20 |
$ pip install -U Flask-SQLAlchemy |
| 21 |
|
| 22 |
.. _pip: https://pip.pypa.io/en/stable/getting-started/ |
| 23 |
|
| 24 |
|
| 25 |
A Simple Example |
| 26 |
---------------- |
| 27 |
|
| 28 |
.. code-block:: python |
| 29 |
|
| 30 |
from flask import Flask |
| 31 |
from flask_sqlalchemy import SQLAlchemy |
| 32 |
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column |
| 33 |
|
| 34 |
app = Flask(__name__) |
| 35 |
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///example.sqlite" |
| 36 |
|
| 37 |
class Base(DeclarativeBase): |
| 38 |
pass |
| 39 |
|
| 40 |
db = SQLAlchemy(app, model_class=Base) |
| 41 |
|
| 42 |
class User(db.Model): |
| 43 |
id: Mapped[int] = mapped_column(db.Integer, primary_key=True) |
| 44 |
username: Mapped[str] = mapped_column(db.String, unique=True, nullable=False) |
| 45 |
|
| 46 |
with app.app_context(): |
| 47 |
db.create_all() |
| 48 |
|
| 49 |
db.session.add(User(username="example")) |
| 50 |
db.session.commit() |
| 51 |
|
| 52 |
users = db.session.execute(db.select(User)).scalars() |
| 53 |
|
| 54 |
|
| 55 |
Contributing |
| 56 |
------------ |
| 57 |
|
| 58 |
For guidance on setting up a development environment and how to make a |
| 59 |
contribution to Flask-SQLAlchemy, see the `contributing guidelines`_. |
| 60 |
|
| 61 |
.. _contributing guidelines: https://github.com/pallets-eco/flask-sqlalchemy/blob/main/CONTRIBUTING.rst |
| 62 |
|
| 63 |
|
| 64 |
Donate |
| 65 |
------ |
| 66 |
|
| 67 |
The Pallets organization develops and supports Flask-SQLAlchemy and |
| 68 |
other popular packages. In order to grow the community of contributors |
| 69 |
and users, and allow the maintainers to devote more time to the |
| 70 |
projects, `please donate today`_. |
| 71 |
|
| 72 |
.. _please donate today: https://palletsprojects.com/donate |
| 73 |
|
| 74 |
|
| 75 |
Links |
| 76 |
----- |
| 77 |
|
| 78 |
- Documentation: https://flask-sqlalchemy.palletsprojects.com/ |
| 79 |
- Changes: https://flask-sqlalchemy.palletsprojects.com/changes/ |
| 80 |
- PyPI Releases: https://pypi.org/project/Flask-SQLAlchemy/ |
| 81 |
- Source Code: https://github.com/pallets-eco/flask-sqlalchemy/ |
| 82 |
- Issue Tracker: https://github.com/pallets-eco/flask-sqlalchemy/issues/ |
| 83 |
- Website: https://palletsprojects.com/ |
| 84 |
- Twitter: https://twitter.com/PalletsTeam |
| 85 |
- Chat: https://discord.gg/pallets |