gino package

Submodules

gino.api module

class gino.api.Gino(bind=None, model_classes=None, query_ext=True, schema_ext=True, ext=True, **kwargs)[源代码]

基类:sqlalchemy.sql.schema.MetaData

All-in-one API class of GINO, providing several shortcuts.

This class is a subclass of SQLAlchemy MetaData, therefore its instances can be used as a normal MetaData object, e.g. used in Alembic. In usual cases, you would want to define one global Gino instance, usually under the name of db, representing the database used in your application.

You may define tables in the official way SQLAlchemy core recommended, but more often in GINO we define model classes with db.Model as their parent class to represent tables, for its objective interface and CRUD operations. Please read CRUD for more information.

For convenience, Gino instance delegated all properties publicly exposed by sqlalchemy, so that you can define tables / models without importing sqlalchemy:

id = db.Column(db.BigInteger(), primary_key=True)

Similar to MetaData, a Gino object can bind to a GinoEngine instance, hereby allowing "implicit execution" through the gino extension on Executable or SchemaItem constructs:

await User.query.gino.first()
await db.gino.create_all()

Differently, GINO encourages the use of implicit execution and manages transactional context correctly.

Binding to a connection object is not supported.

To set a bind property, you can simply set your GinoEngine object on db.bind, or set it to None to unbind. However, the creation of engine usually happens at the same time. Therefore, GINO provided several convenient ways doing so:

  1. with_bind() returning an asynchronous context manager:

    async with db.with_bind('postgresql://...') as engine:
    
  2. set_bind() and pop_bind():

    engine = await db.set_bind('postgresql://...')
    await db.pop_bind().close()
    
  3. Directly await on Gino instance:

    db = await gino.Gino('postgresql://...')
    await db.pop_bind().close()
    

注解

SQLAlchemy allows creating the engine by:

metadata.bind = 'postgresql://...'

While in GINO this only sets a string to bind, because creating an engine requires await, which is exactly what set_bind() does.

At last, Gino delegates all query APIs on the bound GinoEngine.

参数:
  • bind -- A GinoEngine instance to bind. Also accepts string or URL, which will be passed to create_engine() when this Gino instance is awaited. Default is None.
  • model_classes -- A tuple of base class and mixin classes to create the Model class. Default is (CRUDModel, ).
  • query_ext -- Boolean value to control the installation of the gino extension on Executable for implicit execution. Default is to install (True).
  • schema_ext -- Boolean value to control the installation of the gino extension on SchemaItem for implicit execution. Default is to install (True).
  • ext -- Boolean value to control the installation of the two gino extensions. False for no extension at all, while it depends on the two individual switches when this is set to True (default).
  • kwargs -- Other arguments accepted by MetaData.
Model

Declarative base class for models, subclass of gino.declarative.Model. Defining subclasses of this class will result new tables added to this Gino metadata.

acquire(*args, **kwargs)[源代码]

A delegate of GinoEngine.acquire().

coroutine all(clause, *multiparams, **params)[源代码]

A delegate of GinoEngine.all().

bind

An GinoEngine to which this Gino is bound.

This is a simple property with no getter or setter hook - what you set is what you get. To achieve the same result as it is in SQLAlchemy - setting a string or URL and getting an engine instance, use set_bind() (or await on this Gino object after setting a string or URL).

compile(elem, *multiparams, **params)[源代码]

A delegate of GinoEngine.compile().

coroutine first(clause, *multiparams, **params)[源代码]

A delegate of GinoEngine.first().

iterate(clause, *multiparams, **params)[源代码]

A delegate of GinoEngine.iterate().

model_base_classes = (<class 'gino.crud.CRUDModel'>,)

Overridable default model classes to build the Model.

Default is (CRUDModel, ).

no_delegate = {'create_engine', 'engine_from_config'}

A set of symbols from sqlalchemy which is not delegated by Gino.

pop_bind()[源代码]

Unbind self, and return the bound engine.

This is usually used in a chained call to close the engine:

await db.pop_bind().close()
返回:GinoEngine or None if self is not bound.
query_executor

The overridable gino extension class on Executable.

This class will be set as the getter method of the property gino on Executable and its subclasses, if ext and query_ext arguments are both True. Default is GinoExecutor.

GinoExecutor 的别名

coroutine scalar(clause, *multiparams, **params)[源代码]

A delegate of GinoEngine.scalar().

schema_visitor

gino.schema.GinoSchemaVisitor 的别名

coroutine set_bind(bind, loop=None, **kwargs)[源代码]

Bind self to the given GinoEngine and return it.

If the given bind is a string or URL, all arguments will be sent to create_engine() to create a new engine, and return it.

返回:GinoEngine
coroutine status(clause, *multiparams, **params)[源代码]

