如何在FastAPI中的HTTP请求之间共享变量?
如何在 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您需要对该变量进行只读访问,并且/或您从不希望在读取它之前它会被其他请求修改(换句话说,您从不希望为多个客户端提供服务) ,以及您的应用不使用多个工作线程 ——自从每个工作线程都有自己的东西、变量和内存) - 你可以(正如 @MatsLindh 在上面的评论中提到的)在端点外部(换句话说,全局)声明一个字典,例如,
foo = {}
,并在端点内部为其分配一个键,例如,foo['pd'] = df
(稍后您可以在另一个请求到达时检索该变量),或者将您的变量声明为global
(如此处),或者最好是将变量存储在应用实例上,这允许您使用通用app.state
属性存储任意额外状态 - 请参阅此答案介绍如何在应用程序启动之前执行此操作。例如:然后,在
get_dataframe
端点内,您可以像这样检索df
:或者,如果
app
实例在您正在工作的文件(假设您在子模块中定义了端点,与主模块分开,如所述此处),您可以从Request
对象获取app
实例:否则,如果您需要该变量/对象为 <在不同客户端以及多个进程/工作进程之间共享,可能还需要对其进行读/写访问,您应该使用数据库存储,例如 PostgreSQL,
SQLite
、MongoDB
、等,或者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 asglobal
(as described here), or, preferably, store the variable on the app instance, which allows you to store arbitrary extra state using the genericapp.state
attribute—see this answer on how to do this before the application starts up. For example:Then, inside the
get_dataframe
endpoint, you can retrieve thedf
like this: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 theapp
instance from theRequest
object: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., orKey-Value
stores (Caches), such asRedis
,Memcached
, etc. You may want to have a look at this answer as well.