|
|
@ -195,7 +195,7 @@ SQLAlchemy in Flask |
|
|
|
|
|
|
|
|
|
|
|
Many people prefer `SQLAlchemy`_ for database access. In this case it's |
|
|
|
Many people prefer `SQLAlchemy`_ for database access. In this case it's |
|
|
|
encouraged to use a package instead of a module for your flask application |
|
|
|
encouraged to use a package instead of a module for your flask application |
|
|
|
and drop the modules into a separate module (:ref:`larger-applications`). |
|
|
|
and drop the models into a separate module (:ref:`larger-applications`). |
|
|
|
Although that is not necessary but makes a lot of sense. |
|
|
|
Although that is not necessary but makes a lot of sense. |
|
|
|
|
|
|
|
|
|
|
|
There are three very common ways to use SQLAlchemy. I will outline each |
|
|
|
There are three very common ways to use SQLAlchemy. I will outline each |
|
|
@ -225,10 +225,11 @@ Here the example `database.py` module for your application:: |
|
|
|
def init_db(): |
|
|
|
def init_db(): |
|
|
|
Base.metadata.create_all(bind=engine) |
|
|
|
Base.metadata.create_all(bind=engine) |
|
|
|
|
|
|
|
|
|
|
|
To define your models, subclass the `Base` class the above code generated. |
|
|
|
To define your models, just subclass the `Base` class that was created by |
|
|
|
|
|
|
|
the code above. |
|
|
|
|
|
|
|
|
|
|
|
To use SQLAlchemy in a declarative way with your application, you just |
|
|
|
To use SQLAlchemy in a declarative way with your application, you just |
|
|
|
have to put the following code into your application module Flask will |
|
|
|
have to put the following code into your application module. Flask will |
|
|
|
automatically remove database sessions at the end of the request for you:: |
|
|
|
automatically remove database sessions at the end of the request for you:: |
|
|
|
|
|
|
|
|
|
|
|
from yourapplication.database import db_session |
|
|
|
from yourapplication.database import db_session |
|
|
|