APP_SSL_KEY = os.environ.get('APP_SSL_KEY', None) if APP_SSL_CERT and APP_SSL_KEY: APP_SSL = {"cert": APP_SSL_CERT, "key": APP_SSL_KEY} else: APP_SSL = None # MongoDB settings MONGODB_USERNAME = os.environ.get("MONGODB_USERNAME", "user") MONGODB_PASSWORD = os.environ.get("MONGODB_PASSWORD", "password") MONGODB_HOST = os.environ.get("MONGODB_HOST", "mongodb") MONGODB_PORT = to_int(os.environ.get("MONGODB_PORT", 27017)) MONGODB_DATABASE = os.environ.get("MONGODB_DATABASE", "") MONGODB_URI = 'mongodb://{}:{}@{}:{}/{}'.format(MONGODB_USERNAME, MONGODB_PASSWORD, MONGODB_HOST, MONGODB_PORT, MONGODB_DATABASE) LAZY_UMONGO = MotorAsyncIOInstance() # AMQP settings AMQP_USERNAME = os.environ.get("AMQP_USERNAME", "user") AMQP_PASSWORD = os.environ.get("AMQP_PASSWORD", "password") AMQP_HOST = os.environ.get("AMQP_HOST", "rabbitmq") AMQP_PORT = to_int(os.environ.get("AMQP_PORT", 5672)) AMQP_VIRTUAL_HOST = os.environ.get("AMQP_VIRTUAL_HOST", "vhost") AMQP_USING_SSL = to_bool(os.environ.get("AMQP_USING_SSL", False)) # Settings for tests TEST_MONGODB_USERNAME = os.environ.get("TEST_MONGODB_USERNAME", "root") TEST_MONGODB_PASSWORD = os.environ.get("TEST_MONGODB_PASSWORD", "root") TEST_MONGODB_HOST = os.environ.get("MONGODB_HOST", "mongodb") TEST_MONGODB_PORT = to_int(os.environ.get("MONGODB_PORT", 27017)) TEST_MONGODB_DATABASE = os.environ.get("MONGODB_DATABASE", 'test_database')
import asyncio import logging from aiohttp import web from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase from umongo import MotorAsyncIOInstance logger = logging.getLogger(__name__) instance = MotorAsyncIOInstance() async def init_mongo(app: web.Application, mongodb_uri: str) -> AsyncIOMotorDatabase: logger.info(f'init mongo') loop = asyncio.get_event_loop() conn = AsyncIOMotorClient(mongodb_uri, io_loop=loop) return conn.get_database() async def setup_mongo(app: web.Application) -> None: config = app['config'] app['db'] = await init_mongo(app, config.MONGODB_URI) instance.init(app['db']) async def close_mongo(app: web.Application) -> None: logger.info('close mongo') app['db'].client.close() app.on_cleanup.append(close_mongo)
import os from sanic import Sanic from sanic_mongodb_ext import MongoDbExtension from umongo import MotorAsyncIOInstance from trem.views import bp # Create Sanic App app = Sanic(__name__) # Add static folder app.static('/static', './static') # Config Mongo project_name = os.getenv('PROJECT_NAME') app.config.update({ "MONGODB_DATABASE": project_name, "MONGODB_URI": f"mongodb://mongo_{project_name}:27017", "LAZY_UMONGO": MotorAsyncIOInstance(), }) MongoDbExtension(app) instance = app.config["LAZY_UMONGO"] # Config Views from Blueprint app.blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=5000)