def create_app(debug: bool = False) -> web.Application:
    """Init application"""
    app = web.Application(debug=debug)

    load_config(app)
    setup_routes(app)

    app.cleanup_ctx.append(init_pg)
    return app
Beispiel #2
0
def init_app():
    load_config()
    init_logging()

    app = FastAPI(
        title=SERVICE_NAME,
        description=MSG_SERVICE_DESCRIPTION,
        version=VERSION,
    )

    app.include_router(router, prefix=f"/{SERVICE_NAME}")

    return app
Beispiel #3
0
    async def get_application(self):
        """
        Override the get_app method to return your application.
        """
        with open(BASE_DIR / "tests.yaml") as f:
            app = create_app(config=load_config(f))

        return await app
Beispiel #4
0
def create_wsgi():
    application = FlaskApp(__name__)
    config = settings.load_config((
        settings.FlaskSettings,
        settings.SentrySetting,
    ))
    application.app.config.from_object(config)
    CORS(application.app)

    application.add_api(specification='v1/openapi.yaml',
                        resolver=VersionResolver('app.http.v1.handlers'),
                        strict_validation=True,
                        validate_responses=True)

    @application.app.teardown_appcontext
    def shutdown_session(exception):
        models.session.remove()

    sentry_init(dsn=config.SENTRY_DSN,
                integrations=[sentry_flask.FlaskIntegration()])

    return application
Beispiel #5
0
from sentry_sdk import init as sentry_init
from sentry_sdk.integrations import sqlalchemy as sentry_sqlalchemy
from sqlalchemy.engine import create_engine
from app import settings
from ._base import (
    Base,
    session,
    enable_time_logging,
)
from .task import Task
from .user import User


config = settings.load_config(
    (settings.SQLAlchemySettings, settings.SentrySetting,)
)
if config.QUERY_TIME_LOGGING:
    enable_time_logging(config.QUERY_TIME_THRESHOLD)

engine = create_engine(         # pylint: disable=C0103
    config.SQLALCHEMY_DATABASE_URI,
    convert_unicode=True,
    echo=bool(config.SQLALCHEMY_ENGINE_LOG)
)
session.configure(bind=engine)

sentry_init(
    dsn=config.SENTRY_DSN,
    integrations=(sentry_sqlalchemy.SqlalchemyIntegration(),)
)
Beispiel #6
0
            await cur.execute(
                "create table flags_shop.users (user_id INT primary key AUTO_INCREMENT, username VARCHAR(44) NOT NULL UNIQUE)")
        except Exception as ex:
            pass
        try:
            await cur.execute(
                "create table flags_shop.comments (comment_id INT primary key AUTO_INCREMENT, text VARCHAR(64) NOT NULL, private BOOLEAN NOT NULL, author_id INT)")
        except Exception as ex:
            pass
        try:
            await cur.execute(
                "alter table flags_shop.comments ADD FOREIGN KEY (author_id) REFERENCES users(user_id)")
        except Exception as ex:
            pass
        await admin_conn.commit()
    admin_conn.close()


if __name__ == "__main__":
    admin_db_config = load_config('config/admin.toml')['database']
    user_db_config = load_config('config/user.toml')['database']
    teardown_db(executor_config=admin_db_config, target_config=user_db_config)
    setup_db(executor_config=admin_db_config, target_config=user_db_config)
    create_tables(target_config=user_db_config)
    create_sample_data(target_config=user_db_config)
    mongo_loop = asyncio.get_event_loop()
    mysql_loop = asyncio.get_event_loop()
    mongo_loop.run_until_complete(init(mongo_loop, user_db_config))
    mysql_loop.run_until_complete(init_mysql(mysql_loop, admin_db_config))
    mysql_loop.run_until_complete(generate_mysql(mysql_loop, admin_db_config))
Beispiel #7
0
from app import create_app

try:
    import uvloop
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
    print("Library uvloop is not available")

parser = argparse.ArgumentParser(description="aiohttp")
parser.add_argument("--host", help="Host to listen", default="0.0.0.0")
parser.add_argument("--port", help="Port to accept connection", default="8080")
parser.add_argument("--debug",
                    action="store_true",
                    help="Autoreload code on change")
parser.add_argument("--db", help="Path to database")
parser.add_argument("-c",
                    "--config",
                    type=argparse.FileType(),
                    help="Path to configuration file")

args = parser.parse_args()

app = create_app(config=load_config(args.config), db_url=args.db)