A delegate of GinoEngine.status().

transaction(*args, **kwargs)[源代码]

A delegate of GinoEngine.transaction().

with_bind(bind, loop=None, **kwargs)[源代码]

Shortcut for set_bind() and pop_bind() plus closing engine.

This method accepts the same arguments of create_engine(). This allows inline creating an engine and binding self on enter, and unbinding self and closing the engine on exit:

async with db.with_bind('postgresql://...') as engine:
    # play with engine
返回:An asynchronous context manager.
class gino.api.GinoExecutor(query)[源代码]

基类:object

The default gino extension on Executable constructs for implicit execution.

Instances of this class are created when visiting the gino property of Executable instances (also referred as queries or clause elements), for example:

await User.query.gino.first()

This allows GINO to add the asynchronous query APIs (all(), first(), scalar(), status(), iterate()) to SQLAlchemy query clauses without messing up with existing synchronous ones. Calling these asynchronous query APIs has the same restriction - the relevant metadata (the Gino instance) must be bound to an engine, or an AttributeError will be raised.

注解

Executable clause elements that are completely irrelevant with any table - for example db.select([db.text('now()')]) - has no metadata, hence no engine. Therefore, this will always fail:

await db.select([db.text('now()')]).gino.scalar()

You should use conn.scalar(), engine.scalar() or even db.scalar() in this case.

coroutine all(*multiparams, **params)[源代码]

Returns engine.all() with this query as the first argument, and other arguments followed, where engine is the GinoEngine to which the metadata (Gino) is bound, while metadata is found in this query.

coroutine first(*multiparams, **params)[源代码]

Returns engine.first() with this query as the first argument, and other arguments followed, where engine is the GinoEngine to which the metadata (Gino) is bound, while metadata is found in this query.

iterate(*multiparams, **params)[源代码]

Returns engine.iterate() with this query as the first argument, and other arguments followed, where engine is the GinoEngine to which the metadata (Gino) is bound, while metadata is found in this query.

load(value)[源代码]

Shortcut to set execution option loader in a chaining call.

For example to load Book instances with their authors:

query = Book.join(User).select()
books = await query.gino.load(Book.load(author=User)).all()

Read execution_options() for more information.

model(model)[源代码]

Shortcut to set execution option model in a chaining call.

Read execution_options() for more information.

query

Get back the chained Executable.

In a chained query calls, occasionally the previous query clause is needed after a .gino. chain, you can use .query. to resume the chain back. For example:

await User.query.gino.model(FOUser).query.where(...).gino.all()
return_model(switch)[源代码]

Shortcut to set execution option return_model in a chaining call.

Read execution_options() for more information.

coroutine scalar(*multiparams, **params)[源代码]

Returns engine.scalar() with this query as the first argument, and other arguments followed, where engine is the GinoEngine to which the metadata (Gino) is bound, while metadata is found in this query.

coroutine status(*multiparams, **params)[源代码]

Returns engine.status() with this query as the first argument, and other arguments followed, where engine is the GinoEngine to which the metadata (Gino) is bound, while metadata is found in this query.

timeout(timeout)[源代码]

Shortcut to set execution option timeout in a chaining call.

Read execution_options() for more information.

gino.crud module

class gino.crud.Alias(model, *args, **kwargs)[源代码]

基类:object

Experimental proxy for table alias on model.

load(*column_names, **relationships)[源代码]
on(on_clause)[源代码]
class gino.crud.CRUDModel(**values)[源代码]

基类:gino.declarative.Model

The base class for models with CRUD support.

Don't inherit from this class directly, because it has no metadata. Use db.Model instead.

classmethod alias(*args, **kwargs)[源代码]

Experimental proxy for table alias on model.

append_where_primary_key(q)[源代码]

Append where clause to locate this model instance by primary on the given query, and return the new query.

This is mostly used internally in GINO, but also available for such usage:

await user.append_where_primary_key(User.query).gino.first()

which is identical to:

await user.query.gino.first()

0.7.6 版后已移除: Use lookup() instead.

coroutine create(bind=None, timeout=<object object>, **values)

This create behaves a bit different on model classes compared to model instances.

On model classes, create will create a new model instance and insert it into database. On model instances, create will just insert the instance into the database.

Under the hood create() uses INSERT ... RETURNING ... to create the new model instance and load it with database default data if not specified.

Some examples:

user1 = await User.create(name='fantix', age=32)
user2 = User(name='gino', age=42)
await user2.create()
参数:
  • bind -- A GinoEngine to execute the INSERT statement with, or None (default) to use the bound engine on the metadata (Gino).
  • timeout -- Seconds to wait for the database to finish executing, None for wait forever. By default it will use the timeout execution option value if unspecified.
  • values -- Keyword arguments are pairs of attribute names and their initial values. Only available when called on a model class.
