Exemple #1
0
 def __init__(self, config):
     db = Gino(model_classes=tuple(gtfs_model.tables))
     app = web.Application(middlewares=[db])
     # I don't quite get why aiohttp says I shouldn't just use self.config
     # for this, but whatever
     app["config"] = config
     app["aiocache"] = SimpleMemoryCache()
     app["ansiconv"] = ansi2html.converter.Ansi2HTMLConverter(
         linkify=True, title="curlbus", font_size='16px')
     app['siriclient'] = SIRIClient(config["mot"]["url"],
                                    config["mot"]["user_id"])
     db.init_app(app)
     app.router.add_static(
         "/static/", os.path.join(os.path.dirname(__file__), '..',
                                  "static"))
     app.add_routes([
         web.get('/{stop_code:\d+}{tail:/*}', self.handle_station),
         web.get('/operators{tail:/*}', self.handle_operator_index),
         web.get('/nearby', self.handle_nearby),
         web.get('/{operator:\w+}{tail:/*}', self.handle_operator),
         web.get('/rail/stations{tail:/*}', self.handle_rail_stations),
         web.get('/rail/map{tail:/*}', self.handle_rail_map),
         web.get('/operators/{operator}/{route_number}{tail:/*}',
                 self.handle_route),
         web.get(
             '/operators/{operator}/{route_number}/{alternative}{tail:/*}',
             self.handle_route),
         web.get('/operators/{operator}{tail:/*}', self.handle_operator),
         web.get('/{operator}/{route_number}{tail:/*}', self.handle_route),
         web.get('/{operator}/{route_number}/{alternative}{tail:/*}',
                 self.handle_route),
         web.get('/{tail:/*}', self.handle_index)
     ])
     self._app = app
Exemple #2
0
async def init(loop):
    # Setup app.
    app = web.Application()

    # Setup routes
    for route in api.routes.routes:
        app.router.add_route(*route)

    # Setup DB connection
    await init_db()
    db = Gino()
    db.init_app(
        app,
        config={
            "user": "******",
            "password": "",
            "database": "gino",
            "host": "postgres"})

    # Setup middlewares
    middlewares = [
        db, validation_middleware, auth_middleware]
    app.middlewares.extend(middlewares)

    # Setup api_spec
    setup_aiohttp_apispec(
        app=app,
        title="Joke's API documentation",
        version='v1',
        url="/api/v1/docs/swagger.json",
        swagger_path="/api/v1/docs/")
    host = "0.0.0.0"
    port = 80
    return app, host, port
