我们正在使用 Python FastAPI 编写一个 Web 服务,该服务将托管在 Kubernetes 中。出于审计目的,我们需要保存特定路由的request/的原始 JSON 正文。JSON的主体大小约为1MB,最好这不应该影响响应时间。我们怎样才能做到这一点?responserequestresponse
我有一个.csv文件想要在 FastAPI 应用程序中呈现。我只设法.csv以 JSON 格式呈现文件,如下所示:
def transform_question_format(csv_file_name):
json_file_name = f"{csv_file_name[:-4]}.json"
# transforms the csv file into json file
pd.read_csv(csv_file_name ,sep=",").to_json(json_file_name)
with open(json_file_name, "r") as f:
json_data = json.load(f)
return json_data
@app.get("/questions")
def load_questions():
question_json = transform_question_format(question_csv_filename)
return question_json
Run Code Online (Sandbox Code Playgroud)
当我尝试直接返回时pd.read_csv(csv_file_name ,sep=",").to_json(json_file_name),它起作用了,因为它返回一个字符串。
我应该如何进行?我相信这不是一个好方法。
我在FastAPI和Flask中编写了具有相同功能的相同 API 应用程序。但是,当返回 JSON 时,两个框架之间的数据格式不同。两者都使用相同的json库,甚至相同的代码:
import json
from google.cloud import bigquery
bigquery_client = bigquery.Client()
@router.get('/report')
async def report(request: Request):
response = get_clicks_impression(bigquery_client, source_id)
return response
def get_user(client, source_id):
try:
query = """ SELECT * FROM ....."""
job_config = bigquery.QueryJobConfig(
query_parameters=[
bigquery.ScalarQueryParameter("source_id", "STRING", source_id),
]
)
query_job = client.query(query, job_config=job_config) # Wait for the job to complete.
result = []
for row in query_job:
result.append(dict(row))
json_obj = json.dumps(result, indent=4, sort_keys=True, default=str)
except Exception as e:
return …Run Code Online (Sandbox Code Playgroud) 我正在查看这个,我看到了在 API 中上传的功能?https://fastapi.tiangolo.com/tutorial/request-files/没有选择 dl .. 我错过了什么吗?我希望为文件下载站点创建一个 api。我应该使用不同的api吗?
from typing import List
from fastapi import FastAPI, Query
app = FastAPI()
PATH "some/path"
@app.get("/shows/")
def get_items(q: List[str] = Query(None)):
'''
Pass path to function.
Returns folders and files.
'''
results = {}
query_items = {"q": q}
entry = PATH + "/".join(query_items["q"]) + "/"
dirs = os.listdir(entry)
results["folders"] = [val for val in dirs if os.path.isdir(entry+val)]
results["files"] = [val for val in dirs if os.path.isfile(entry+val)]
results["path_vars"] = query_items["q"]
return results
Run Code Online (Sandbox Code Playgroud)
这是python获取路径的文件和目录的示例代码,您可以将路径作为列表返回,并在循环中添加新条目以深入了解文件树。传递文件名应该会触发下载功能,但我似乎无法启动下载功能。
有没有办法通过FastAPI下载文件?我们想要的文件位于 Azure Datalake 中,从数据湖中检索它们不是问题,当我们尝试将从数据湖获取的字节传输到本地计算机时,就会出现问题。
我们尝试过在 FastAPI 中使用不同的模块,例如starlette.responses.FileResponse和 ,fastapi.Response但没有成功。
在 Flask 中这不是问题,可以通过以下方式完成:
from io import BytesIO
from flask import Flask
from werkzeug import FileWrapper
flask_app = Flask(__name__)
@flask_app.route('/downloadfile/<file_name>', methods=['GET'])
def get_the_file(file_name: str):
the_file = FileWrapper(BytesIO(download_file_from_directory(file_name)))
if the_file:
return Response(the_file, mimetype=file_name, direct_passthrough=True)
Run Code Online (Sandbox Code Playgroud)
当使用有效的文件名运行此文件时,文件会自动下载。FastAPI 中有类似的方法吗?
经过更多的故障排除后,我找到了一种方法来做到这一点。
from fastapi import APIRouter, Response
router = APIRouter()
@router.get('/downloadfile/{file_name}', tags=['getSkynetDL'])
async def get_the_file(file_name: str):
# the_file object is raw bytes
the_file = download_file_from_directory(file_name)
if the_file:
return Response(the_file)
Run Code Online (Sandbox Code Playgroud)
因此,经过大量的故障排除和数小时的文档查看之后,这就是所需要的一切,只需将字节返回为Response(the_file).
我正在尝试将.csv文件上传到 FastAPI 服务器,然后将其转换为 JSON 并将其返回给客户端。但是,当我尝试直接处理它(而不将其存储在某处)时,我收到此错误:
Error : FileNotFoundError: [Error 2] No such file or directory : "testdata.csv"
Run Code Online (Sandbox Code Playgroud)
这是我的 FastAPI 代码:
async def upload(file: UploadFile = File(...)):
data = {}
with open(file.filename,encoding='utf-8') as csvf:
csvReader = csv.DictReader(csvf)
for rows in csvReader:
key = rows['No']
data[key] = rows
return {data}```
Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个docx文件并将其发送到前端客户端应用程序,以便可以将其下载到用户的本地计算机。我使用 FastAPI 作为后端。我还使用python-docx库来创建Document.
下面的代码用于创建一个docx文件并将其保存到服务器。
@app.post("/create_file")
async def create_file(data: Item):
document = Document()
document.add_heading("file generated", level=1)
document.add_paragraph("test")
document.save('generated_file.docx')
return {"status":"Done!"}
Run Code Online (Sandbox Code Playgroud)
然后使用以下代码将创建的docx文件作为 a发送FileResponse到客户端。
@app.get("/generated_file")
async def download_generated_file():
file_path = "generated_file.docx"
return FileResponse(file_path, media_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document', filename=file_path)
Run Code Online (Sandbox Code Playgroud)
在客户端(我正在使用 ReactJS):
@app.post("/create_file")
async def create_file(data: Item):
document = Document()
document.add_heading("file generated", level=1)
document.add_paragraph("test")
document.save('generated_file.docx')
return {"status":"Done!"}
Run Code Online (Sandbox Code Playgroud)
调用函数generated.docx时会下载文件。downloadFile但是,该docx文件始终已损坏并且无法打开。我尝试使用txt文件,效果很好。我需要使用docx文件,我该怎么办?
如何使用FastAPI返回excel文件(版本:Office365)?该文档看起来非常简单。但是,我不知道media_type该用什么。这是我的代码:
import os
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
from typing import Optional
excel_file_path = r"C:\Users\some_path\the_excel_file.xlsx"
app = FastAPI()
class ExcelRequestInfo(BaseModel):
client_id: str
@app.post("/post_for_excel_file/")
async def serve_excel(item: ExcelRequestInfo):
# (Generate excel using item.)
# For now, return a fixed excel.
return FileResponse(
path=excel_file_path,
# Swagger UI says 'cannot render, look at console', but console shows nothing.
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
# Swagger renders funny chars with this argument:
# 'application/vnd.ms-excel'
)
Run Code Online (Sandbox Code Playgroud)
假设我做对了,如何下载该文件?我可以使用FastAPI生成的Swagger UI来查看工作表吗?或者,卷曲?理想情况下,我希望能够下载并在 Excel 中查看该文件。 …
我发现如何使用 FastAPI 将 numpy 数组作为图像返回?然而,我仍然在努力展示图像,它看起来只是一个白色的方块。
io.BytesIO我像这样读入一个数组:
def iterarray(array):
output = io.BytesIO()
np.savez(output, array)
yield output.get_value()
Run Code Online (Sandbox Code Playgroud)
在我的端点中,我的回报是StreamingResponse(iterarray(), media_type='application/octet-stream')
当我留空media_type以推断时,会下载一个 zip 文件。
如何将数组显示为图像?