gino.ext package

Submodules

gino.ext.aiohttp module

class gino.ext.aiohttp.AiohttpModelMixin[source]

Bases: object

coroutine get_or_404(*args, **kwargs)[source]
class gino.ext.aiohttp.AiohttpStrategy[source]

Bases: gino.strategies.GinoStrategy

engine_cls

alias of GinoEngine

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

Bases: gino.api.Gino

Support aiohttp.web server.

The common usage looks like this:

from aiohttp import web
from gino.ext.aiohttp import Gino

db = Gino()
app = web.Application(middlewares=[db])
db.init_app(app)

By init_app() GINO subscribes to a few signals on aiohttp, so that GINO could use database configuration in aiohttp config.gino to initialize the bound engine. The config includes:

  • driver - the database driver, default is asyncpg.
  • host - database server host, default is localhost.
  • port - database server port, default is 5432.
  • user - database server user, default is postgres.
  • password - database server password, default is empty.
  • database - database name, default is postgres.
  • dsn - a SQLAlchemy database URL to create the engine, its existence will replace all previous connect arguments.
  • pool_min_size - the initial number of connections of the db pool.
  • pool_max_size - the maximum number of connections in the db pool.
  • echo - enable SQLAlchemy echo mode.

If the db is set as an aiohttp middleware, then a lazy connection is available at request['connection']. By default, a database connection is borrowed on the first query, shared in the same execution context, and returned to the pool on response. If you need to release the connection early in the middle to do some long-running tasks, you can simply do this:

await request['connection'].release(permanent=False)
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.
coroutine first_or_404(*args, **kwargs)[source]
init_app(app)[source]
model_base_classes = (<class 'gino.crud.CRUDModel'>, <class 'gino.ext.aiohttp.AiohttpModelMixin'>)
query_executor

alias of GinoExecutor

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
class gino.ext.aiohttp.GinoConnection(dialect, sa_conn, stack=None)[source]

Bases: gino.engine.GinoConnection

coroutine first_or_404(*args, **kwargs)[source]
class gino.ext.aiohttp.GinoEngine(dialect, pool, loop, logging_name=None, echo=None, execution_options=None)[source]

Bases: gino.engine.GinoEngine

connection_cls

alias of GinoConnection

coroutine first_or_404(*args, **kwargs)[source]
class gino.ext.aiohttp.GinoExecutor(query)[source]

Bases: gino.api.GinoExecutor

coroutine first_or_404(*args, **kwargs)[source]

gino.ext.quart module

gino.ext.sanic module

class gino.ext.sanic.Gino(app=None, *args, **kwargs)[source]

Bases: gino.api.Gino

Support Sanic web server.

By init_app() GINO registers a few hooks on Sanic, so that GINO could use database configuration in Sanic config to initialize the bound engine.

A lazy connection context is enabled by default for every request. You can change this default behavior by setting DB_USE_CONNECTION_FOR_REQUEST config value to False. By default, a database connection is borrowed on the first query, shared in the same execution context, and returned to the pool on response. If you need to release the connection early in the middle to do some long-running tasks, you can simply do this:

await request['connection'].release(permanent=False)
coroutine first_or_404(*args, **kwargs)[source]
init_app(app)[source]
model_base_classes = (<class 'gino.crud.CRUDModel'>, <class 'gino.ext.sanic.SanicModelMixin'>)
query_executor

alias of GinoExecutor

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
class gino.ext.sanic.GinoConnection(dialect, sa_conn, stack=None)[source]

Bases: gino.engine.GinoConnection

coroutine first_or_404(*args, **kwargs)[source]
class gino.ext.sanic.GinoEngine(dialect, pool, loop, logging_name=None, echo=None, execution_options=None)[source]

Bases: gino.engine.GinoEngine

connection_cls

alias of GinoConnection

coroutine first_or_404(*args, **kwargs)[source]
class gino.ext.sanic.GinoExecutor(query)[source]

Bases: gino.api.GinoExecutor

coroutine first_or_404(*args, **kwargs)[source]
class gino.ext.sanic.SanicModelMixin[source]