返回:

The instance of this model class (newly created or existing).

delete

Similar to update(), this delete is also different on model classes than on model instances.

On model classes delete is an attribute of type Delete for massive deletes, for example:

await User.delete.where(User.enabled.is_(False)).gino.status()

Similarly you can add a returning() clause to the query and it shall return the deleted rows as model objects.

And on model instances, delete() is a method to remove the corresponding row in the database of this model instance. and returns the status returned from the database:

print(await user.delete())  # e.g. prints DELETE 1

注解

delete() only removes the row from database, it does not affect the current model instance.

参数:
  • bind -- An optional GinoEngine if current metadata (Gino) has no bound engine, or specifying a different GinoEngine to execute the DELETE.
  • timeout -- Seconds to wait for the database to finish executing, None for wait forever. By default it will use the timeout execution option value if unspecified.
classmethod distinct(*columns)[源代码]

Experimental loader feature to yield only distinct instances by given columns.

coroutine get(ident, bind=None, timeout=<object object>)[源代码]

Get an instance of this model class by primary key.

For example:

user = await User.get(request.args.get('user_id'))
参数:
  • ident -- Value of the primary key. For composite primary keys this should be a tuple of values for all keys in database order, or a dict of names (or position numbers in database order starting from zero) of all primary keys to their values.
  • bind -- A GinoEngine to execute the INSERT statement with, or None (default) to use the bound engine on the metadata (Gino).
  • timeout -- Seconds to wait for the database to finish executing, None for wait forever. By default it will use the timeout execution option value if unspecified.
返回:

An instance of this model class, or None if no such row.

classmethod load(*column_names, **relationships)[源代码]

Populates a loader.Loader instance to be used by the loader execution option in order to customize the loading behavior to load specified fields into instances of this model.

The basic usage of this method is to provide the loader execution option (if you are looking for reloading the instance from database, check get() or query) for a given query.

This method takes both positional arguments and keyword arguments with very different meanings. The positional arguments should be column names as strings, specifying only these columns should be loaded into the model instance (other values are discarded even if they are retrieved from database). Meanwhile, the keyword arguments should be loaders for instance attributes. For example:

u = await User.query.gino.load(User.load('id', 'name')).first()

小技巧

gino.load is a shortcut for setting the execution option loader.

This will populate a User instance with only id and name values, all the rest are simply None even if the query actually returned all the column values.

q = User.join(Team).select()
u = await q.gino.load(User.load(team=Team)).first()

This will load two instances of model User and Team, returning the User instance with u.team set to the Team instance.

Both positional and keyword arguments can be used ath the same time. If they are both omitted, like Team.load(), it is equivalent to just Team as a loader.

Additionally, a loader.Loader instance can also be used to generate queries, as its structure is usually the same as the query:

u = await User.load(team=Team).query.gino.first()

This generates a query like this:

SELECT users.xxx, ..., teams.xxx, ...
  FROM users LEFT JOIN teams
    ON ...

The Loader delegates attributes on the query, so .query can be omitted. The LEFT JOIN is built-in behavior, while the ON clause is generated based on foreign key. If there is no foreign key, or the condition should be customized, you can use this:

u = await User.load(
    team=Team.on(User.team_id == Team.id)).gino.first()

And you can use both load() and on() at the same time in a chain, in whatever order suits you.

lookup()[源代码]

Generate where-clause expression to locate this model instance.

By default this method uses current values of all primary keys, and you can override it to behave differently. Most instance-level CRUD operations depend on this method internally. Particularly while lookup() is called in update(), the where condition is used in UpdateRequest.apply(), so that queries like UPDATE ... SET id = NEW WHERE id = OLD could work correctly.

返回:

0.7.6 新版功能.

classmethod none_as_none(enabled=True)[源代码]
classmethod on(on_clause)[源代码]

Customize the on-clause for the auto-generated outer join query.

注解

This has no effect when provided as the loader execution option for a given query.

参见

load()

query

Get a SQLAlchemy query clause of the table behind this model. This equals to sqlalchemy.select([self.__table__]). If this attribute is retrieved on a model instance, then a where clause to locate this instance by its primary key is appended to the returning query clause. This model type is set as the execution option model in the returning clause, so by default the query yields instances of this model instead of database rows.

select()

Build a query to retrieve only specified columns from this table.

This method accepts positional string arguments as names of attributes to retrieve, and returns a Select for query. The returning query object is always set with two execution options:

  1. model is set to this model type
  2. return_model is set to False

So that by default it always return rows instead of model instances, while column types can be inferred correctly by the model option.

For example:

