API

这部分文档记录了 Flask-SQLAlchemy 里的所有公开的类和函数。

配置

class flask.ext.sqlalchemy.SQLAlchemy(app=None, use_native_unicode=True, session_options=None, metadata=None, query_class=<class 'flask_sqlalchemy.BaseQuery'>, model_class=<class 'flask_sqlalchemy.Model'>)

这个类用于将SQLAlchemy集成控制为1或更多的烧瓶应用。参数的初始化方式对象,它可以立即使用或将根据需要附加到瓶的应用程序。

有两种使用模式的工作原理非常相似。一个是绑定:

app = Flask(__name__)
db = SQLAlchemy(app)

第二种可能性是只创建一次对象并配置:

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    db.init_app(app)
    return app

两者的区别在于,在第一种情况中,方法是 create_all() and drop_all() 将一直工作,但在第二种情况下,flask.Flask.app_context() 必须存在。

默认情况下,Flask-SQLAlchemy将应用一些特定于后端的设置 来改善你的体验。从SQLAlchemy 0.6开始SQLAlchemy 将探测该库是否支持原生unicode。如果它检测到 unicode它将让库处理它,否则它自己做。 有时,这种检测可能会失败,在这种情况下,您可能想要设置 use_native_unicode (or the SQLALCHEMY_NATIVE_UNICODE configuration key) to False. 注意,配置键覆盖 传递给构造函数的值。

这个类还提供了对所有SQLAlchemy函数和类的访问 从sqlalchemy and sqlalchemy.orm模块。所以你可以像这样声明模型:

class User(db.Model):
    username = db.Column(db.String(80), unique=True)
    pw_hash = db.Column(db.String(80))

你仍然可以使用 sqlalchemy and sqlalchemy.orm 直接使用,但是请注意,Flask-SQLAlchemy定制只能通过它的一个实例使用SQLAlchemy 类. 查询类默认为 BaseQuery 对于 db.Query, db.Model.query_class, 和 查询类默认为 query_class 对于db.relationshipdb.backref. 你可以直接通过 sqlalchemysqlalchemy.orm , 默认的查询类是 sqlalchemy.

仔细检查类型

不要对db.table执行type或isinstance检查,因为它模拟表行为,但不是类。db.table暴露了Table接口,但它是一个允许省略元数据的函数。

你也可以定义你自己的SessionExtension实例 定义SQLAlchemy类实例。您可以传递自定义实例 session_extensions关键字。这可以是单一的 SessionExtension实例或SessionExtension实例列表。在 下面的用例中,我们使用SQLAlchemy中的VersionedListener 版本控制的例子。

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))
session_options参数可以用来覆盖会话选项。如果提供了,它就是传递给会话构造函数的参数字典。

0.10新版功能:添加了session_options参数。

0.16新版功能:session_options现在接受scopefunc。它允许指定一个自定义函数,该函数将定义SQLAlchemy会话的范围。

2.1新版功能:添加了元数据参数。这允许在其他非琐碎的事情之间设置自定义命名约定。

Query

The BaseQuery class.

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. It internally calls create_session().

create_session(options)

Creates the session. The default implementation returns a SignallingSession.

New in version 2.0.

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(model, metadata=None)

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

模型

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 绑定多个数据库.

__tablename__

The name of the table in the database. This is required by SQLAlchemy; however, Flask-SQLAlchemy will set it automatically if a model has a primary key defined. If the __table__ or __tablename__ is set explicitly, that will be used instead.

query = None

an instance of query_class. Can be used to query the database for instances of this model.

query_class

the query class used. The query attribute is an instance of this class. By default a BaseQuery is used.

alias of BaseQuery

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 the query_class attribute. This is a subclass of a standard SQLAlchemy Query 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.

first_or_404()

Like first() but aborts with 404 if not found instead of returning None.

get(ident)

Return an instance based on the given primary key identifier, or None if not found.

E.g.:

my_user = session.query(User).get(5)

some_object = session.query(VersionedFoo).get((5, 10))

get() is special in that it provides direct access to the identity map of the owning Session. If the given primary key identifier is present in the local identity map, the object is returned directly from this collection and no SQL is emitted, unless the object has been marked fully expired. If not present, a SELECT is performed in order to locate the object.

get() also will perform a check if the object is present in the identity map and marked as expired - a SELECT is emitted to refresh the object as well as to ensure that the row is still present. If not, ObjectDeletedError is raised.

get() is only used to return a single mapped instance, not multiple instances or individual column constructs, and strictly on a single primary key value. The originating Query must be constructed in this way, i.e. against a single mapped entity, with no additional filtering criterion. Loading options via options() may be applied however, and will be used if the object is not yet locally present.

A lazy-loading, many-to-one attribute configured by relationship(), using a simple foreign-key-to-primary-key criterion, will also use an operation equivalent to get() in order to retrieve the target value from the local identity map before querying the database. See /orm/loading_relationships for further details on relationship loading.

Parameters:ident – A scalar or tuple value representing the primary key. For a composite primary key, the order of identifiers corresponds in most cases to that of the mapped Table object’s primary key columns. For a mapper() that was given the primary key argument during construction, the order of identifiers corresponds to the elements present in this collection.
Returns:The object instance, or None.
get_or_404(ident)

Like get() but aborts with 404 if not found instead of returning None.

paginate(page=None, per_page=None, 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.

If page or per_page are None, they will be retrieved from the request query. If the values are not ints and error_out is true, it will abort with 404. If there is no request or they aren’t in the query, they default to page 1 and 20 respectively.

Returns an Pagination object.

会话

class flask.ext.sqlalchemy.SignallingSession(db, autocommit=False, autoflush=True, app=None, **options)

The signalling session is the default session that Flask-SQLAlchemy uses. It extends the default session system with bind selection and modification tracking.

If you want to use a different session you can override the SQLAlchemy.create_session() function.

New in version 2.0.

New in version 2.1: The binds option was added, which allows a session to be joined to an external transaction.

app = None

The application that this session belongs to.

实用工具

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 the prev() and next() 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.