async def get_consumer(self): if not self._consumer: self._consumer = AIOKafkaConsumer( get_settings().KAFKA_TOPIC, loop=loop, group_id="group1", bootstrap_servers=get_settings().KAFKA_BOOTSTRAP_SERVERS, ) await self._consumer.start() return self._consumer
async def get_producer(self): if not self._producer: self._producer = AIOKafkaProducer( loop=loop, bootstrap_servers=get_settings().KAFKA_BOOTSTRAP_SERVERS) await self._producer.start() return self._producer
async def register_tortoise_async(): m = import_submodules("tifa.models") await Tortoise.init( db_url=get_settings().POSTGRES_DATABASE_URI, modules={ "models": list(m.keys()), }, )
def setup_db_models(app): m = import_submodules("tifa.models") register_tortoise( app, db_url=get_settings().POSTGRES_DATABASE_URI, modules={ "models": ["tifa.models"], }, )
async def register_tortoise_async(): m = import_submodules("tifa.models") await Tortoise.init( db_url=get_settings().POSTGRES_DATABASE_URI, modules={ "models": list(m.keys()), }, ) def create_app(settings: TifaSettings): app = TifaFastApi( debug=settings.DEBUG, title=settings.TITLE, description=settings.DESCRIPTION, ) setup_db_models(app) # 初始化路由 setup_routers(app) setup_static_files(app, settings) # 初始化全局 error_handler setup_error_handlers(app) # 初始化全局 middleware setup_middleware(app) # 初始化全局 middleware setup_cli(app) setup_logging(app) return app current_app = create_app(settings=get_settings())
def settings(self) -> TifaSettings: return get_settings()
import logging import aioredis from tifa.settings import get_settings logger = logging.getLogger(__name__) class MyRedis: _pool = None def __init__(self, dsn: str): self.dsn = dsn async def get_pool(self): if not self._pool: self._pool = await aioredis.create_redis_pool(self.dsn) return self._pool redis = MyRedis(get_settings().REDIS_CACHE_URI)
async def send(self, data): producer = await self.get_producer() await producer.send(get_settings().KAFKA_TOPIC, json.dumps(data))