gino.ext.tornado module

GINO provides a convenient plugin for integrating with Tornado webserver.

Provide tornado-specific methods on models

GINO can provide a web framework-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

GINO provides two ways to initialize the db instances for tornado:

1) Initialize by db.init_app(app), and get the Gino instance in the RequestHandler subclasses by self.application.db.

2) For subclassed tornado Application, use gino.ext.tornado.DBMixin and run init_db().

Request Handler Mixin

A mixin to provide a convenience property access to db using self.db instead of self.application.db.

An example application

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

import ssl

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

from gino.ext.tornado import Gino, RequestHandlerMixin

# 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(tornado.web.RequestHandler, RequestHandlerMixin):
    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(tornado.web.RequestHandler, RequestHandlerMixin):
    async def get(self, uid):
        async with self.db.acquire() as conn:
            async with conn.transaction():
                user: User = await User.get_or_404(int(uid))
                self.write(f'Hi, {user.nickname}!')


if __name__ == '__main__':
    app = tornado.web.Application([
        tornado.web.URLSpec(r'/', AllUsers, name='index'),
        tornado.web.URLSpec(r'/users/(?P<uid>[0-9]+)', GetUser,
                            name='user')
    ], debug=True)
    tornado.ioloop.IOLoop.current().run_sync(
        lambda: db.init_app(app, ssl=True))
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

API reference

class gino.ext.tornado.DBMixin[source]

Bases: object

A mixin for tornado.web.Application to initialize and have convenience methods for database accesses.

db = None
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.

model_base_classes = (<class 'gino.crud.CRUDModel'>, <class 'gino.ext.tornado.TornadoModelMixin'>)
query_executor

alias of GinoExecutor

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

Bases: gino.engine.GinoConnection

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

class gino.ext.tornado.GinoExecutor(query)[source]

Bases: gino.api.GinoExecutor

class gino.ext.tornado.RequestHandlerMixin[source]

Bases: object

A mixin to provide convenience methods to access GINO object

property db
class gino.ext.tornado.TornadoModelMixin[source]

Bases: object

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

Bases: gino.strategies.GinoStrategy

engine_cls

alias of GinoEngine

name = 'tornado'