【问题标题】:Running fastapi within class在课堂上运行 fastapi
【发布时间】:2021-06-10 01:11:14
【问题描述】:
import uvicorn
from fastapi import FastAPI

# 2. Create the app object
app = FastAPI()

# 3. Index route, opens automatically on http://127.0.0.1:8000
class RunModel():
    @app.get('/')
    def index(self):
        return {'message': 'Hello'}

    @app.get('/predict')
    def get_res(self, feat1: float, feat2:float):
        res = feat1 + feat2
        return {'result': f'{res:.4f}'}

run_model = RunModel()
# 5. Run the API with uvicorn
#    Will run on http://127.0.0.1:8000
if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=8000)

当我首先运行它时,我得到了错误(在终端而不是浏览器中)422 Unprocessable Entity。接下来是当我访问 http://localhost:8000/docs 时,它似乎希望我为 /predict 路由输入 3 个值,这两个功能符合预期和 self。所以问题是我怎样才能使用这个类结构并且仍然使用fastapi(即忽略self)。

【问题讨论】:

    标签: python fastapi


    【解决方案1】:

    你可以这样做:

    from fastapi import FastAPI
    import uvicorn
    
    class Settings:
        def __init__(self):
            self.api_version = "v1"
            self.api_name = "my_api"
            self.db = "some db"
            self.logger = "configured logger"
            self.DEBUG = True
    
    
    class MyApi:
        def __init__(self, settings):
            self.settings = settings
            self._fastapi = FastAPI(
                version=self.settings.api_version,
            )
            self._fastapi.add_api_route(
                path="/",
                endpoint=self.index,
                methods=["GET"]
            )
    
            self._fastapi.add_api_route(
                path="/predict",
                endpoint=self.get_res,
                methods=["POST"]
            )
    
        async def index(self):
            if self.settings.DEBUG:
                pass
            return {"message": "Hello"}
    
        async def get_res(self, feat1: float, feat2: float):
            """
            You are able to access the settings
            """
            res = feat1 + feat2
            return {"result": f"{res:.4f}", "api_version": self.settings.api_version}
    
        def __getattr__(self, attr):
            if hasattr(self._fastapi, attr):
                return getattr(self._fastapi, attr)
            else:
                raise AttributeError(f"{attr} not exist")
    
        async def __call__(self, *args, **kwargs):
            return await self._fastapi(*args, **kwargs)
    
    
    settings = Settings()
    app = MyApi(settings)
    
    
    if __name__ == "__main__":
        uvicorn.run(app, host="0.0.0.0", port=8000)
    

    【讨论】:

      【解决方案2】:

      使用来自fastapi-utils 的基于类的视图。

      使用 InferringRouter 创建一个路由器,然后用cbv 对象装饰类。在类中,您可以使用 router 对象开始创建端点。

      import uvicorn
      from fastapi import FastAPI
      from fastapi_utils.cbv import cbv
      from fastapi_utils.inferring_router import InferringRouter
      
      
      app = FastAPI()
      router = InferringRouter()
      
      
      @cbv(router)
      class RunModel:
          @router.get("/")
          def index(self):
              return {"message": "Hello"}
      
          @router.get("/predict")
          def get_res(self, feat1: float, feat2: float):
              res = feat1 + feat2
              return {"result": f"{res:.4f}"}
      
      
      app.include_router(router)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-05
        • 1970-01-01
        • 2019-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多