async for row in User.select('id', 'name').gino.iterate():
    print(row['id'], row['name'])

If select() is invoked on a model instance, then a WHERE clause to locate this instance by its primary key is appended to the returning query clause. This is useful when you want to retrieve a latest value of a field on current model instance from database:

db_age = await user.select('age').gino.scalar()
to_dict()[源代码]

Convenient method to generate a dict from this model instance.

Keys will be attribute names, while values are loaded from memory (not from database). If there are JSONProperty attributes in this model, their source JSON field will not be included in the returning dict - instead the JSON attributes will be.

参见

json_support

update

This update behaves quite different on model classes rather than model instances.

On model classes, update is an attribute of type Update for massive updates, for example:

await User.update.values(enabled=True).where(...).gino.status()

Like query, the update query also has the model execution option of this model, so if you use the returning() clause, the query shall return model objects.

However on model instances, update() is a method which accepts keyword arguments only and returns an UpdateRequest to update this single model instance. The keyword arguments are pairs of attribute names and new values. This is the same as UpdateRequest.update(), feel free to read more about it. A normal usage example would be like this:

await user.update(name='new name', age=32).apply()

Here, the await ... apply() executes the actual UPDATE SQL in the database, while user.update() only makes changes in the memory, and collect all changes into an UpdateRequest instance.

class gino.crud.UpdateRequest(instance: gino.crud.CRUDModel)[源代码]

基类:object

A collection of attributes and their new values to update on one model instance.

UpdateRequest instances are created by CRUDModel.update, don't instantiate manually unless required. Every UpdateRequest instance is bound to one model instance, all updates are for that one specific model instance and its database row.

coroutine apply(bind=None, timeout=<object object>)[源代码]

Apply pending updates into database by executing an UPDATE SQL.

参数:
  • bind -- A GinoEngine to execute the SQL, or None (default) to use the bound engine in the metadata.
  • timeout -- Seconds to wait for the database to finish executing, None for wait forever. By default it will use the timeout execution option value if unspecified.
返回:

self for chaining calls.

update(**values)[源代码]

Set given attributes on the bound model instance, and add them into the update collections for apply().

Given keyword-only arguments are pairs of attribute names and values to update. This is not a coroutine, calling update() will have instant effect on the bound model instance - its in-memory values will be updated immediately. Therefore this can be used individually as a shortcut to update several attributes in a batch:

user.update(age=32, disabled=True)

update() returns self for chaining calls to either apply() or another update(). If one attribute is updated several times by the same UpdateRequest, then only the last value is remembered for apply().

Updated values can be SQLAlchemy expressions, for example an atomic increment for user balance looks like this:

await user.update(balance=User.balance + 100).apply()

注解

Expression values will not affect the in-memory attribute value on update() before apply(), because it has no knowledge of the latest value in the database. After apply() the new value will be automatically reloaded from database with RETURNING clause.

gino.declarative module

class gino.declarative.ColumnAttribute(prop_name, column)[源代码]

基类:object

class gino.declarative.Model[源代码]

基类:object

gino.declarative.declarative_base(metadata, model_classes=(<class 'gino.declarative.Model'>, ), name='Model')[源代码]
gino.declarative.declared_attr(m)[源代码]

Mark a class-level method as a factory of attribute.

This is intended to be used as decorators on class-level methods of a Model class. When initializing the class as well as its subclasses, the decorated factory method will be called for each class, the returned result will be set on the class in place of the factory method under the same name.

@declared_attr is implemented differently than declared_attr of SQLAlchemy, but they are both more often used on mixins to dynamically declare indices or constraints (also works for column and __table_args__, or even normal class attributes):

class TrackedMixin:
    created = db.Column(db.DateTime(timezone=True))

    @db.declared_attr
    def unique_id(cls):
        return db.Column(db.Integer())

    @db.declared_attr
    def unique_constraint(cls):
        return db.UniqueConstraint('unique_id')

    @db.declared_attr
    def poly(cls):
        if cls.__name__ == 'Thing':
            return db.Column(db.Unicode())

    @db.declared_attr
    def __table_args__(cls):
        if cls.__name__ == 'Thing':
            return db.UniqueConstraint('poly'),

注解

This doesn't work if the model already had a __table__.

class gino.declarative.InvertDict(*args, **kwargs)[源代码]

基类:dict

invert_get(key, default=None)[源代码]

gino.engine module

class gino.engine.GinoConnection(dialect, sa_conn, stack=None)[源代码]

基类:object

Represents an actual database connection.

This is the root of all query API like all(), first(), scalar() or status(), those on engine or query are simply wrappers of methods in this class.

Usually instances of this class are created by GinoEngine.acquire().

注解

