lenML/ChatTTS-Forge
301
1import fnmatch2import logging3 4from fastapi import FastAPI5from fastapi.middleware.cors import CORSMiddleware6from fastapi.staticfiles import StaticFiles7 8 9def is_excluded(path, exclude_patterns):10 """11 检查路径是否被排除12 13 :param path: 需要检查的路径14 :param exclude_patterns: 包含通配符的排除路径列表15 :return: 如果路径被排除,返回 True;否则返回 False16 """17 for pattern in exclude_patterns:18 if fnmatch.fnmatch(path, pattern):19 print(path, pattern)20 return True21 return False22 23 24class APIManager:25 def __init__(self, app: FastAPI, exclude_patterns=[]):26 self.app = app27 self.registered_apis = {}28 self.logger = logging.getLogger(__name__)29 self.exclude = exclude_patterns30 31 def is_excluded(self, path):32 return is_excluded(path, self.exclude)33 34 def set_cors(35 self,36 allow_origins: list = ["*"],37 allow_credentials: bool = True,38 allow_methods: list = ["*"],39 allow_headers: list = ["*"],40 ):41 # reset middleware stack42 self.app.middleware_stack = None43 self.app.add_middleware(44 CORSMiddleware,45 allow_origins=allow_origins,46 allow_credentials=allow_credentials,47 allow_methods=allow_methods,48 allow_headers=allow_headers,49 )50 self.app.build_middleware_stack()51 52 def setup_playground(self):53 app = self.app54 app.mount(55 "/playground",56 StaticFiles(directory="playground", html=True),57 name="playground",58 )59 60 def get(self, path: str, **kwargs):61 def decorator(func):62 if self.is_excluded(path):63 return func64 65 self.app.get(path, **kwargs)(func)66 67 self.registered_apis[path] = func68 self.logger.info(f"Registered API: GET {path}")69 70 return func71 72 return decorator73 74 def post(self, path: str, **kwargs):75 def decorator(func):76 if self.is_excluded(path):77 return func78 79 self.app.post(path, **kwargs)(func)80 81 self.registered_apis[path] = func82 self.logger.info(f"Registered API: POST {path}")83 84 return func85 86 return decorator87 