如何在FastAPI中的HTTP请求之间共享变量?

发布于 2025-01-10 06:15:44 字数 939 浏览 1 评论 0 原文

如何在 FastAPI 中的 HTTP 请求之间共享变量值?例如,我有一个 POST 请求,在该请求中我获取了一些音频文件,然后将它们的信息转换为 Pandas Dataframe。我想在 GET 请求中发送该 Dataframe,但我无法访问 GET 上的 Dataframe > 请求范围。

@app.post(
    path="/upload-audios/",
    status_code=status.HTTP_200_OK
)
async def upload_audios(audios: list[UploadFile] = File(...)):
    filenames = [audio.filename for audio in audios]
    audio_data = [audio.file for audio in audios]
    new_data = []
    final_data = []
    header = ["name", "file"]
    for i in range(len(audios)):
        new_data = [filenames[i], audio_data[i]]
        final_data.append(new_data)
    new_df = pd.DataFrame(final_data, columns=header)
    return f"You have uploaded {len(audios)} audios which names are: {filenames}"

@app.get("/get-dataframe/")
async def get_dataframe():
    pass

How can I share the value of variables between HTTP requests in FastAPI? For instance, I have a POST request in which I get some audio files and then I convert their info into a Pandas Dataframe. I would like to send that Dataframe in a GET request, but I can't access the Dataframe on the GET request scope.

@app.post(
    path="/upload-audios/",
    status_code=status.HTTP_200_OK
)
async def upload_audios(audios: list[UploadFile] = File(...)):
    filenames = [audio.filename for audio in audios]
    audio_data = [audio.file for audio in audios]
    new_data = []
    final_data = []
    header = ["name", "file"]
    for i in range(len(audios)):
        new_data = [filenames[i], audio_data[i]]
        final_data.append(new_data)
    new_df = pd.DataFrame(final_data, columns=header)
    return f"You have uploaded {len(audios)} audios which names are: {filenames}"

@app.get("/get-dataframe/")
async def get_dataframe():
    pass

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

难如初 2025-01-17 06:15:44

如果您需要对该变量进行只读访问,并且/或您从不希望在读取它之前它会被其他请求修改(换句话说,您从不希望为多个客户端提供服务) ,以及您的应用使用多个工作线程 ——自从每个工作线程都有自己的东西、变量和内存) - 你可以(正如 @MatsLindh 在上面的评论中提到的)在端点外部(换句话说,全局)声明一个字典,例如,foo = {},并在端点内部为其分配一个键,例如, foo['pd'] = df(稍后您可以在另一个请求到达时检索该变量),或者将您的变量声明为 global (如此处),或者最好是将变量存储在应用实例上,这允许您使用通用 app.state 属性存储任意额外状态 - 请参阅此答案介绍如何在应用程序启动之前执行此操作。例如:

from fastapi import FastAPI

app = FastAPI()

@app.post("/create")
async def create_dataframe():
    # df = ...  # create the df here
    app.state.df = df

然后,在 get_dataframe 端点内,您可以像这样检索 df

@app.get("/get")
async def get_dataframe():
    df = app.state.df

或者,如果 app 实例在您正在工作的文件(假设您在子模块中定义了端点,与主模块分开,如所述此处),您可以从 Request 对象获取 app 实例:

from fastapi import Request

@app.get('/get')
async def get_dataframe(request: Request):
    df = request.app.state.df

否则,如果您需要该变量/对象为 <在不同客户端以及多个进程/工作进程之间共享,可能还需要对其进行读/写访问,您应该使用数据库存储,例如 PostgreSQL, SQLiteMongoDB、等,或者Key-Value存储(缓存),例如Redis< /a>、Memcached 等。您可能想看看这个答案也是如此。

If you need read-only access to that variable, and/or you never expect it to be modified by some other request before reading it (in other words, you never expect to serve more than one client), as well as your app does not use several workers—since each worker has its own things, variables and memory)—you could either (as mentioned by @MatsLindh in the comments above) declare a dictionary, e.g., foo = {}, outside the endpoints (in other words, globally) and assign a key to it inside the endpoint, e.g., foo['pd'] = df, (which you can later retrieve when another request arrives), or declare your variable as global (as described here), or, preferably, store the variable on the app instance, which allows you to store arbitrary extra state using the generic app.state attribute—see this answer on how to do this before the application starts up. For example:

from fastapi import FastAPI

app = FastAPI()

@app.post("/create")
async def create_dataframe():
    # df = ...  # create the df here
    app.state.df = df

Then, inside the get_dataframe endpoint, you can retrieve the df like this:

@app.get("/get")
async def get_dataframe():
    df = app.state.df

or, if the app instance is not available in the file from which you are working (let's say you have your endpoints defined in submodules, separately from the main module, as described here), you could get the app instance from the Request object:

from fastapi import Request

@app.get('/get')
async def get_dataframe(request: Request):
    df = request.app.state.df

Otherwise, if you needed that variable/object to be shared among different clients, as well as among multiple processes/workers, that may also require read/write access to it, you should rather use a database storage, such as PostgreSQL, SQLite, MongoDB, etc., or Key-Value stores (Caches), such as Redis, Memcached, etc. You may want to have a look at this answer as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文