gino package

Submodules

gino.api module

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

Bases: 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()
    

Note

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 excatly what set_bind() does.

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

Parameters:
  • 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)[source]

A delegate of GinoEngine.acquire().

coroutine all(clause, *multiparams, **params)[source]

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)[source]

A delegate of GinoEngine.compile().

coroutine first(clause, *multiparams, **params)[source]

A delegate of GinoEngine.first().

iterate(clause, *multiparams, **params)[source]

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()[source]

Unbind self, and return the bound engine.

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

await db.pop_bind().close()
Returns: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.

alias of GinoExecutor

coroutine scalar(clause, *multiparams, **params)[source]

A delegate of GinoEngine.scalar().

schema_visitor

alias of gino.schema.GinoSchemaVisitor

coroutine set_bind(bind, loop=None, **kwargs)[source]

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.

Returns:GinoEngine
coroutine status(clause, *multiparams, **params)[source]

A delegate of GinoEngine.status().

transaction(*args, **kwargs)[source]

A delegate of GinoEngine.transaction().

with_bind(bind, loop=None, **kwargs)[source]

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
Returns:An asynchronous context manager.
class gino.api.GinoExecutor(query)[source]

Bases: 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.

Note

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

Shortcut to set execution option return_model in a chaining call.

Read execution_options() for more information.

coroutine scalar(*multiparams, **params)[source]

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)[source]

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)[source]

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)[source]

Bases: object

Experimental proxy for table alias on model.

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

Bases: 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)[source]

Experimental proxy for table alias on model.

append_where_primary_key(q)[source]

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()

Deprecated since version 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()
Parameters:
  • 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.
Returns:

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

Note

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

Parameters:
  • 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)[source]

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

coroutine get(ident, bind=None, timeout=<object object>)[source]

Get an instance of this model class by primary key.

For example:

user = await User.get(request.args.get('user_id'))
Parameters:
  • 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.
Returns:

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

classmethod load(*column_names, **relationships)[source]

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()

Tip

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()[source]

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.

Returns:

New in version 0.7.6.

classmethod none_as_none(enabled=True)[source]
classmethod on(on_clause)[source]

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

Note

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

See also

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()[source]

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.

See also

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)[source]

Bases: 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>)[source]

Apply pending updates into database by executing an UPDATE SQL.

Parameters:
  • 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.
Returns:

self for chaining calls.

update(**values)[source]

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()

Note

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(column)[source]

Bases: object

class gino.declarative.Model[source]

Bases: object

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

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'),

Note

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

gino.engine module

class gino.engine.GinoConnection(dialect, sa_conn, stack=None)[source]

Bases: 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().

Note

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)[source]

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)[source]

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:

Parameters:
  • 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)[source]

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)[source]

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

Parameters:timeout – Seconds to wait for the underlying acquiring
Returns:Underlying database connection instance depending on the dialect in use
Raises:TimeoutError if the acquiring timed out
iterate(clause, *multiparams, **params)[source]

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)[source]
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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

Bases: 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)[source]

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

Parameters:
  • 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.
Returns:

A GinoConnection object.

coroutine all(clause, *multiparams, **params)[source]

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()[source]

Close the engine, by closing the underlying pool.

compile(clause, *multiparams, **params)[source]

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.

alias of GinoConnection

current_connection

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

Returns:GinoConnection
dialect

Read-only property for the Dialect of this engine.

coroutine first(clause, *multiparams, **params)[source]

Runs first(), See all().

iterate(clause, *multiparams, **params)[source]

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)[source]

Runs scalar(), See all().

coroutine status(clause, *multiparams, **params)[source]

Runs status(). See also all().

transaction(*args, timeout=None, reuse=True, reusable=True, **kwargs)[source]

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.

Returns:A asynchronous context manager that yields a GinoTransaction
update_execution_options(**opt)[source]

Update the default execution_options dictionary of this GinoEngine.

gino.exceptions module

exception gino.exceptions.GinoException[source]

Bases: Exception

exception gino.exceptions.NoSuchRowError[source]

Bases: gino.exceptions.GinoException

exception gino.exceptions.UninitializedError[source]

Bases: gino.exceptions.GinoException

gino.json_support module

class gino.json_support.JSONProperty(default=None, column_name='profile')[source]

Bases: object

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

Bases: gino.json_support.JSONProperty

make_expression(base_exp)[source]
class gino.json_support.DateTimeProperty(default=None, column_name='profile')[source]

Bases: gino.json_support.JSONProperty

decode(val)[source]
encode(val)[source]
make_expression(base_exp)[source]
class gino.json_support.IntegerProperty(default=None, column_name='profile')[source]

Bases: gino.json_support.JSONProperty

decode(val)[source]
encode(val)[source]
make_expression(base_exp)[source]
class gino.json_support.BooleanProperty(default=None, column_name='profile')[source]

Bases: gino.json_support.JSONProperty

decode(val)[source]
encode(val)[source]
make_expression(base_exp)[source]
class gino.json_support.ObjectProperty(default=None, column_name='profile')[source]

Bases: gino.json_support.JSONProperty

decode(val)[source]
encode(val)[source]
class gino.json_support.ArrayProperty(default=None, column_name='profile')[source]

Bases: gino.json_support.JSONProperty

decode(val)[source]
encode(val)[source]

gino.loader module

class gino.loader.AliasLoader(alias, *column_names, **extras)[source]

Bases: gino.loader.ModelLoader

class gino.loader.CallableLoader(func)[source]

Bases: gino.loader.Loader

do_load(row, context)[source]
class gino.loader.ColumnLoader(column)[source]

Bases: gino.loader.Loader

do_load(row, context)[source]
class gino.loader.Loader[source]

Bases: object

do_load(row, context)[source]
classmethod get(value)[source]
get_columns()[source]
get_from()[source]
query
class gino.loader.ModelLoader(model, *column_names, **extras)[source]

Bases: gino.loader.Loader

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

Bases: gino.loader.Loader

do_load(row, context)[source]
class gino.loader.ValueLoader(value)[source]

Bases: gino.loader.Loader

do_load(row, context)[source]

gino.schema module

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

Bases: gino.schema.AsyncVisitor, sqlalchemy.sql.ddl.SchemaDropper

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

Bases: gino.schema.AsyncVisitor, sqlalchemy.sql.ddl.SchemaGenerator

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

Bases: object

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

Bases: object

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

Bases: object

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

gino.strategies module

class gino.strategies.GinoStrategy[source]

Bases: sqlalchemy.engine.strategies.EngineStrategy

coroutine create(name_or_url, loop=None, **kwargs)[source]

Given arguments, returns a new Engine instance.

engine_cls

alias of gino.engine.GinoEngine

name = 'gino'

gino.transaction module

class gino.transaction.GinoTransaction(conn, args, kwargs)[source]

Bases: 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

Tip

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()[source]

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()[source]

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()[source]

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()[source]

Only available in manual mode: manually rollback this transaction.

Module contents

gino.create_engine(*args, **kwargs)[source]