if args.debug:
    print("Debug mode activated")
    aioreloader.start()

if __name__ == '__main__':
    web.run_app(app, host=args.host, port=args.port)
Beispiel #8
0
def run(config_path: str = None):
    config = load_config(config_path)
    app = create_app(config)
    web.run_app(app, port=config['port'])
def setup_db():
    conf = load_config()
    return AsyncIOMotorClient(conf["database_uri"]).control_conf
Beispiel #10
0
def main(config_path, port):
    config = load_config(config_path)
    app = create_app(config)
    app.run(port, debug=True, use_default_access_log=True)
Beispiel #11
0
from app.settings import load_config
config = load_config()
Beispiel #12
0
async def client(aiohttp_client):
    config = load_config()
    app = await create_app(config)
    await preload_data(app)
    return await aiohttp_client(app)
Beispiel #13
0
def create_tables(target_config=None):
    engine = get_engine(target_config)

    meta = MetaData()
    meta.create_all(bind=engine, tables=[cars, characters])


def drop_tables(target_config=None):
    engine = get_engine(target_config)

    meta = MetaData()
    meta.drop_all(bind=engine, tables=[cars, characters])


if __name__ == '__main__':
    user_db_config = load_config('config/user_config.toml')['database']
    admin_db_config = load_config('config/config.toml')['database']

    parser = argparse.ArgumentParser(description='DB related shortcuts')
    parser.add_argument("-c",
                        "--create",
                        help="Create empty database and user with permissions",
                        action='store_true')
    parser.add_argument("-d",
                        "--drop",
                        help="Drop database and user role",
                        action='store_true')
    parser.add_argument("-r",
                        "--recreate",
                        help="Drop and recreate database and user",
                        action='store_true')
 def config(self):
     if self.__config is None:
         from app.settings import load_config
         self.__config = load_config()
     return self.__config
import argparse
import aiohttp
from app import create_app
from app.settings import load_config

parser = argparse.ArgumentParser(description=" project")
parser.add_argument("--host", help="Host to listen", default="0.0.0.0")
parser.add_argument("--port", help="Port to accept connections", default=8000)
parser.add_argument("--reload",
                    action="store_true",
                    help="Autoreload code on change")
parser.add_argument("-c",
                    "--config",
                    type=argparse.FileType("r"),
                    help="Path to configuration file")

args = parser.parse_args()

app = create_app(config=load_config(args.config))

if __name__ == "__main__":
    aiohttp.web.run_app(app, host=args.host, port=args.port)
Beispiel #16
0
async def get_app(configpath):
    config = load_config(configpath)
    # logging.basicConfig(level=logging.DEBUG)
    loop = asyncio.get_event_loop()
    app = await init_app(config, loop)
    return app
Beispiel #17
0

@bot.message_handler(commands=['start'])
def handler_start(message: telebot.types.Message):
    """
    Метод старта бота. Для отправки вступительного письма
    :param message: Входящий запрос
    :return:
    """
    logger(message.json)
    response_text = GREETING_MESSAGE
    bot.send_message(message.chat.id, response_text)


@bot.message_handler(commands=['help'])
def handler_help(message: telebot.types.Message):
    """
    Справочный метод для помощи пользователям
    :param message: Входящий запрос
    :return:
    """
    logger(message.json)
    response_text = HELP_MESSAGE.format(TABLE_URL)
    bot.send_message(message.chat.id, response_text)


if __name__ == '__main__':
    load_config()
    init_databases(CONFIG)
    bot.polling(none_stop=True, interval=0, timeout=20)
Beispiel #18
0
import logging
import os
from pathlib import Path
from asyncpg import connect
import pytest
from aioresponses import aioresponses
from app.app import create_app
from app.settings import load_config

logger = logging.getLogger('conftest')
pytest_plugins = 'aiohttp.pytest_plugin'

file_path = Path(__file__).parent / 'test_config.yaml'
with open(file_path, 'r') as config_file:
    test_config_dict = load_config(config_file)


@pytest.fixture
def samples_list():
    samples_dir = Path(__file__).parent / 'test_samples/samples/'
    samples_path_list = [
        os.path.join(samples_dir, item) for item in os.listdir(samples_dir)
        if item.endswith('.json')
    ]
    return samples_path_list


@pytest.fixture
def one_citizen_sample():
    sample = Path(__file__).parent / 'test_samples/samples/sample_1.json'
    return sample