import json from starlette.requests import Request from starlette.responses import JSONResponse from core.edge_util import camel_to_snake from core.config import settings def setup_routes(context, app): @app.get("/") async def system_info(): info = context.get_component("_database").system_info() return {"code": 0, "message": "success", "result": info} @app.get("/components") async def components(): return {"code": 0, "message": "success", "result": list(context.components.keys())} @app.middleware("http") async def add_process_time_header(request: Request, call_next): if request.url.path.startswith("/service"): req_body = await request.body() req_body = req_body.decode("utf-8") if req_body == '': req_body = "{}" req = json.loads(req_body) req.update(request.query_params) method = req.get('method') component = req.get('component') method = camel_to_snake(method) if req.get("method") is None: response = {"code": -1, "type": "service", "message": "没有method参数!"} else: if component == "" or component is None: executor = context else: executor = context.get_component(component) if executor: try: kwargs = {key: value for key, value in req.items() if key not in ["method", "component"]} result = await executor.execute(method, **kwargs) response = {"code": 0, "type": "service", "message": "success", "result": result} except Exception as e: response = {"code": -1, "type": "service", "message": str(e)} else: response = {"code": -2, "type": "service", "message": f"Executor {component} not found"} return JSONResponse(response) elif request.url.path.startswith("/task"): req_body = await request.body() req_body = req_body.decode("utf-8") if req_body == '': req_body = "{}" req = json.loads(req_body) try: result = await context.execute_task(**req) response = {"code": 0, "type": "task", "message": "success", "result": result} except Exception as e: response = {"code": -1, "type": "task", "message": str(e)} return JSONResponse(response) else: return await call_next(request)