import asyncio import platform from contextlib import asynccontextmanager from aiokafka.errors import KafkaConnectionError from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from starlette.staticfiles import StaticFiles import routers from constants import API_ROOT from external.kafka import consume_messages from external.kafka.producer import init_producer, get_producer origins = [ 'http://localhost:5173' ] @asynccontextmanager async def lifespan(app: FastAPI): try: await init_producer() producer = await get_producer() if producer: await producer.start() except KafkaConnectionError as e: print(e) consumer_task = asyncio.create_task(consume_messages()) yield producer = await get_producer() if producer: await producer.stop() consumer_task.cancel() app = FastAPI(lifespan=lifespan, separate_input_output_schemas=False, root_path='/api') app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) routers_list = [ routers.attribute_router, routers.auth_router, routers.card_router, routers.card_group_router, routers.client_router, routers.service_router, routers.product_router, routers.barcode_router, routers.shipping_warehouse_router, routers.position_router, routers.user_router, routers.role_router, routers.marketplace_router, routers.payroll_router, routers.time_tracking_router, routers.billing_router, routers.task_router, routers.statistics_router, routers.work_shifts_router, routers.work_shifts_planning_router, routers.transaction_router, routers.shipping_router, routers.department_router, routers.residues_router, routers.project_router, routers.board_router, routers.status_router, routers.card_tag_router, routers.chat_router, routers.wms_router, ] for router in routers_list: app.include_router(router) app.mount("/static", StaticFiles(directory="static"), name="static")