API¶
This part of the documentation documents all the public classes and functions in Flask-SQLAlchemy.
Configuration¶
-
class
flask.ext.sqlalchemy.
SQLAlchemy
(app=None, use_native_unicode=True, session_options=None)¶ This class is used to control the SQLAlchemy integration to one or more Flask applications. Depending on how you initialize the object it is usable right away or will attach as needed to a Flask application.
There are two usage modes which work very similar. One is binding the instance to a very specific Flask application:
app = Flask(__name__) db = SQLAlchemy(app)
The second possibility is to create the object once and configure the application later to support it:
db = SQLAlchemy() def create_app(): app = Flask(__name__) db.init_app(app) return app
The difference between the two is that in the first case methods like
create_all()
anddrop_all()
will work all the time but in the second case aflask.Flask.request_context()
has to exist.By default Flask-SQLAlchemy will apply some backend-specific settings to improve your experience with them. As of SQLAlchemy 0.6 SQLAlchemy will probe the library for native unicode support. If it detects unicode it will let the library handle that, otherwise do that itself. Sometimes this detection can fail in which case you might want to set use_native_unicode (or the
SQLALCHEMY_NATIVE_UNICODE
configuration key) to False. Note that the configuration key overrides the value you pass to the constructor.This class also provides access to all the SQLAlchemy functions and classes from the
sqlalchemy
andsqlalchemy.orm
modules. So you can declare models like this:class User(db.Model): username = db.Column(db.String(80), unique=True) pw_hash = db.Column(db.String(80))
You can still use
sqlalchemy
andsqlalchemy.orm
directly, but note that Flask-SQLAlchemy customizations are available only through an instance of thisSQLAlchemy
class. Query classes default toBaseQuery
for db.Query, db.Model.query_class, and the default query_class for db.relationship and db.backref. If you use these interfaces throughsqlalchemy
andsqlalchemy.orm
directly, the default query class will be that ofsqlalchemy
.Check types carefully
Don’t perform type or isinstance checks against db.Table, which emulates Table behavior but is not a class. db.Table exposes the Table interface, but is a function which allows omission of metadata.
You may also define your own SessionExtension instances as well when defining your SQLAlchemy class instance. You may pass your custom instances to the session_extensions keyword. This can be either a single SessionExtension instance, or a list of SessionExtension instances. In the following use case we use the VersionedListener from the SQLAlchemy versioning examples.:
from history_meta import VersionedMeta, VersionedListener app = Flask(__name__) db = SQLAlchemy(app, session_extensions=[VersionedListener()]) class User(db.Model): __metaclass__ = VersionedMeta username = db.Column(db.String(80), unique=True) pw_hash = db.Column(db.String(80))
The session_options parameter can be used to override session options. If provided it’s a dict of parameters passed to the session’s constructor.
New in version 0.10: The session_options parameter was added.
New in version 0.16: scopefunc is now accepted on session_options. It allows specifying a custom function which will define the SQLAlchemy session’s scoping.
-
apply_driver_hacks
(app, info, options)¶ This method is called before engine creation and used to inject driver specific hacks into the options. The options parameter is a dictionary of keyword arguments that will then be used to call the
sqlalchemy.create_engine()
function.The default implementation provides some saner defaults for things like pool sizes for MySQL and sqlite. Also it injects the setting of SQLALCHEMY_NATIVE_UNICODE.
-
create_all
(bind='__all__', app=None)¶ Creates all tables.
Changed in version 0.12: Parameters were added
-
create_scoped_session
(options=None)¶ Helper factory method that creates a scoped session.
-
drop_all
(bind='__all__', app=None)¶ Drops all tables.
Changed in version 0.12: Parameters were added
-
engine
¶ Gives access to the engine. If the database configuration is bound to a specific application (initialized with an application) this will always return a database connection. If however the current application is used this might raise a
RuntimeError
if no application is active at the moment.
-
get_app
(reference_app=None)¶ Helper method that implements the logic to look up an application.
-
get_binds
(app=None)¶ Returns a dictionary with a table->engine mapping.
This is suitable for use of sessionmaker(binds=db.get_binds(app)).
-
get_engine
(app, bind=None)¶ Returns a specific engine.
New in version 0.12.
-
get_tables_for_bind
(bind=None)¶ Returns a list of all tables relevant for a bind.
-
init_app
(app)¶ This callback can be used to initialize an application for the use with this database setup. Never use a database in the context of an application not initialized that way or connections will leak.
-
make_connector
(app, bind=None)¶ Creates the connector for a given state and bind.
-
make_declarative_base
()¶ Creates the declarative base.
-
metadata
¶ Returns the metadata
-
reflect
(bind='__all__', app=None)¶ Reflects tables from the database.
Changed in version 0.12: Parameters were added
-
Models¶
-
class
flask.ext.sqlalchemy.
Model
¶ Baseclass for custom user models.
-
__bind_key__
¶ Optionally declares the bind to use. None refers to the default bind. For more information see Multiple Databases with Binds.
-
query
= None¶ an instance of
query_class
. Can be used to query the database for instances of this model.
-
-
class
flask.ext.sqlalchemy.
BaseQuery
(entities, session=None)¶ The default query object used for models, and exposed as
Query
. This can be subclassed and replaced for individual models by setting thequery_class
attribute. This is a subclass of a standard SQLAlchemyQuery
class and has all the methods of a standard query as well.-
all
()¶ Return the results represented by this query as a list. This results in an execution of the underlying query.
-
order_by
(*criterion)¶ apply one or more ORDER BY criterion to the query and return the newly resulting query.
-
limit
(limit)¶ Apply a LIMIT to the query and return the newly resulting query.
-
offset
(offset)¶ Apply an OFFSET to the query and return the newly resulting query.
-
first
()¶ Return the first result of this query or None if the result doesn’t contain any rows. This results in an execution of the underlying query.
-
get
(ident)¶ Return an instance of the object based on the given identifier, or
None
if not found.The
ident
argument is a scalar or tuple of primary key column values in the order of the mapper’s “primary key” setting, which defaults to the list of primary key columns for the mappedTable
.get()
returns only a single mapped instance, orNone
. It is not intended to return rows or scalar column values, therefore theQuery
must be constructed only against a single mapper or mapped class, not a SQL expression or multiple entities. Other usages raise an error.
-
paginate
(page, per_page=20, error_out=True)¶ Returns per_page items from page page. By default it will abort with 404 if no items were found and the page was larger than 1. This behavor can be disabled by setting error_out to False.
Returns an
Pagination
object.
-
Utilities¶
-
class
flask.ext.sqlalchemy.
Pagination
(query, page, per_page, total, items)¶ Internal helper class returned by
BaseQuery.paginate()
. You can also construct it from any other SQLAlchemy query object if you are working with other libraries. Additionally it is possible to pass None as query object in which case theprev()
andnext()
will no longer work.-
has_next
¶ True if a next page exists.
-
has_prev
¶ True if a previous page exists
-
items
= None¶ the items for the current page
-
iter_pages
(left_edge=2, left_current=2, right_current=5, right_edge=2)¶ Iterates over the page numbers in the pagination. The four parameters control the thresholds how many numbers should be produced from the sides. Skipped page numbers are represented as None. This is how you could render such a pagination in the templates:
{% macro render_pagination(pagination, endpoint) %} <div class=pagination> {%- for page in pagination.iter_pages() %} {% if page %} {% if page != pagination.page %} <a href="{{ url_for(endpoint, page=page) }}">{{ page }}</a> {% else %} <strong>{{ page }}</strong> {% endif %} {% else %} <span class=ellipsis>…</span> {% endif %} {%- endfor %} </div> {% endmacro %}
-
next
(error_out=False)¶ Returns a
Pagination
object for the next page.
-
next_num
¶ Number of the next page
-
page
= None¶ the current page number (1 indexed)
-
pages
¶ The total number of pages
-
per_page
= None¶ the number of items to be displayed on a page.
-
prev
(error_out=False)¶ Returns a
Pagination
object for the previous page.
-
prev_num
¶ Number of the previous page.
-
query
= None¶ the unlimited query object that was used to create this pagination object.
-
total
= None¶ the total number of items matching the query
-
-
flask.ext.sqlalchemy.
get_debug_queries
()¶ In debug mode Flask-SQLAlchemy will log all the SQL queries sent to the database. This information is available until the end of request which makes it possible to easily ensure that the SQL generated is the one expected on errors or in unittesting. If you don’t want to enable the DEBUG mode for your unittests you can also enable the query recording by setting the
'SQLALCHEMY_RECORD_QUERIES'
config variable to True. This is automatically enabled if Flask is in testing mode.The value returned will be a list of named tuples with the following attributes:
- statement
- The SQL statement issued
- parameters
- The parameters for the SQL statement
- start_time / end_time
- Time the query started / the results arrived. Please keep in mind that the timer function used depends on your platform. These values are only useful for sorting or comparing. They do not necessarily represent an absolute timestamp.
- duration
- Time the query took in seconds
- context
- A string giving a rough estimation of where in your application query was issued. The exact format is undefined so don’t try to reconstruct filename or function name.