gino package¶
Subpackages¶
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 normalMetaData
object, e.g. used in Alembic. In usual cases, you would want to define one globalGino
instance, usually under the name ofdb
, 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 bysqlalchemy
, so that you can define tables / models without importingsqlalchemy
:id = db.Column(db.BigInteger(), primary_key=True)
Similar to
MetaData
, aGino
object can bind to aGinoEngine
instance, hereby allowing “implicit execution” through thegino
extension onExecutable
orSchemaItem
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 ondb.bind
, or set it toNone
to unbind. However, the creation of engine usually happens at the same time. Therefore, GINO provided several convenient ways doing so:with_bind()
returning an asynchronous context manager:async with db.with_bind('postgresql://...') as engine:
set_bind()
andpop_bind()
:engine = await db.set_bind('postgresql://...') await db.pop_bind().close()
Directly
await
onGino
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 requiresawait
, which is excatly whatset_bind()
does.At last,
Gino
delegated all query APIs on the boundGinoEngine
.Parameters: - bind – A
GinoEngine
instance to bind. Also accepts string orURL
, which will be passed tocreate_engine()
when thisGino
instance is awaited. Default isNone
. - model_classes – A
tuple
of base class and mixin classes to create theModel
class. Default is(CRUDModel, )
. - query_ext – Boolean value to control the installation of the
gino
extension onExecutable
for implicit execution. Default is to install (True
). - schema_ext – Boolean value to control the installation of the
gino
extension onSchemaItem
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 toTrue
(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 thisGino
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 thisGino
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, useset_bind()
(orawait
on thisGino
object after setting a string orURL
).
-
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 byGino
.
-
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
orNone
if self is not bound.
-
query_executor
¶ The overridable
gino
extension class onExecutable
.This class will be set as the getter method of the property
gino
onExecutable
and its subclasses, ifext
andquery_ext
arguments are bothTrue
. Default isGinoExecutor
.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 orURL
, all arguments will be sent tocreate_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()
andpop_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 onExecutable
constructs for implicit execution.Instances of this class are created when visiting the
gino
property ofExecutable
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 (theGino
instance) must be bound to an engine, or anAttributeError
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 evendb.scalar()
in this case.-
coroutine
all
(*multiparams, **params)[source]¶ Returns
engine.all()
with this query as the first argument, and other arguments followed, whereengine
is theGinoEngine
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, whereengine
is theGinoEngine
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, whereengine
is theGinoEngine
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, whereengine
is theGinoEngine
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, whereengine
is theGinoEngine
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.
-
coroutine
gino.crud module¶
-
class
gino.crud.
Alias
(model, *args, **kwargs)[source]¶ Bases:
object
Experimental proxy for table alias on model.
-
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.-
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()
usesINSERT ... 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 theINSERT
statement with, orNone
(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 thetimeout
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).
- bind – A
-
delete
¶ Similar to
update()
, thisdelete
is also different on model classes than on model instances.On model classes
delete
is an attribute of typeDelete
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 differentGinoEngine
to execute theDELETE
. - timeout – Seconds to wait for the database to finish executing,
None
for wait forever. By default it will use thetimeout
execution option value if unspecified.
- bind – An optional
-
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 theINSERT
statement with, orNone
(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 thetimeout
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 theloader
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, checkget()
orquery
) 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 optionloader
.This will populate a
User
instance with onlyid
andname
values, all the rest are simplyNone
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
andTeam
, returning theUser
instance withu.team
set to theTeam
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 justTeam
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 thequery
, so.query
can be omitted. TheLEFT JOIN
is built-in behavior, while theON
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()
andon()
at the same time in a chain, in whatever order suits you.See also
-
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 inupdate()
, the where condition is used inUpdateRequest.apply()
, so that queries likeUPDATE ... SET id = NEW WHERE id = OLD
could work correctly.Returns: New in version 0.7.6.
-
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
-
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 optionmodel
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:model
is set to this model typereturn_model
is set toFalse
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 aWHERE
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()
See also
-
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
-
update
¶ This
update
behaves quite different on model classes rather than model instances.On model classes,
update
is an attribute of typeUpdate
for massive updates, for example:await User.update.values(enabled=True).where(...).gino.status()
Like
query
, the update query also has themodel
execution option of this model, so if you use thereturning()
clause, the query shall return model objects.However on model instances,
update()
is a method which accepts keyword arguments only and returns anUpdateRequest
to update this single model instance. The keyword arguments are pairs of attribute names and new values. This is the same asUpdateRequest.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 actualUPDATE
SQL in the database, whileuser.update()
only makes changes in the memory, and collect all changes into anUpdateRequest
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 byCRUDModel.update
, don’t instantiate manually unless required. EveryUpdateRequest
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, orNone
(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 thetimeout
execution option value if unspecified.
Returns: self
for chaining calls.- bind – A
-
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()
returnsself
for chaining calls to eitherapply()
or anotherupdate()
. If one attribute is updated several times by the sameUpdateRequest
, then only the last value is remembered forapply()
.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()
-
coroutine
gino.declarative module¶
-
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 thandeclared_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()
orstatus()
, 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 aGinoConnection
is acquired withlazy=True
, the underlying connection may still be in the pool, until a query API is called orget_raw_connection()
is called.Oppositely, one underlying database connection can be shared by many
GinoConnection
instances when they are acquired withreuse=True
. The actual database connection is only returned to the pool when the rootGinoConnection
is released. Read more inGinoEngine.acquire()
method.See also
-
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
.
-
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 SQLAlchemyConnection
. 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 isTrue
. - model – Specifies the type of model instance to create on return.
This has no effect if
return_model
is set toFalse
. 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 usefirst()
instead ofscalar()
. However, using directlyscalar()
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 therow
instance, the second is a context object which is only present if nested elseNone
. - A
Loader
instance directly. - Anything else will be treated as literal values thus returned as whatever they are.
- 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
-
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()
.
-
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.See also
-
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 theGinoTransaction
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()
orrollback()
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.
-
coroutine
-
class
gino.engine.
GinoEngine
(dialect, pool, loop, logging_name=None, echo=None, execution_options=None)[source]¶ Bases:
object
Connects a
Pool
andDialect
together to provide a source of database connectivity and behavior.A
GinoEngine
object is instantiated publicly using thegino.create_engine()
function ordb.set_bind()
method.See also
-
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 reParameters: - timeout – Block up to
timeout
seconds until there is one free connection in the pool. Default isNone
- block forever until succeeded. This has no effect whenlazy=True
, and depends on the actual situation whenreuse=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 ifreusable=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 settingreuse=True
at the same time, then the reused connection - if any - applies the same laziness. For example, reusing a lazy connection withlazy=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
andreusing=False
makes it a cleanly isolated connection which is only referenced once here.
Returns: A
GinoConnection
object.- timeout – Block up to
-
coroutine
all
(clause, *multiparams, **params)[source]¶ Acquires a connection with
reuse=True
and runsall()
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.
-
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
-
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.
-
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 withreuse=True
andreusable=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¶
gino.json_support module¶
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
-
class
gino.loader.
ColumnLoader
(column)[source]¶ Bases:
gino.loader.Loader
-
class
gino.loader.
ModelLoader
(model, *column_names, **extras)[source]¶ Bases:
gino.loader.Loader
-
class
gino.loader.
TupleLoader
(values)[source]¶ Bases:
gino.loader.Loader
-
class
gino.loader.
ValueLoader
(value)[source]¶ Bases:
gino.loader.Loader
gino.schema module¶
-
class
gino.schema.
AsyncSchemaDropper
(dialect, connection, checkfirst=False, tables=None, **kwargs)[source]¶ Bases:
gino.schema.AsyncVisitor
,sqlalchemy.sql.ddl.SchemaDropper
-
class
gino.schema.
AsyncSchemaGenerator
(dialect, connection, checkfirst=False, tables=None, **kwargs)[source]¶ Bases:
gino.schema.AsyncVisitor
,sqlalchemy.sql.ddl.SchemaGenerator
gino.strategies module¶
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 eithergino.engine.GinoConnection.transaction()
, orgino.engine.GinoEngine.transaction()
, orgino.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 withawait
will put theGinoTransaction
in manual mode where you have to call thecommit()
orrollback()
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 byraise_commit()
orraise_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()
andraise_rollback()
is a subclass ofBaseException
, so normaltry ... except Exception:
can’t trap the commit or rollback.-
connection
¶ Accesses to the
GinoConnection
of this transaction. This is useful if when the transaction is started fromdb
orengine
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.
-