def _setup_base_app(): if database_exists(config.POSTGRES_URI): drop_database(config.POSTGRES_URI) create_database(config.POSTGRES_URI) app = FastAPI() db = Gino(dsn=GINO_DATABASE_URL) db.init_app(app) return db, app
async def _app(**kwargs): app = Starlette() kwargs.update({ 'kwargs': dict( max_inactive_connection_lifetime=_MAX_INACTIVE_CONNECTION_LIFETIME, ), }) db = Gino(app, **kwargs) 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 PlainTextResponse('Hello, world!') @app.route('/users/{uid:int}') async def get_user(request): uid = request.path_params.get('uid') method = request.query_params.get('method') q = User.query.where(User.id == uid) if method == '1': return JSONResponse((await q.gino.first_or_404()).to_dict()) elif method == '2': return JSONResponse( (await request['connection'].first_or_404(q)).to_dict()) elif method == '3': return JSONResponse( (await db.bind.first_or_404(q)).to_dict()) elif method == '4': return JSONResponse( (await db.first_or_404(q)).to_dict()) else: return JSONResponse((await User.get_or_404(uid)).to_dict()) @app.route('/users', methods=['POST']) async def add_user(request): u = await User.create(nickname=(await request.json()).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 JSONResponse(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 existing_database(db: Gino, name: Optional[str]) -> bool: """ Return the names of existing database """ query: str = """ SELECT datname FROM pg_database; """ raws: List = await db.all(db.text(query)) for raw in raws: if raw[0] == name: return True return False
from gino.ext.starlette import Gino from . import config db = Gino( dsn=config.DB_DSN, echo=config.DB_ECHO, ) class Snapshots(db.Model): __tablename__ = 'snapshots' id = db.Column(db.BigInteger(), primary_key=True) timestamp = db.Column(db.DateTime()) snapshot = db.Column(db.Unicode())
# from sqlalchemy.ext.declarative import declarative_base # # from core.factories import Session from sqlalchemy import MetaData from gino.ext.starlette import Gino from core.factories import settings db: MetaData = Gino(dsn=settings.DATABASE_URL)
from starlette.responses import JSONResponse, PlainTextResponse # Database Configuration PG_URL = "postgresql://{user}:{password}@{host}:{port}/{database}".format( host=os.getenv("DB_HOST", "localhost"), port=os.getenv("DB_PORT", 5432), user=os.getenv("DB_USER", "postgres"), password=os.getenv("DB_PASS", ""), database=os.getenv("DB_NAME", "postgres"), ) # Initialize Starlette app app = Starlette() # Initialize Gino instance db = Gino(app, dsn=PG_URL) # Definition of table class User(db.Model): __tablename__ = "simple_starlette_demo_users" id = db.Column(db.BigInteger(), primary_key=True) nickname = db.Column(db.Unicode(), default="unnamed") # Definition of routes @app.route("/") async def index(request): return PlainTextResponse("Hello, world!")
import uvicorn from starlette.applications import Starlette from my_app.settings import DATABASE, DEBUG, ALEMBIC_CFG from my_app.middleware import middleware from my_app.commands import args from gino.ext.starlette import Gino from alembic import command from exceptions.exception_handlers import exception_handlers app = Starlette(debug=DEBUG, middleware=middleware, exception_handlers=exception_handlers) db = Gino(dsn=DATABASE) db.init_app(app) from views import * if __name__ == "__main__": if args.command == 'runserver': uvicorn.run(app, host="127.0.0.1", port=8000) if args.command == 'makemigrations': command.revision(ALEMBIC_CFG, autogenerate=True) if args.command == "migrate": command.upgrade(ALEMBIC_CFG, "head")
from gino.ext.starlette import Gino from .. import settings db = Gino( dsn=settings.DB_DSN, pool_min_size=settings.DB_POOL_MIN_SIZE, pool_max_size=settings.DB_POOL_MAX_SIZE, echo=settings.DB_ECHO, ssl=settings.DB_SSL, use_connection_for_request=settings.DB_USE_CONNECTION_FOR_REQUEST, retry_limit=settings.DB_RETRY_LIMIT, retry_interval=settings.DB_RETRY_INTERVAL, )
import logging from gino.ext.starlette import Gino from src.core.config import DATABASE_URI LOGGER = logging.getLogger(__name__) # create Gino engine LOGGER.info(f"Initialise Gino engine and connecting to {DATABASE_URI}") db = Gino(dsn=DATABASE_URI)
from fastapi import FastAPI from gino.ext.starlette import Gino from sqlalchemy.schema import MetaData from app.core.config import DATABASE_CONFIG, DEBUG, PROJECT_NAME, VERSION application: FastAPI = FastAPI(title=PROJECT_NAME, debug=DEBUG, version=VERSION) db: MetaData = Gino(application, dsn=DATABASE_CONFIG.url)
from gino.ext.starlette import Gino from starlette.applications import Starlette from app.events import errors from config.application import settings from routes import applications app = Starlette(debug=settings.DEBUG, routes=applications.routes) app.add_exception_handler(404, errors.error_response) app.add_exception_handler(500, errors.error_response) database = Gino(app, dsn=settings.SQLALCHEMY_DATABASE_URI)
import os # because main app used fast api 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): __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())
from fastapi import FastAPI from gino.ext.starlette import Gino from .config import settings from .routers import load_routers db = Gino() def get_app(db, database_url): app = FastAPI() db.config["dsn"] = database_url db.init_app(app) load_routers(app) return app app = get_app(db, settings.DATABASE_URL)
from gino.ext.starlette import Gino from core.factories import settings from ssl import create_default_context if not settings.DEBUG: ssl_object = create_default_context(cafile=settings.SSL_CERT_FILE) db: Gino = Gino( dsn=settings.DATABASE_URL, echo=False, ssl=ssl_object, pool_min_size=3, pool_max_size=20, retry_limit=1, retry_interval=1, ) else: db: Gino = Gino(dsn=settings.DATABASE_URL)
# coding: utf-8 from gino.ext.starlette import Gino from modularapi.settings import get_setting db = Gino(dsn=get_setting().PG_DNS)
DATE_FIELD = 'Rate Date' COST_FIELD = 'Buying Rate' RATE_FIELD = 'Central Rate' SALE_FIELD = 'Selling Rate' MAPPED_FIELDS = { COST_FIELD: 'cost', RATE_FIELD: 'rate', SALE_FIELD: 'sale', } # logger log = logging.getLogger(__name__) # database db = Gino(dsn=settings.DATABASE_URL) # source: https://iban.com/currency-codes class Currency(enum.Enum): # fmt: off # standard names CFA_FRANC = 'XOF' DANISH_KRONE = 'DKK' EURO = 'EUR' NAIRA = 'NGN' POUND_STERLING = 'GBP' RAND = 'ZAR' SAUDI_RIYAL = 'SAR' SWISS_FRANC = 'CHF' US_DOLLAR = 'USD'
async def _app(**kwargs): app = Starlette() kwargs.update({ "kwargs": dict( max_inactive_connection_lifetime=_MAX_INACTIVE_CONNECTION_LIFETIME, ), }) factory = kwargs.pop("factory", False) db_delayed = kwargs.pop("db_delayed", False) if db_delayed: async def start_proxy(_port): loop = asyncio.get_event_loop() app.db_proxy = await loop.create_server( lambda: ProxyServerProtocol(loop, DB_ARGS["host"], DB_ARGS[ "port"]), "localhost", _port, reuse_address=True, reuse_port=True, ) return app.db_proxy server = await start_proxy(0) for s in server.sockets: try: host, port = s.getsockname() break except ValueError: pass server.close() await server.wait_closed() app.start_proxy = lambda: start_proxy(port) kwargs["host"] = host kwargs["port"] = port kwargs["retry_limit"] = 4 kwargs["retry_interval"] = 0.5 if factory: db = Gino(**kwargs) db.init_app(app) else: db = Gino(app, **kwargs) 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 PlainTextResponse("Hello, world!") @app.route("/users/{uid:int}") async def get_user(request): uid = request.path_params.get("uid") method = request.query_params.get("method") q = User.query.where(User.id == uid) if method == "1": return JSONResponse((await q.gino.first_or_404()).to_dict()) elif method == "2": return JSONResponse( (await request["connection"].first_or_404(q)).to_dict()) elif method == "3": return JSONResponse((await db.bind.first_or_404(q)).to_dict()) elif method == "4": return JSONResponse((await db.first_or_404(q)).to_dict()) else: return JSONResponse((await User.get_or_404(uid)).to_dict()) @app.route("/users", methods=["POST"]) async def add_user(request): u = await User.create(nickname=(await request.json()).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 JSONResponse(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 fastapi import FastAPI from core.config import settings from gino.ext.starlette import Gino app: FastAPI = FastAPI(title=settings.PROJECT_NAME, version=settings.VERSION) db: Gino = Gino(dsn=settings.get_postgres_dsn()) db.init_app(app) from api.api_v1.api import router app.include_router(router, prefix=settings.API_VERSION_STR)
from fastapi import FastAPI from gino.ext.starlette import Gino from sqlalchemy.schema import MetaData from .settings.globals import DATABASE_CONFIG app: FastAPI = FastAPI() db: MetaData = Gino(app, dsn=DATABASE_CONFIG.url)
import logging from gino.ext.starlette import Gino from ..core.config import DB_DSN logging.getLogger('gino.engine').setLevel(logging.ERROR) db = Gino(dsn=DB_DSN, echo=False)
from datetime import datetime from gino.ext.starlette import Gino from sqlalchemy import Column, DateTime, String from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.sql.sqltypes import Boolean from .config import config db = Gino( dsn=config["DB_URL"], pool_min_size=config["DB_POOL_MIN_SIZE"], pool_max_size=config["DB_POOL_MAX_SIZE"], echo=config["DB_ECHO"], ssl=config["DB_SSL"], use_connection_for_request=config["DB_USE_CONNECTION_FOR_REQUEST"], retry_limit=config["DB_RETRY_LIMIT"], retry_interval=config["DB_RETRY_INTERVAL"], ) class Request(db.Model): __tablename__ = "requests" request_id = Column(UUID, primary_key=True) username = Column(String, nullable=False) policy_id = Column(String, nullable=False) revoke = Column(Boolean, default=False, nullable=False) status = Column(String, nullable=False) created_time = Column(DateTime, default=datetime.utcnow, nullable=False) updated_time = Column(DateTime, default=datetime.utcnow, nullable=False)
import os from fastapi import FastAPI from gino.ext.starlette import Gino from pydantic import BaseModel app = FastAPI() db = Gino( app, host=os.getenv("DB_HOST", "localhost"), port=os.getenv("DB_PORT", 5432), user=os.getenv("DB_USER", "postgres"), password=os.getenv("DB_PASS", ""), database=os.getenv("DB_NAME", "postgres"), ) class User(db.Model): __tablename__ = "simple_fastapi_demo_users" id = db.Column(db.BigInteger(), primary_key=True) nickname = db.Column(db.Unicode(), default="unnamed") class UserModel(BaseModel): name: str @app.get("/") async def index(): return {"message": "Hello, world!"}
import os from gino.ext.starlette import Gino DATABASE_HOST = os.getenv("DATABASE_HOST", "localhost") DATABASE_PORT = int(os.getenv("DATABASE_PORT", "5432")) db = Gino( dsn=f"postgresql://*****:*****@{DATABASE_HOST}:{DATABASE_PORT}/postgres", )