GinoConnection may refer to zero or one underlying database connection - when a GinoConnection is acquired with lazy=True, the underlying connection may still be in the pool, until a query API is called or get_raw_connection() is called.

Oppositely, one underlying database connection can be shared by many GinoConnection instances when they are acquired with reuse=True. The actual database connection is only returned to the pool when the root GinoConnection is released. Read more in GinoEngine.acquire() method.

coroutine all(clause, *multiparams, **params)[源代码]

Runs the given query in database, returns all results as a list.

This method accepts the same parameters taken by SQLAlchemy execute(). You can pass in a raw SQL string, or any SQLAlchemy query clauses.

If the given query clause is built by CRUD models, then the returning rows will be turned into relevant model objects (Only one type of model per query is supported for now, no relationship support yet). See execution_options() for more information.

If the given parameters are parsed as "executemany" - bulk inserting multiple rows in one call for example, the returning result from database will be discarded and this method will return None.

dialect

The Dialect in use, inherited from the engine created this connection.

execution_options(**opt)[源代码]

Set non-SQL options for the connection which take effect during execution.

This method returns a copy of this GinoConnection which references the same underlying database connection, but with the given execution options set on the copy. Therefore, it is a good practice to discard the copy immediately after use, for example:

row = await conn.execution_options(model=None).first(User.query)

This is very much the same as SQLAlchemy execution_options(), it actually does pass the execution options to the underlying SQLAlchemy Connection. Furthermore, GINO added a few execution options:

参数:
  • return_model -- Boolean to control whether the returning results should be loaded into model instances, where the model class is defined in another execution option model. Default is True.
  • model -- Specifies the type of model instance to create on return. This has no effect if return_model is set to False. Usually in queries built by CRUD models, this execution option is automatically set. For now, GINO only supports loading each row into one type of model object, relationships are not supported. Please use multiple queries for that. None for no postprocessing (default).
  • timeout -- Seconds to wait for the query to finish. None for no time out (default).
  • loader --

    A loader expression to load the database rows into specified objective structure. It can be either:

    • A model class, so that the query will yield model instances of this class. It is your responsibility to make sure all the columns of this model is selected in the query.
    • A Column instance, so that each result will be only a single value of this column. Please note, if you want to achieve fetching the very first value, you should use first() instead of scalar(). However, using directly scalar() is a more direct way.
    • A tuple nesting more loader expressions recursively.
    • A callable() function that will be called for each row to fully customize the result. Two positional arguments will be passed to the function: the first is the row instance, the second is a context object which is only present if nested else None.
    • A Loader instance directly.
    • Anything else will be treated as literal values thus returned as whatever they are.
coroutine first(clause, *multiparams, **params)[源代码]

Runs the given query in database, returns the first result.

If the query returns no result, this method will return None.

See all() for common query comments.

coroutine get_raw_connection(*, timeout=None)[源代码]

Get the underlying database connection, acquire one if none present.

参数:timeout -- Seconds to wait for the underlying acquiring
返回:Underlying database connection instance depending on the dialect in use
Raises:TimeoutError if the acquiring timed out
iterate(clause, *multiparams, **params)[源代码]

Creates a server-side cursor in database for large query results.

Cursors must work within transactions:

async with conn.transaction():
    async for user in conn.iterate(User.query):
        # handle each user without loading all users into memory

Alternatively, you can manually control how the cursor works:

async with conn.transaction():
    cursor = await conn.iterate(User.query)
    user = await cursor.next()
    users = await cursor.many(10)

Read more about how Cursor works.

Similarly, this method takes the same parameters as all().

coroutine prepare(clause)[源代码]
raw_connection

The current underlying database connection instance, type depends on the dialect in use. May be None if self is a lazy connection.

coroutine release(*, permanent=True)[源代码]

Returns the underlying database connection to its pool.

If permanent=False, this connection will be set in lazy mode with underlying database connection returned, the next query on this connection will cause a new database connection acquired. This is useful when this connection may still be useful again later, while some long-running I/O operations are about to take place, which should not take up one database connection or even transaction for that long time.

Otherwise with permanent=True (default), this connection will be marked as closed after returning to pool, and be no longer usable again.

If this connection is a reusing connection, then only this connection is closed (depending on permanent), the reused underlying connection will not be returned back to the pool.

Practically it is recommended to return connections in the reversed order as they are borrowed, but if this connection is a reused connection with still other opening connections reusing it, then on release the underlying connection will be returned to the pool, with all the reusing connections losing an available underlying connection. The availability of further operations on those reusing connections depends on the given permanent value.

coroutine scalar(clause, *multiparams, **params)[源代码]

Runs the given query in database, returns the first result.

If the query returns no result, this method will return None.

See all() for common query comments.