Bases: object

coroutine get_or_404(*args, **kwargs)[source]
class gino.ext.sanic.SanicStrategy[source]

Bases: gino.strategies.GinoStrategy

engine_cls

alias of GinoEngine

name = 'sanic'

gino.ext.tornado module

GINO provides a convenient plugin for integrating with Tornado webserver. It consists of two parts, each of them is optional.

Warning

Tornado doesn’t wrap request handlers to asyncio tasks, hence task locals doesn’t work in request handlers by default. To fix this, you may either redefine _execute() method on you handlers to wrap request processing into a task, or simply use gino.ext.tornado.AsyncioRequestHandler as a base class for all of your handlers.

See integrate GINO with application and request handlers for more details.

Provide tornado-specific methods on models

GINO can provide a webframework-aware .get_or_404() method which work similar to .get() but raises an appropriate error whenever requested object not found. In case of tornado, an appropriate error is tornado.web.HTTPError(404).

To have it working, simply use gino.ext.tornado.Gino as your database metadata.

Integrate GINO with application and request handlers

In addition to .get_or_404(), GINO provides bases for application and request handler objects.

Inherit your application class from gino.ext.tornado.Application to automate connection pool management and provide access to the database object to all of your request handlers via self.application.db.

Inherit your request handlers from gino.ext.tornado.AsyncioRequestHandler to enable task locals support.

Inherit your request handlers from gino.ext.tornado.GinoRequestHandler to enable active connection management. Note that gino.ext.tornado.GinoRequestHandler requires your application to have a db property with acquire coroutine so its best to use it with gino.ext.tornado.Application.

Settings defined by this extension

GINO would define some options for database configuration. Use them with the standard tornado.options module:

  • 'db_driver' – if not set, asyncpg;
  • 'db_host' – if not set, localhost;
  • 'db_port' – if not set, 5432;
  • 'db_user' – if not set, postgres;
  • 'db_password' – if not set, empty string;
  • 'db_database' – if not set, postgres;
  • 'db_echo' – whether to enable SQLAlchemy echo mode, defaults to False.
  • dsn – a SQLAlchemy database URL to create the engine, its existence will replace all previous connect arguments.
  • 'db_pool_min_size' – number of connection the pool will be initialized with. Default is 5;
  • 'db_pool_max_size' – max number of connections in the pool. Default is 10;
  • 'db_pool_max_inactive_conn_lifetime' – number of seconds after which inactive connections in the pool will be closed. Pass 0 to disable this mechanism. Default is 300;
  • 'db_pool_max_queries ' – number of queries after a connection is closed and replaced with a new connection. Default is 50000.

An example application

A helloworld application that uses tornado and GINO may look like this:

import tornado.web
import tornado.ioloop
import tornado.options
import tornado.escape

from gino.ext.tornado import Gino, Application, GinoRequestHandler


# Define your database metadata
# -----------------------------

db = Gino()


# Define tables as you would normally do
# --------------------------------------

class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
    nickname = db.Column(db.Unicode(), nullable=False)


# Now just use your tables
# ------------------------

class AllUsers(GinoRequestHandler):
    async def get(self):
        users = await User.query.gino.all()

        for user in users:
            url = self.application.reverse_url('user', user.id)
            nickname = tornado.escape.xhtml_escape(user.nickname)
            self.write(f'<a href="{url}">{nickname}</a><br/>')


class GetUser(GinoRequestHandler):
    async def get(self, uid):
        user: User = await User.get_or_404(int(uid))
        self.write(f'Hi, {user.nickname}!')


if __name__ == '__main__':
    tornado.options.parse_command_line()
    tornado.ioloop.IOLoop.configure('tornado.platform.asyncio.AsyncIOMainLoop')

    app = Application([
        tornado.web.URLSpec(r'/', AllUsers, name='index'),
        tornado.web.URLSpec(r'/user/(?P<uid>[0-9]+)', GetUser, name='user')
    ], debug=True)

    loop = tornado.ioloop.IOLoop.current().asyncio_loop

    # If you intend to use HTTPServer in multiprocessed environment,
    # call the app.late_init method after calling HTTPServer.start(n).
    # This will create one connection pool per process.
    loop.run_until_complete(app.late_init(db))

    app.listen(8888)

    loop.run_forever()

