gino.ext.tornado module

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


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_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',
            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__':

    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.



API reference

class gino.ext.tornado.Application(handlers=None, default_host=None, transforms=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
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.
  • 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
class gino.ext.tornado.AsyncioRequestHandler(application, request, **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.

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

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.

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


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, request, **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.


Access to the database object.

This property is equal to Application.db by default.


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.


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


alias of GinoEngine

name = 'tornado'