跳到主要内容

在FastAPI中使用OpenBB与Depends

本页面演示了如何高效地将OpenBB Python包导入FastAPI应用程序, 以便在任何端点中使用。

下面的代码是一个完整的示例,用于在调用obb.equity.price.quote的API中包装Python接口。

最佳实践是将OpenBBApp创建为单独的文件,并在需要它的每个路由器文件中直接导入。

示例

"""在FastAPI依赖项中使用OpenBB Python接口的示例。"""

from typing import Annotated
from openbb_core.app.model.abstract.singleton import SingletonMeta
from fastapi import (
Depends,
FastAPI,
)

app = FastAPI()


class OpenBB(metaclass=SingletonMeta):
def __init__(self):
import openbb

self._obb = openbb.sdk

@property
def obb(self):
return self._obb


def get_openbb():
return OpenBB().obb


OpenBBApp = Annotated[OpenBB, Depends(get_openbb)]


@app.get("/quote")
async def quote(obb: OpenBBApp, symbol: str = "AAPL", provider: str = "yfinance"):
return obb.equity.price.quote(symbol, provider=provider).model_dump()["results"]


if __name__ == "__main__":
import uvicorn

uvicorn.run(app)
信息

通过将上面的代码块复制到新文件中启动服务器,然后从命令行作为脚本运行它。