API reference

class gino.ext.tornado.Application(handlers: List[Union[Rule, List[Any], Tuple[Union[str, Matcher], Any], Tuple[Union[str, Matcher], Any, Dict[str, Any]], Tuple[Union[str, Matcher], Any, Dict[str, Any], str]]] = None, default_host: str = None, transforms: List[Type[OutputTransform]] = None, **settings)[source]

Bases: tornado.web.Application

Base application that provides access to the database object and defines a convenient method for initializing all the database-related stuff.

db = None

The database object associated with this application. Use late_init() to init this or set it manually.

coroutine late_init(db: gino.ext.tornado.Gino, *, loop=None, options=<tornado.options.OptionParser object>)[source]

Initialize this application with a database object.

This method does a few things to setup application for working with the database:

  • it enables task local storage;
  • creates a connection pool and binds it to the passed database object;
  • populates db.
Parameters:
  • db – the gino.ext.tornado.Gino() class instance that will be used in this application.
  • loop – io loop that will be used to run heep server, either tornado’s or asyncio’s.
  • options – a tornado’s OptionParser() instance or any dictionary-like object with the database settings. Default is to use tornado.options.options global.
use_connection_for_request = True

If True, enables GinoRequestHandler to create lazy connections.

See use_connection_for_request for more info.

class gino.ext.tornado.AsyncioRequestHandler(application: tornado.web.Application, request: tornado.httputil.HTTPServerRequest, **kwargs)[source]

Bases: tornado.web.RequestHandler

This class enables support for task locals by wrapping the _execute() method into asyncio.Task instances.

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

Bases: gino.api.Gino

Base class for GINO database.

Using this class as a metadata for your database adds an additional get_or_404() method to all of your table classes.

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.
coroutine first_or_404(*args, **kwargs)[source]
model_base_classes = (<class 'gino.crud.CRUDModel'>, <class 'gino.ext.tornado.TornadoModelMixin'>)
query_executor

alias of GinoExecutor

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
class gino.ext.tornado.GinoConnection(dialect, sa_conn, stack=None)[source]

Bases: gino.engine.GinoConnection

coroutine first_or_404(*args, **kwargs)[source]
class gino.ext.tornado.GinoEngine(dialect, pool, loop, logging_name=None, echo=None, execution_options=None)[source]

Bases: gino.engine.GinoEngine

connection_cls

alias of GinoConnection

coroutine first_or_404(*args, **kwargs)[source]
class gino.ext.tornado.GinoExecutor(query)[source]

Bases: gino.api.GinoExecutor

coroutine first_or_404(*args, **kwargs)[source]
class gino.ext.tornado.GinoRequestHandler(application: tornado.web.Application, request: tornado.httputil.HTTPServerRequest, **kwargs)[source]

Bases: gino.ext.tornado.AsyncioRequestHandler

Base class for all request handlers that use GINO.

In addition to features provided by AsyncioRequestHandler, this class manages lazy connections for each request.

db

Access to the database object.

This property is equal to Application.db by default.

db_connection

The actual connection associated with this request or None if use_connection_for_request is False.

coroutine release_connection()[source]

Return the connection associated with this request back to the pool.

use_connection_for_request

If True, a lazy connection is created for each request.

That is, whenever the first query occurs, a new connection is borrowed from the application’s db object. All succeeding queries made within this request will reuse that connection. The connection will be returned to the pool once the request is finished or the release_connection() method is called explicitly.

This property is equal to Application.use_connection_for_request by default.

class gino.ext.tornado.TornadoModelMixin[source]

Bases: object

coroutine get_or_404(*args, **kwargs)[source]
class gino.ext.tornado.TornadoStrategy[source]

Bases: gino.strategies.GinoStrategy

engine_cls

alias of GinoEngine

name = 'tornado'

Module contents