def setup_database_creation_listener(app: Sanic, database: Gino): database.init_app(app) @app.listener("after_server_start") async def setup_database(app: Sanic, loop): await database.gino.create_all()
async def _app(config): app = sanic.Sanic() app.config.update(config) app.config.update({ 'DB_KWARGS': dict( max_inactive_connection_lifetime=_MAX_INACTIVE_CONNECTION_LIFETIME, ), }) db = Gino(app) class User(db.Model): __tablename__ = 'gino_users' id = db.Column(db.BigInteger(), primary_key=True) nickname = db.Column(db.Unicode(), default='noname') @app.route('/') async def root(request): conn = await request['connection'].get_raw_connection() # noinspection PyProtectedMember assert conn._holder._max_inactive_time == \ _MAX_INACTIVE_CONNECTION_LIFETIME return text('Hello, world!') @app.route('/users/<uid:int>') async def get_user(request, uid): method = request.args.get('method') q = User.query.where(User.id == uid) if method == '1': return json((await q.gino.first_or_404()).to_dict()) elif method == '2': return json((await request['connection'].first_or_404(q)).to_dict()) elif method == '3': return json((await db.bind.first_or_404(q)).to_dict()) elif method == '4': return json((await db.first_or_404(q)).to_dict()) else: return json((await User.get_or_404(uid)).to_dict()) @app.route('/users', methods=['POST']) async def add_user(request): u = await User.create(nickname=request.form.get('name')) await u.query.gino.first_or_404() await db.first_or_404(u.query) await db.bind.first_or_404(u.query) await request['connection'].first_or_404(u.query) return json(u.to_dict()) e = await gino.create_engine(PG_URL) try: try: await db.gino.create_all(e) await yield_(app) finally: await db.gino.drop_all(e) finally: await e.close()
async def _app(config): app = sanic.Sanic() app.config.update(config) app.config.update({ "DB_KWARGS": dict( max_inactive_connection_lifetime=_MAX_INACTIVE_CONNECTION_LIFETIME, ), }) db = Gino(app) class User(db.Model): __tablename__ = "gino_users" id = db.Column(db.BigInteger(), primary_key=True) nickname = db.Column(db.Unicode(), default="noname") @app.route("/") async def root(request): conn = await request["connection"].get_raw_connection() # noinspection PyProtectedMember assert conn._holder._max_inactive_time == _MAX_INACTIVE_CONNECTION_LIFETIME return text("Hello, world!") @app.route("/users/<uid:int>") async def get_user(request, uid): method = request.args.get("method") q = User.query.where(User.id == uid) if method == "1": return json((await q.gino.first_or_404()).to_dict()) elif method == "2": return json((await request["connection"].first_or_404(q)).to_dict()) elif method == "3": return json((await db.bind.first_or_404(q)).to_dict()) elif method == "4": return json((await db.first_or_404(q)).to_dict()) else: return json((await User.get_or_404(uid)).to_dict()) @app.route("/users", methods=["POST"]) async def add_user(request): u = await User.create(nickname=request.form.get("name")) await u.query.gino.first_or_404() await db.first_or_404(u.query) await db.bind.first_or_404(u.query) await request["connection"].first_or_404(u.query) return json(u.to_dict()) e = await gino.create_engine(PG_URL) try: try: await db.gino.create_all(e) yield app finally: await db.gino.drop_all(e) finally: await e.close()
async def app(): app = sanic.Sanic() app.config['DB_HOST'] = DB_ARGS['host'] app.config['DB_PORT'] = DB_ARGS['port'] app.config['DB_USER'] = DB_ARGS['user'] app.config['DB_PASSWORD'] = DB_ARGS['password'] app.config['DB_DATABASE'] = DB_ARGS['database'] db = Gino(app) class User(db.Model): __tablename__ = 'gino_users' id = db.Column(db.BigInteger(), primary_key=True) nickname = db.Column(db.Unicode(), default='noname') @app.route('/') async def root(request): return text('Hello, world!') @app.route('/users/<uid:int>') async def get_user(request, uid): method = request.args.get('method') q = User.query.where(User.id == uid) if method == '1': return json((await q.gino.first_or_404()).to_dict()) elif method == '2': return json((await request['connection'].first_or_404(q)).to_dict()) elif method == '3': return json((await db.bind.first_or_404(q)).to_dict()) elif method == '4': return json((await db.first_or_404(q)).to_dict()) else: return json((await User.get_or_404(uid)).to_dict()) @app.route('/users', methods=['POST']) async def add_user(request): u = await User.create(nickname=request.form.get('name')) await u.query.gino.first_or_404() await db.first_or_404(u.query) await db.bind.first_or_404(u.query) await request['connection'].first_or_404(u.query) return json(u.to_dict()) e = await gino.create_engine(PG_URL) try: try: await db.gino.create_all(e) yield app finally: await db.gino.drop_all(e) finally: await e.close()
from gino.ext.sanic import Gino db = Gino() class GiftCard(db.Model): __tablename__ = "gifts" # class to test different types support id = db.Column(db.BigInteger(), unique=True, primary_key=True) user_id = db.Column(db.String(), db.ForeignKey("users.id")) balance = db.Column(db.Integer(), default=0) rate = db.Column(db.Numeric()) rate_3 = db.Column(db.Float()) created_at = db.Column(db.DateTime()) magic_date = db.Column(db.Date()) active = db.Column(db.Boolean()) class User(db.Model): __tablename__ = "users" id = db.Column(db.String(), unique=True, primary_key=True) password_hash = db.Column(db.String(), nullable=False) email = db.Column(db.String()) name = db.Column(db.String()) phone = db.Column(db.String()) address = db.Column(db.String()) class Place(db.Model):
from sanic import Sanic import asyncio from sys import platform from gino.ext.sanic import Gino from config import * from sanic_cors import CORS app = Sanic("Heros legacy") app.config.DB_HOST = DB_ARGS['host'] app.config.DB_DATABASE = DB_ARGS['database'] app.config.DB_PASSWORD = DB_ARGS['password'] app.config.DB_USER = DB_ARGS['user'] app.config.DB_PORT = DB_ARGS['port'] CORS(app, resources={r"/*": {"origins": "*"}}) db = Gino() db.init_app(app)
from gino.ext.sanic import Gino DATABASE = Gino()
import os import datetime from sanic import Sanic from gino.ext.sanic import Gino from app import config as config_module from app import database, api from app.domain import security_domain config = config_module.get_config() app = Sanic() app.config.from_object(config) database.AppRepository.db = Gino(app=app) api.create_api(app) @app.middleware('request') async def print_on_request(request): print(request) token = request.cookies.get('myToken') decrypted_token = security_domain.Security.decrypt_token(token) if decrypted_token is not None: decrypted_token['datetime'] = str(datetime.datetime.now()) setattr(request, 'authenticated', True) setattr(request, 'user', decrypted_token)
import os # when gino admin runs it set 'GINO_ADMIN' = '1' to get possible check that application used DB Model # pay attention, that in this case you need to run admin panel and main app in different venvs if os.environ.get("GINO_ADMIN"): from gino.ext.sanic import Gino db = Gino() else: from gino.ext.starlette import Gino db = Gino( dsn=f"postgresql://*****:*****@{os.environ.get('DB_HOST','localhost')}:5432/gino" ) class GiftCard(db.Model): __tablename__ = "gifts" # class to test different types support id = db.Column(db.BigInteger(), unique=True, primary_key=True) user_id = db.Column(db.String(), db.ForeignKey("users.id")) balance = db.Column(db.Integer(), default=0) rate = db.Column(db.Numeric()) rate_3 = db.Column(db.Float()) created_at = db.Column(db.DateTime()) magic_date = db.Column(db.Date()) active = db.Column(db.Boolean()) class User(db.Model):
#!/usr/bin/env python3 import enum from datetime import datetime from enum import auto from functools import reduce from typing import List from gino.ext.sanic import Gino from sqlalchemy import and_ db = Gino() class GrantPolicyFlag(enum.Enum): REQUIRED = auto() OPTIONAL = auto() BYPASSED = auto() class PermissionFlag(enum.Enum): ALLOW = auto() DENY = auto() class GrantController: @classmethod async def create_from_context(cls, auth_context: dict): pass
import settings import uvloop import asyncio class HookedUpdateRequest(UpdateRequest): async def apply(self, bind=None, timeout=DEFAULT): self.update(last_modified=datetime.utcnow()) return await super().apply(bind, timeout) class HookedCRUDModel(CRUDModel): _update_request_cls = HookedUpdateRequest # requires latest master db = Gino(model_classes=(HookedCRUDModel, )) app = Sanic(__name__) db.init_app(app) # load app settings settings.app.load_settings(app, db) # create uvloop to db set bind and create all tables asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) loop = asyncio.get_event_loop() loop.run_until_complete(db.set_bind(app.config.DB_CONN_STR)) # loads model to create tables from models.user import User from models.tweet import Tweet from models.tag import Tag
app.config.RESPONSE_TIMEOUT = 20 app.config.ACCESS_LOG = False app.config.DB_HOST = DB_HOST app.config.DB_DATABASE = DB_NAME app.config.DB_USER = DB_USER app.config.DB_PASSWORD = DB_PASSWORD app.config.DB_POOL_MIN_SIZE = SERVER_DB_POOL_MIN_SIZE app.config.DB_POOL_MAX_SIZE = SERVER_DB_POOL_MAX_SIZE app.config.DB_USE_CONNECTION_FOR_REQUEST = False Compress(app) # must be before all response middleware db = Gino(app) jinja = SanicJinja2(app, pkg_name='core') @app.listener('after_server_start') async def setup_db(app, loop): pass @app.listener('before_server_stop') async def setup_db(app, loop): await asyncio.sleep(5) @app.middleware('request')