Exemple #3
0
async def _test_client(config):
    from aiohttp.test_utils import TestServer, TestClient

    db = Gino()
    app = web.Application(middlewares=[db])
    app['config'] = dict(gino=config)
    db.init_app(app)

    class User(db.Model):
        __tablename__ = 'gino_users'

        id = db.Column(db.BigInteger(), primary_key=True)
        nickname = db.Column('name', db.Unicode(), default='noname')

    routes = web.RouteTableDef()

    @routes.get('/')
    async def root(request):
        return web.Response(text='Hello, world!')

    @routes.get('/users/{uid}')
    async def get_user(request):
        uid = int(request.match_info['uid'])
        method = request.query.get('method')
        q = User.query.where(User.id == uid)
        if method == '1':
            return web.json_response((await q.gino.first_or_404()).to_dict())
        elif method == '2':
            return web.json_response(
                (await request['connection'].first_or_404(q)).to_dict())
        elif method == '3':
            return web.json_response((await db.bind.first_or_404(q)).to_dict())
        elif method == '4':
            return web.json_response(
                (await request.app['db'].first_or_404(q)).to_dict())
        else:
            return web.json_response((await User.get_or_404(uid)).to_dict())

    @routes.post('/users')
    async def add_user(request):
        form = await request.post()
        u = await User.create(nickname=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 web.json_response(u.to_dict())

    app.router.add_routes(routes)

    e = await gino.create_engine(PG_URL)
    try:
        try:
            await db.gino.create_all(e)
            async with TestClient(TestServer(app)) as rv:
                await yield_(rv)
        finally:
            await db.gino.drop_all(e)
    finally:
        await e.close()
Exemple #4
0
 def __init__(self, config):
     db = Gino(model_classes=tuple(gtfs_model.tables))
     app = web.Application(middlewares=[db])
     # I don't quite get why aiohttp says I shouldn't just use self.config
     # for this, but whatever
     app["config"] = config
     app["aiocache"] = SimpleMemoryCache()
     app["ansiconv"] = ansi2html.converter.Ansi2HTMLConverter(linkify=True,
                                                              title="curlbus",
                                                              font_size='16px')
     app['siriclient'] = SIRIClient(config["mot"]["url"],
                                    config["mot"]["user_id"])
     db.init_app(app)
     app.router.add_static("/static/", os.path.join(os.path.dirname(__file__), '..', "static"))
     app.add_routes([web.get('/{stop_code:\d+}{tail:/*}', self.handle_station),
                     web.get('/operators{tail:/*}', self.handle_operator_index),
                     web.get('/nearby', self.handle_nearby),
                     web.get('/{operator:\w+}{tail:/*}', self.handle_operator),
                     web.get('/rail/stations{tail:/*}', self.handle_rail_stations),
                     web.get('/rail/map{tail:/*}', self.handle_rail_map),
                     web.get('/operators/{operator}/{route_number}{tail:/*}', self.handle_route),
                     web.get('/operators/{operator}/{route_number}/{alternative}{tail:/*}', self.handle_route),
                     web.get('/operators/{operator}{tail:/*}', self.handle_operator),
                     web.get('/{operator}/{route_number}{tail:/*}', self.handle_route),
                     web.get('/{operator}/{route_number}/{alternative}{tail:/*}', self.handle_route),
                     web.get('/{tail:/*}', self.handle_index)])
     self._app = app
    def __init__(self, config):
        db = Gino(model_classes=tuple(gtfs_model.tables))
        app = web.Application(middlewares=[db])
        app["config"] = config

        db.init_app(app)
        app.add_routes([web.post('/{tail:.*}', self.handle_request)])
        self._app = app
Exemple #6
0
    def __init__(self, config):
        db = Gino(model_classes=tuple(gtfs_model.tables))
        app = web.Application(middlewares=[db])
        app["config"] = config

        db.init_app(app)
        app.add_routes([web.post('/{tail:.*}', self.handle_request)])
        self._app = app
Exemple #7
0
async def main(loop):

    await init_db()
    db = Gino()
    app = Application(middlewares=[db])

    db.init_app(app, config={'dsn': DB_ADDRESS})

    for model in models_collection:
        resource = GenericResource(model.__table__.name, model)
        resource.register(app.router)

    return app
async def client(aiohttp_client, loop):
    app, _, _ = await init(loop)

    db = Gino()

    db.init_app(app,
                config={
                    "user": "******",
                    "password": "",
                    "database": "gino",
                    "host": "postgres-test"
                })

    async with db.with_bind('postgresql://postgres@postgres-test/gino'):
        await db.gino.create_all()

    return await aiohttp_client(app)
Exemple #9
0
async def cli(loop, aiohttp_client):
    await init_db()

    db = Gino()
    app = Application(middlewares=[db])

    db.init_app(app, config={'dsn': DB_ADDRESS})

    authors = GenericResource('authors', Author)
    books = GenericResource('books', Book)
    countries = GenericResource('countries', Country)

    authors.register(app.router)
    books.register(app.router)
    countries.register(app.router)

    await _create_model_instances()
    yield await aiohttp_client(app)

    await teardown_db()
Exemple #10
0
def init_db(app: web.Application) -> Gino:
    db = Gino.init()
    db_conf = config.get("database")
    app["config"]["gino"] = db_conf
    db.init_app(app)
    host = db_conf.get("host", "postgres")
    user = db_conf.get("user", "postgres")
    database = db_conf.get("database", "gino")
    sync_db_engine = sa.create_engine(f"postgresql://{host}@{user}/"
                                      f"{database}")
    db.create_all(bind=sync_db_engine)
    sync_db_engine.dispose()
    return db
Exemple #11
0
import pathlib

from gino.ext.aiohttp import Gino

BASE_DIR = pathlib.Path(__file__).parent.parent

SHARED_SECRET_KEY = 'dskaty3786219tgedusadnhjouid12-0hnduj-inq3123'

DEBUG = False

HOST = '127.0.0.1'
PORT = '8000'

DATABASE = {
    'drivername': 'postgresql',
    'user': '',
    'password': '',
    'host': '',
    'port': '',
    'database': '',
    'username': ''
}

DB = Gino()

try:
    from .settings_local import *
except ImportError:
    pass
Exemple #12
0
async def _test_client(config, in_app_config=True):
    from aiohttp.test_utils import TestServer, TestClient

    db = Gino()
    app = web.Application(middlewares=[db])
    db_attr_name = "gino_db"
    config.update({
        "kwargs":
        dict(
            max_inactive_connection_lifetime=_MAX_INACTIVE_CONNECTION_LIFETIME,
        ),
    })
    if in_app_config:
        app["config"] = dict(gino=config)
        db.init_app(app, db_attr_name=db_attr_name)
    else:
        db.init_app(app, config, db_attr_name=db_attr_name)

    class User(db.Model):
        __tablename__ = "gino_users"

        id = db.Column(db.BigInteger(), primary_key=True)
        nickname = db.Column("name", db.Unicode(), default="unnamed")

    routes = web.RouteTableDef()

    @routes.get("/")
    async def root(request):
        conn = await request["connection"].get_raw_connection()
        # noinspection PyProtectedMember
        assert (conn._holder._max_inactive_time ==
                _MAX_INACTIVE_CONNECTION_LIFETIME)
        return web.Response(text="Hello, world!")

    @routes.get("/users/{uid}")
    async def get_user(request):
        uid = int(request.match_info["uid"])
        method = request.query.get("method")
        q = User.query.where(User.id == uid)
        if method == "1":
            return web.json_response((await q.gino.first_or_404()).to_dict())
        elif method == "2":
            return web.json_response(
                (await request["connection"].first_or_404(q)).to_dict())
        elif method == "3":
            return web.json_response((await db.bind.first_or_404(q)).to_dict())
        elif method == "4":
            return web.json_response(
                (await request.app[db_attr_name].first_or_404(q)).to_dict())
        else:
            return web.json_response((await User.get_or_404(uid)).to_dict())

    @routes.post("/users")
    async def add_user(request):
        form = await request.post()
        u = await User.create(nickname=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 web.json_response(u.to_dict())

    app.router.add_routes(routes)

    e = await gino.create_engine(PG_URL)
    try:
        try:
            await db.gino.create_all(e)
            async with TestClient(TestServer(app)) as rv:
                await yield_(rv)
        finally:
            await db.gino.drop_all(e)
    finally:
        await e.close()
Exemple #13
0
from datetime import datetime

from gino.ext.aiohttp import Gino
from sqlalchemy import or_

import settings

db = Gino()


class User(db.Model):
    """
    1) Можно кошелек сделать отдельное таблицей, если нужно заложить возможность использования
     пользователем нескольких кошельков. Да и пользователь должен быть в отдельном приложении
    2) Можно сделать страну и город отдельными таблицами с предвнесенными значениями
    """
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, nullable=False, index=True)
    country = db.Column(db.String(64), nullable=False)
    city = db.Column(db.String(64), nullable=False)
    currency = db.Column(db.String(3), nullable=False)
    balance = db.Column(db.Numeric(precision=12, scale=2),
                        default=0,
                        nullable=False)
    timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)