schema_for_object = <sqlalchemy.sql.schema._SchemaTranslateMap object>

A SQLAlchemy compatibility attribute, don't use it for now, it bites.

coroutine status(clause, *multiparams, **params)[源代码]

Runs the given query in database, returns the query status.

The returning query status depends on underlying database and the dialect in use. For asyncpg it is a string, you can parse it like this: https://git.io/v7oze

transaction(*args, **kwargs)[源代码]

Starts a database transaction.

There are two ways using this method: managed as an asynchronous context manager:

async with conn.transaction() as tx:
    # run query in transaction

or manually awaited:

tx = await conn.transaction()
try:
    # run query in transaction
    await tx.commit()
except Exception:
    await tx.rollback()
    raise

Where the tx is an instance of the GinoTransaction class, feel free to read more about it.

In the first managed mode, the transaction is automatically committed on exiting the context block, or rolled back if an exception was raised which led to the exit of the context. In the second manual mode, you'll need to manually call the commit() or rollback() methods on need.

If this is a lazy connection, entering a transaction will cause a new database connection acquired if none was present.

Transactions may support nesting depending on the dialect in use. For example in asyncpg, starting a second transaction on the same connection will create a save point in the database.

For now, the parameters are directly passed to underlying database driver, read asyncpg.connection.Connection.transaction() for asyncpg.

class gino.engine.GinoEngine(dialect, pool, loop, logging_name=None, echo=None, execution_options=None)[源代码]

基类:object

Connects a Pool and Dialect together to provide a source of database connectivity and behavior.

A GinoEngine object is instantiated publicly using the gino.create_engine() function or db.set_bind() method.

acquire(*, timeout=None, reuse=False, lazy=False, reusable=True)[源代码]

Acquire a connection from the pool.

There are two ways using this method - as an asynchronous context manager:

async with engine.acquire() as conn:
    # play with the connection

which will guarantee the connection is returned to the pool when leaving the async with block; or as a coroutine:

conn = await engine.acquire()
try:
    # play with the connection
finally:
    await conn.release()

where the connection should be manually returned to the pool with conn.release().

Within the same context (usually the same Task, see also Transaction), a nesting acquire by default re

