|
| 1 | +# noinspection PyPackageRequirements |
| 2 | +from starlette.applications import Starlette |
| 3 | +# noinspection PyPackageRequirements |
| 4 | +from starlette.types import Message, Receive, Scope, Send |
| 5 | +# noinspection PyPackageRequirements |
| 6 | +from starlette.exceptions import HTTPException |
| 7 | +# noinspection PyPackageRequirements |
| 8 | +from starlette import status |
| 9 | +from sqlalchemy.engine.url import URL |
| 10 | + |
| 11 | +from ..api import Gino as _Gino, GinoExecutor as _Executor |
| 12 | +from ..engine import GinoConnection as _Connection, GinoEngine as _Engine |
| 13 | +from ..strategies import GinoStrategy |
| 14 | + |
| 15 | + |
| 16 | +class StarletteModelMixin: |
| 17 | + @classmethod |
| 18 | + async def get_or_404(cls, *args, **kwargs): |
| 19 | + # noinspection PyUnresolvedReferences |
| 20 | + rv = await cls.get(*args, **kwargs) |
| 21 | + if rv is None: |
| 22 | + raise HTTPException(status.HTTP_404_NOT_FOUND, |
| 23 | + '{} is not found'.format(cls.__name__)) |
| 24 | + return rv |
| 25 | + |
| 26 | + |
| 27 | +# noinspection PyClassHasNoInit |
| 28 | +class GinoExecutor(_Executor): |
| 29 | + async def first_or_404(self, *args, **kwargs): |
| 30 | + rv = await self.first(*args, **kwargs) |
| 31 | + if rv is None: |
| 32 | + raise HTTPException(status.HTTP_404_NOT_FOUND, 'No such data') |
| 33 | + return rv |
| 34 | + |
| 35 | + |
| 36 | +# noinspection PyClassHasNoInit |
| 37 | +class GinoConnection(_Connection): |
| 38 | + async def first_or_404(self, *args, **kwargs): |
| 39 | + rv = await self.first(*args, **kwargs) |
| 40 | + if rv is None: |
| 41 | + raise HTTPException(status.HTTP_404_NOT_FOUND, 'No such data') |
| 42 | + return rv |
| 43 | + |
| 44 | + |
| 45 | +# noinspection PyClassHasNoInit |
| 46 | +class GinoEngine(_Engine): |
| 47 | + connection_cls = GinoConnection |
| 48 | + |
| 49 | + async def first_or_404(self, *args, **kwargs): |
| 50 | + rv = await self.first(*args, **kwargs) |
| 51 | + if rv is None: |
| 52 | + raise HTTPException(status.HTTP_404_NOT_FOUND, 'No such data') |
| 53 | + return rv |
| 54 | + |
| 55 | + |
| 56 | +class StarletteStrategy(GinoStrategy): |
| 57 | + name = 'starlette' |
| 58 | + engine_cls = GinoEngine |
| 59 | + |
| 60 | + |
| 61 | +StarletteStrategy() |
| 62 | + |
| 63 | + |
| 64 | +class _Middleware: |
| 65 | + def __init__(self, app, db): |
| 66 | + self.app = app |
| 67 | + self.db = db |
| 68 | + |
| 69 | + async def __call__(self, scope: Scope, receive: Receive, |
| 70 | + send: Send) -> None: |
| 71 | + if (scope['type'] == 'http' and |
| 72 | + self.db.config['use_connection_for_request']): |
| 73 | + scope['connection'] = await self.db.acquire(lazy=True) |
| 74 | + await self.app(scope, receive, send) |
| 75 | + conn = scope.pop('connection', None) |
| 76 | + if conn is not None: |
| 77 | + await conn.release() |
| 78 | + return |
| 79 | + |
| 80 | + if scope['type'] == 'lifespan': |
| 81 | + async def receiver() -> Message: |
| 82 | + message = await receive() |
| 83 | + if message["type"] == "lifespan.startup": |
| 84 | + await self.db.set_bind( |
| 85 | + self.db.config['dsn'], |
| 86 | + echo=self.db.config['echo'], |
| 87 | + min_size=self.db.config['min_size'], |
| 88 | + max_size=self.db.config['max_size'], |
| 89 | + ssl=self.db.config['ssl'], |
| 90 | + **self.db.config['kwargs'], |
| 91 | + ) |
| 92 | + elif message["type"] == "lifespan.shutdown": |
| 93 | + await self.db.pop_bind().close() |
| 94 | + return message |
| 95 | + await self.app(scope, receiver, send) |
| 96 | + return |
| 97 | + |
| 98 | + await self.app(scope, receive, send) |
| 99 | + |
| 100 | + |
| 101 | +class Gino(_Gino): |
| 102 | + """Support Starlette server. |
| 103 | +
|
| 104 | + The common usage looks like this:: |
| 105 | +
|
| 106 | + from starlette.applications import Starlette |
| 107 | + from gino.ext.starlette import Gino |
| 108 | +
|
| 109 | + app = Starlette() |
| 110 | + db = Gino(app, **kwargs) |
| 111 | +
|
| 112 | + GINO adds a middleware to the Starlette app to setup and cleanup database |
| 113 | + according to the configurations that passed in the ``kwargs`` parameter. |
| 114 | +
|
| 115 | + The config includes: |
| 116 | +
|
| 117 | + * ``driver`` - the database driver, default is ``asyncpg``. |
| 118 | + * ``host`` - database server host, default is ``localhost``. |
| 119 | + * ``port`` - database server port, default is ``5432``. |
| 120 | + * ``user`` - database server user, default is ``postgres``. |
| 121 | + * ``password`` - database server password, default is empty. |
| 122 | + * ``database`` - database name, default is ``postgres``. |
| 123 | + * ``dsn`` - a SQLAlchemy database URL to create the engine, its existence |
| 124 | + will replace all previous connect arguments. |
| 125 | + * ``pool_min_size`` - the initial number of connections of the db pool. |
| 126 | + * ``pool_max_size`` - the maximum number of connections in the db pool. |
| 127 | + * ``echo`` - enable SQLAlchemy echo mode. |
| 128 | + * ``ssl`` - SSL context passed to ``asyncpg.connect``, default is ``None``. |
| 129 | + * ``use_connection_for_request`` - flag to set up lazy connection for |
| 130 | + requests. |
| 131 | + * ``kwargs`` - other parameters passed to the specified dialects, |
| 132 | + like ``asyncpg``. Unrecognized parameters will cause exceptions. |
| 133 | +
|
| 134 | + If ``use_connection_for_request`` is set to be True, then a lazy connection |
| 135 | + is available at ``request['connection']``. By default, a database |
| 136 | + connection is borrowed on the first query, shared in the same execution |
| 137 | + context, and returned to the pool on response. If you need to release the |
| 138 | + connection early in the middle to do some long-running tasks, you can |
| 139 | + simply do this:: |
| 140 | +
|
| 141 | + await request['connection'].release(permanent=False) |
| 142 | +
|
| 143 | + """ |
| 144 | + model_base_classes = _Gino.model_base_classes + (StarletteModelMixin,) |
| 145 | + query_executor = GinoExecutor |
| 146 | + |
| 147 | + def __init__(self, app: Starlette, *args, **kwargs): |
| 148 | + self.config = dict() |
| 149 | + if 'dsn' in kwargs: |
| 150 | + self.config['dsn'] = kwargs.pop('dsn') |
| 151 | + else: |
| 152 | + self.config['dsn'] = URL( |
| 153 | + drivername=kwargs.pop('driver', 'asyncpg'), |
| 154 | + host=kwargs.pop('host', 'localhost'), |
| 155 | + port=kwargs.pop('port', 5432), |
| 156 | + username=kwargs.pop('user', 'postgres'), |
| 157 | + password=kwargs.pop('password', ''), |
| 158 | + database=kwargs.pop('database', 'postgres'), |
| 159 | + ) |
| 160 | + self.config['echo'] = kwargs.pop('echo', False) |
| 161 | + self.config['min_size'] = kwargs.pop('pool_min_size', 5) |
| 162 | + self.config['max_size'] = kwargs.pop('pool_max_size', 10) |
| 163 | + self.config['ssl'] = kwargs.pop('ssl', None) |
| 164 | + self.config['use_connection_for_request'] = \ |
| 165 | + kwargs.pop('use_connection_for_request', True) |
| 166 | + self.config['kwargs'] = kwargs.pop('kwargs', dict()) |
| 167 | + |
| 168 | + super().__init__(*args, **kwargs) |
| 169 | + |
| 170 | + app.add_middleware(_Middleware, db=self) |
| 171 | + |
| 172 | + async def first_or_404(self, *args, **kwargs): |
| 173 | + rv = await self.first(*args, **kwargs) |
| 174 | + if rv is None: |
| 175 | + raise HTTPException(status.HTTP_404_NOT_FOUND, 'No such data') |
| 176 | + return rv |
| 177 | + |
| 178 | + async def set_bind(self, bind, loop=None, **kwargs): |
| 179 | + kwargs.setdefault('strategy', 'starlette') |
| 180 | + return await super().set_bind(bind, loop=loop, **kwargs) |
0 commit comments