# note: https://responder.kennethreitz.org/en/latest/search.html?q=resp.content from hub import methods def generate_app(): """""" from api.url import action_methods # from factories.line_manage import LineManage # see: https://lzomedia.com/blog/host-fastapi-backend-api-and-react-app-frontend-locally/ # --- define middleware --- see: https://www.starlette.io/middleware/ # from starlette.applications import Starlette # from starlette.middleware import Middleware # # from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware # # from starlette.middleware.trustedhost import TrustedHostMiddlewar # middleware = [ # Middleware( # TrustedHostMiddleware, # allow_credentials=True, # allowed_hosts=['*'], # allow_methods=["*"], # allow_headers=["*"], # ), # # Middleware(HTTPSRedirectMiddleware) # ] # --- define app --- see: https://responder.kennethreitz.org/en/latest/tour.html#cors import responder app = responder.API( # cors=True, # allow_methods=['*'], # allow_credentials=True, ) async def coroutine_method(module, method, _params): """协程方法""" # run_at = time.time() result = await getattr(module, method)(**_params) # methods.debug_log(f"app.coroutine_method", f"use time {round(time.time() - run_at, 2)}s") return result def foreground_method(module, method, _params): """等待返回""" # run_at = time.time() result = getattr(module, method)(**_params) # methods.debug_log(f"app.foreground_method", f"use time {round(time.time() - run_at, 2)}s") return result @app.background.task def background_method(module, method, _params): """不等返回""" # run_at = time.time() result = getattr(module, method)(**_params) # methods.debug_log(f"app.background_method", f"use time {round(time.time() - run_at, 2)}s") return result async def run_method(_method_key, _params): if _method_key not in action_methods: return dict(code=3, details=f"{_method_key} not found!") else: module, method, method_type = action_methods[_method_key] del _params['module'] del _params['method'] if method_type == 'IsAsync': return await coroutine_method(module, method, _params) elif method_type == 'IsBack': return foreground_method(module, method, _params) elif method_type == 'NoBack': return background_method(module, method, _params) @app.route('/api') async def web_api(request, response): try: if request.params: params = dict(request.params.items()) else: params = await request.media() # --- todo 存在get请求只能接受一个参数的问题 --- if 'mp3_name' in params: params['module'] = 'TEST' params['method'] = 'test011' methods.debug_log('app.web_api', f"m-60: params is {params}") if not params.get('module'): response.media = dict(code=1, details=f"module is null!") elif not params.get('method'): response.media = dict(code=2, details=f"method is null!") else: method_key = f"{params.get('module')}.{params.get('method')}" result = await run_method(method_key, params) if result.__class__.__name__ == 'bytes': response.content = result elif result.__class__.__name__ == 'str': response.text = result elif result.__class__.__name__ == 'dict': response.media = result elif result.__class__.__name__ == 'Future': response.media = dict(code=0, details=f"{result} is running.") elif not result: response.media = dict(code=0, details=f"return is null.") else: response.media = dict(code=0, details=f"return type is {result.__class__.__name__}.") except Exception as exception: methods.debug_log('app.web_api', f"m-86: exception | {exception}") methods.debug_log('app.web_api', f"m-86: traceback | {methods.trace_log()}") response.media = dict(code=-1, details=f"{methods.trace_log()}") @app.route('/line', websocket=True) async def line(ws): """ let wsuri = `${location.protocol === 'https' ? 'wss' : 'ws'}://${location.host}:8801/line`; connect_json_text = { line_id: 连接id,暂为token } ) send_json_text_1 = { face_uuid: 匹配到的人脸id face_name: 人脸名称 input_face_b64: 抓拍图片(b64格式字符串) } """ try: await ws.accept() while True: data = await ws.receive_text() # 消息接受方法 receive_{text/json/bytes} if not data: methods.debug_log('app.line', f"error code is 1!") break if not methods.is_json(data): methods.debug_log('app.line', f"error code is 2!") break data = methods.json_loads(data) # methods.debug_log('app.line', f"data: {data}") if not data.get('line_id'): methods.debug_log('api.line', f"error code is 3!") break # --- check --- if not data.get('line_id'): methods.debug_log('api.line', f"error code is 4!") break # --- save --- line_id = data.get('line_id') # LineManage.line_dict[line_id] = ws except Exception as exception: if exception.__class__.__name__ == 'WebSocketDisconnect': await ws.close() else: methods.debug_log('app.line', f"m-136: exception | {exception}") methods.debug_log('app.line', f"m-136: traceback | {methods.trace_log()}") # --- return --- return app