参数:
  • timeout -- Block up to timeout seconds until there is one free connection in the pool. Default is None - block forever until succeeded. This has no effect when lazy=True, and depends on the actual situation when reuse=True.
  • reuse -- Reuse the latest reusable acquired connection (before it's returned to the pool) in current context if there is one, or borrow a new one if none present. Default is False for always borrow a new one. This is useful when you are in a nested method call series, wishing to use the same connection without passing it around as parameters. See also: Transaction. A reusing connection is not reusable even if reusable=True. If the reused connection happened to be a lazy one, then the reusing connection is lazy too.
  • lazy -- Don't acquire the actual underlying connection yet - do it only when needed. Default is False for always do it immediately. This is useful before entering a code block which may or may not make use of a given connection object. Feeding in a lazy connection will save the borrow-return job if the connection is never used. If setting reuse=True at the same time, then the reused connection - if any - applies the same laziness. For example, reusing a lazy connection with lazy=False will cause the reused connection to acquire an underlying connection immediately.
  • reusable -- Mark this connection as reusable or otherwise. This has no effect if it is a reusing connection. All reusable connections are placed in a stack, any reusing acquire operation will always reuse the top (latest) reusable connection. One reusable connection may be reused by several reusing connections - they all share one same underlying connection. Acquiring a connection with reusable=False and reusing=False makes it a cleanly isolated connection which is only referenced once here.
返回:

A GinoConnection object.

coroutine all(clause, *multiparams, **params)[源代码]

Acquires a connection with reuse=True and runs all() on it. reuse=True means you can safely do this without borrowing more than one underlying connection:

async with engine.acquire():
    await engine.all('SELECT ...')

The same applies for other query methods.

coroutine close()[源代码]

Close the engine, by closing the underlying pool.

compile(clause, *multiparams, **params)[源代码]

A shortcut for compile() on the dialect, returns raw SQL string and parameters according to the rules of the dialect.

connection_cls

Customizes the connection class to use, default is GinoConnection.

GinoConnection 的别名

current_connection

Gets the most recently acquired reusable connection in the context. None if there is no such connection.

返回:GinoConnection
dialect

Read-only property for the Dialect of this engine.

coroutine first(clause, *multiparams, **params)[源代码]

Runs first(), See all().

iterate(clause, *multiparams, **params)[源代码]

Creates a server-side cursor in database for large query results.

This requires that there is a reusable connection in the current context, and an active transaction is present. Then its GinoConnection.iterate() is executed and returned.

raw_pool

Read-only access to the underlying database connection pool instance. This depends on the actual dialect in use, Pool of asyncpg for example.

coroutine scalar(clause, *multiparams, **params)[源代码]

Runs scalar(), See all().

coroutine status(clause, *multiparams, **params)[源代码]

Runs status(). See also all().

transaction(*args, timeout=None, reuse=True, reusable=True, **kwargs)[源代码]

Borrows a new connection and starts a transaction with it.

Different to GinoConnection.transaction(), transaction on engine level supports only managed usage:

async with engine.transaction() as tx:
    # play with transaction here

Where the implicitly acquired connection is available as tx.connection.

By default, transaction() acquires connection with reuse=True and reusable=True, that means it by default tries to create a nested transaction instead of a new transaction on a new connection. You can change the default behavior by setting these two arguments.

The other arguments are the same as transaction() on connection.

返回:A asynchronous context manager that yields a GinoTransaction
update_execution_options(**opt)[源代码]

Update the default execution_options dictionary of this GinoEngine.

gino.exceptions module

exception gino.exceptions.GinoException[源代码]

基类:Exception

exception gino.exceptions.NoSuchRowError[源代码]

基类:gino.exceptions.GinoException

exception gino.exceptions.UninitializedError[源代码]

基类:gino.exceptions.GinoException

exception gino.exceptions.UnknownJSONPropertyError[源代码]

基类:gino.exceptions.GinoException

gino.json_support module

class gino.json_support.JSONProperty(default=None, prop_name='profile')[源代码]

基类:object

decode(val)[源代码]
encode(val)[源代码]
get_profile(instance)[源代码]
make_expression(base_exp)[源代码]
reload(instance)[源代码]
save(instance, value=<object object>)[源代码]
class gino.json_support.StringProperty(default=None, prop_name='profile')[源代码]

基类:gino.json_support.JSONProperty

make_expression(base_exp)[源代码]
class gino.json_support.DateTimeProperty(default=None, prop_name='profile')[源代码]

基类:gino.json_support.JSONProperty

decode(val)[源代码]
encode(val)[源代码]
make_expression(base_exp)[源代码]
class gino.json_support.IntegerProperty(default=None, prop_name='profile')[源代码]

基类:gino.json_support.JSONProperty

decode(val)[源代码]
encode(val)[源代码]
make_expression(base_exp)[源代码]
class gino.json_support.BooleanProperty(default=None, prop_name='profile')[源代码]

基类:gino.json_support.JSONProperty

decode(val)[源代码]
encode(val)[源代码]
make_expression(base_exp)[源代码]
class gino.json_support.ObjectProperty(default=None, prop_name='profile')[源代码]

基类:gino.json_support.JSONProperty

decode(val)[源代码]
encode(val)[源代码]
class gino.json_support.ArrayProperty(default=None, prop_name='profile')[源代码]

基类:gino.json_support.JSONProperty

decode(val)[源代码]
encode(val)[源代码]

gino.loader module

class gino.loader.AliasLoader(alias, *columns, **extras)[源代码]

基类:gino.loader.ModelLoader

class gino.loader.CallableLoader(func)[源代码]

基类:gino.loader.Loader

do_load(row, context)[源代码]
class gino.loader.ColumnLoader(column)[源代码]

基类:gino.loader.Loader

do_load(row, context)[源代码]
class gino.loader.Loader[源代码]

基类:object

do_load(row, context)[源代码]
classmethod get(value)[源代码]
get_columns()[源代码]
get_from()[源代码]
query
class gino.loader.ModelLoader(model, *columns, **extras)[源代码]

基类:gino.loader.Loader

distinct(*columns)[源代码]
do_load(row, context)[源代码]
get_columns()[源代码]
get_from()[源代码]
load(*columns, **extras)[源代码]
none_as_none(enabled=True)[源代码]
on(on_clause)[源代码]
class gino.loader.TupleLoader(values)[源代码]

基类:gino.loader.Loader

do_load(row, context)[源代码]
class gino.loader.ValueLoader(value)[源代码]

基类:gino.loader.Loader

do_load(row, context)[源代码]

gino.schema module

class gino.schema.AsyncSchemaDropper(dialect, connection, checkfirst=False, tables=None, **kwargs)[源代码]

基类:gino.schema.AsyncVisitor, sqlalchemy.sql.ddl.SchemaDropper

coroutine visit_foreign_key_constraint(constraint)[源代码]
coroutine visit_index(index)[源代码]
coroutine visit_metadata(metadata)[源代码]
coroutine visit_sequence(sequence, drop_ok=False)[源代码]
coroutine visit_table(table, drop_ok=False, _is_metadata_operation=False)[源代码]
class gino.schema.AsyncSchemaGenerator(dialect, connection, checkfirst=False, tables=None, **kwargs)[源代码]

基类:gino.schema.AsyncVisitor, sqlalchemy.sql.ddl.SchemaGenerator

coroutine visit_foreign_key_constraint(constraint)[源代码]
coroutine visit_index(index)[源代码]
coroutine visit_metadata(metadata)[源代码]
coroutine visit_sequence(sequence, create_ok=False)[源代码]
coroutine visit_table(table, create_ok=False, include_foreign_key_constraints=None, _is_metadata_operation=False)[源代码]
class gino.schema.AsyncSchemaTypeMixin[源代码]

基类:object

coroutine create_async(bind=None, checkfirst=False)[源代码]
coroutine drop_async(bind=None, checkfirst=False)[源代码]
class gino.schema.AsyncVisitor[源代码]

基类:object

coroutine traverse_single(obj, **kw)[源代码]
class gino.schema.GinoSchemaVisitor(item)[源代码]

基类:object

coroutine create(bind=None, *args, **kwargs)[源代码]
coroutine create_all(bind=None, tables=None, checkfirst=True)[源代码]
coroutine drop(bind=None, *args, **kwargs)[源代码]
coroutine drop_all(bind=None, tables=None, checkfirst=True)[源代码]
gino.schema.patch_schema(db)[源代码]

gino.strategies module

class gino.strategies.GinoStrategy[源代码]

基类:sqlalchemy.engine.strategies.EngineStrategy

coroutine create(name_or_url, loop=None, **kwargs)[源代码]

Given arguments, returns a new Engine instance.

engine_cls

gino.engine.GinoEngine 的别名

name = 'gino'

gino.transaction module

class gino.transaction.GinoTransaction(conn, args, kwargs)[源代码]

基类:object

Represents an underlying database transaction and its connection, offering methods to manage this transaction.

GinoTransaction is supposed to be created by either gino.engine.GinoConnection.transaction(), or gino.engine.GinoEngine.transaction(), or gino.api.Gino.transaction(), shown as follows:

async with db.transaction() as tx:
    ...

async with engine.transaction() as tx:
    ...

async with conn.transaction() as tx:
    ...

tx = await conn.transaction()
try:
    ...
    await tx.commit()
except Exception:
    await tx.rollback()
    raise

When in use with asynchronous context manager, GinoTransaction will be in managed mode, while the last example with await will put the GinoTransaction in manual mode where you have to call the commit() or rollback() to manually close the transaction.

In managed mode the transaction will be automatically committed or rolled back on exiting the async with block depending on whether there is an exception or not. Meanwhile, you can explicitly exit the transaction early by raise_commit() or raise_rollback() which will raise an internal exception managed by the asynchronous context manager and interpreted as a commit or rollback action. In a nested transaction situation, the two exit-early methods always close up the very transaction which the two methods are referenced upon - all children transactions are either committed or rolled back correspondingly, while no parent transaction was ever touched. For example:

async with db.transaction() as tx1:
    async with db.transaction() as tx2:
        async with db.transaction() as tx3:
            tx2.raise_rollback()
            # Won't reach here
        # Won't reach here
    # Continues here with tx1, with both tx2 and tx3 rolled back.

    # For PostgreSQL, tx1 can still be committed successfully because
    # tx2 and tx3 are just SAVEPOINTs in transaction tx1

小技巧

The internal exception raised from raise_commit() and raise_rollback() is a subclass of BaseException, so normal try ... except Exception: can't trap the commit or rollback.

coroutine commit()[源代码]

Only available in manual mode: manually commit this transaction.

connection

Accesses to the GinoConnection of this transaction. This is useful if when the transaction is started from db or engine where the connection is implicitly acquired for you together with the transaction.

raise_commit()[源代码]

Only available in managed mode: skip rest of the code in this transaction and commit immediately by raising an internal exception, which will be caught and handled by the asynchronous context manager:

async with db.transaction() as tx:
    await user.update(age=64).apply()
    tx.raise_commit()
    await user.update(age=32).apply()  # won't reach here

assert user.age == 64  # no exception raised before
raise_rollback()[源代码]

Only available in managed mode: skip rest of the code in this transaction and rollback immediately by raising an internal exception, which will be caught and handled by the asynchronous context manager:

assert user.age == 64  # assumption

async with db.transaction() as tx:
    await user.update(age=32).apply()
    tx.raise_rollback()
    await user.update(age=128).apply()  # won't reach here

assert user.age == 64  # no exception raised before
raw_transaction

Accesses to the underlying transaction object, whose type depends on the dialect in use.

coroutine rollback()[源代码]

Only available in manual mode: manually rollback this transaction.

Module contents

gino.create_engine(*args, **kwargs)[源代码]