class Transaction(db.Model):
    """
Exemple #14
0
import os
from aiohttp import web
from gino.ext.aiohttp import Gino

DB_ARGS = dict(
    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"),
)
PG_URL = "postgresql://{user}:{password}@{host}:{port}/{database}".format(
    **DB_ARGS)

db = Gino()
app = web.Application(middlewares=[db])
config = {"dsn": PG_URL}
db.init_app(app, config=config)


class User(db.Model):
    __tablename__ = "gino_users"

    id = db.Column(db.BigInteger(), primary_key=True)
    nickname = db.Column("name", db.Unicode(), default="unnamed")


routes = web.RouteTableDef()


@routes.get("/")
Exemple #15
0
from gino.ext.aiohttp import Gino
from sqlalchemy.schema import MetaData

db: MetaData = Gino()
Exemple #16
0
async def _app(config, in_app_config=True, db_delayed=False):
    db = Gino()
    app = web.Application(middlewares=[db])
    db_attr_name = "gino_db"
    config.update({
        "kwargs":
        dict(
            max_inactive_connection_lifetime=_MAX_INACTIVE_CONNECTION_LIFETIME,
        ),
    })
    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)
        config["host"] = host
        config["port"] = port
        config["retry_limit"] = 4
        config["retry_interval"] = 0.5

    if in_app_config:
        app["config"] = dict(gino=config)
        db.init_app(app, db_attr_name=db_attr_name)
    else:
        db.init_app(app, config, db_attr_name=db_attr_name)

    class User(db.Model):
        __tablename__ = "gino_users"

        id = db.Column(db.BigInteger(), primary_key=True)
        nickname = db.Column("name", db.Unicode(), default="noname")

    routes = web.RouteTableDef()

    @routes.get("/")
    async def root(request):
        conn = await request["connection"].get_raw_connection()
        # noinspection PyProtectedMember
        assert conn._holder._max_inactive_time == _MAX_INACTIVE_CONNECTION_LIFETIME
        return web.Response(text="Hello, world!")

    @routes.get("/users/{uid}")
    async def get_user(request):
        uid = int(request.match_info["uid"])
        method = request.query.get("method")
        q = User.query.where(User.id == uid)
        if method == "1":
            return web.json_response((await q.gino.first_or_404()).to_dict())
        elif method == "2":
            return web.json_response(
                (await request["connection"].first_or_404(q)).to_dict())
        elif method == "3":
            return web.json_response((await db.bind.first_or_404(q)).to_dict())
        elif method == "4":
            return web.json_response(
                (await request.app[db_attr_name].first_or_404(q)).to_dict())
        else:
            return web.json_response((await User.get_or_404(uid)).to_dict())

    @routes.post("/users")
    async def add_user(request):
        form = await request.post()
        u = await User.create(nickname=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 web.json_response(u.to_dict())

    app.router.add_routes(routes)

    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()
Exemple #17
0
import os

from aiohttp import web
from gino.ext.aiohttp import Gino

# Database Configuration
PG_URL = "postgresql://{user}:{password}@{host}:{port}/{database}".format(
    host=os.getenv("DB_HOST", "db"),
    port=os.getenv("DB_PORT", 5432),
    user=os.getenv("DB_USER", "postgres"),
    password=os.getenv("DB_PASSWORD", ""),
    database=os.getenv("DB_DATABASE", "postgres"),
)

# Initialize Gino instance
db = Gino()

# Initialize aiohttp app
app = web.Application(middlewares=[db])
db.init_app(app, dict(dsn=PG_URL))


# Definition of table
class Message(db.Model):
    __tablename__ = "messages"

    id = db.Column(db.BigInteger(), primary_key=True)
    recipient = db.Column(db.Unicode())
    source = db.Column(db.Integer())
    status = db.Column(db.Unicode(), default="new")
    body = db.Column(db.Unicode())