相关疑难解决方法(0)

如何使用 FastAPI 从内存缓冲区返回 PDF 文件?

我想从 s3 获取一个 PDF 文件,然后从 FastAPI 后端返回到前端。

这是我的代码:

@router.post("/pdf_document")
def get_pdf(document : PDFRequest) :
    s3 = boto3.client('s3')
    file=document.name
    f=io.BytesIO()
    s3.download_fileobj('adm2yearsdatapdf', file,f)
    return StreamingResponse(f, media_type="application/pdf")
Run Code Online (Sandbox Code Playgroud)

此 API 返回200状态代码,但不返回 PDF 文件作为响应。

python pdf amazon-s3 boto3 fastapi

7
推荐指数
1
解决办法
9164
查看次数

如何在fastapi StreamingResponse中从内存返回文件?

我想根据要求提供 xlsx。通过使用BytesIOxlsxwriter我创建了一个文件。

使用下面的代码,我可以下载一个空(!).txt文件:

@router.get("/payments/xlsx", response_description='xlsx')
async def payments():
    """sss"""
    output = BytesIO()
    workbook = xlsxwriter.Workbook(output)
    worksheet = workbook.add_worksheet()
    worksheet.write(0, 0, 'ISBN')
    worksheet.write(0, 1, 'Name')
    worksheet.write(0, 2, 'Takedown date')
    worksheet.write(0, 3, 'Last updated')
    workbook.close()
    output.seek(0)
    return StreamingResponse(output)
Run Code Online (Sandbox Code Playgroud)

如果我添加,headers={'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}我会在浏览器中收到此错误:

Unable to open file
You may be having a problem connecting with the server, or the file that you wanted to open was corrupted.
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

bytesio python-3.x xlsxwriter fastapi

6
推荐指数
1
解决办法
1万
查看次数

来自 S3 FastAPI 的响应文件流

我正在尝试从 S3 返回图片的响应。在StreamingResponse.stream_response我看来,块是从流中读取并发送到套接字的。但另一边却什么也没有发生。

这就是我在浏览器中看到的

import uvicorn

from fastapi import FastAPI
from fastapi.responses import StreamingResponse

from aiobotocore.session import get_session
from aioboto3 import session

app = FastAPI()


@app.get("/")
async def main():

    sess = get_session()
    async with sess.create_client(
            's3',
            endpoint_url="",
            aws_secret_access_key="",
            aws_access_key_id=""
    ) as client:
        result = await client.get_object(Bucket="", Key="")

        return StreamingResponse(result["Body"], media_type="image/jpeg")


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8080)```
Run Code Online (Sandbox Code Playgroud)

async-await starlette fastapi

6
推荐指数
2
解决办法
8720
查看次数

如何显示 API 的“内容类型:image/jpg”响应?(反应本机)

我正在发布图像,并从后端获取处理后的图像作为响应。问题出在响应部分。无论我做什么都无法显示图像。

\n

首先,邮递员工作。所以后端很好,我在邮递员中看到图像响应。无论如何,这是 FastAPI 后端的相关部分:

\n
for img in results.imgs:\n        bytes_io = io.BytesIO()\n        img_base64 = Image.fromarray(img)\n        img_base64.save(bytes_io, format="jpeg")\n    return Response(content=bytes_io.getvalue(), media_type="image/jpeg")\n
Run Code Online (Sandbox Code Playgroud)\n

我尝试过 axios 并获取两者。

\n

Axios 的响应看起来像这样,带有标题:(我得到 200)

\n
"data": "\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd",\n  "headers": Object {\n    "content-length": "86387",\n    "content-type": "image/jpeg",\n    "date": "Thu, 05 May 2022 17:45:03 GMT",\n    "server": "uvicorn",\n  },\n
Run Code Online (Sandbox Code Playgroud)\n

如您所见,数据看起来很奇怪。

\n

这是代码:

\n
axios.post("http://10.0.0.3:8000/object-to-img", body, {\n          headers: {\n            "Content-Type": "multipart/form-data",\n          },\n        })\n        .then(function (response) {\n          setImage("data:image/jpeg;base64," + response.data);\n        })\n        .catch(function (error) {\n          console.log(error);\n        });\n
Run Code Online (Sandbox Code Playgroud)\n

这就是我尝试将其形象化的方式:

\n
<Image\n        style={{\n …
Run Code Online (Sandbox Code Playgroud)

javascript react-native axios expo fastapi

6
推荐指数
1
解决办法
3764
查看次数

How do I convert a torch tensor to an image to be returned by FastAPI?

I have a torch tensor which I need to convert to a byte object so that I can pass it to starlette's StreamingResponse which will return a reconstructed image from the byte object. I am trying to convert the tensor and return it like so:

def some_unimportant_function(params):
    return_image = io.BytesIO()
    torch.save(some_img, return_image)
    return_image.seek(0)
    return_img = return_image.read()
    
    return StreamingResponse(content=return_img, media_type="image/jpeg")

Run Code Online (Sandbox Code Playgroud)

The below works fine on regular byte objects and my API returns the reconstructed image:

def some_unimportant_function(params):
    image = Image.open(io.BytesIO(some_image))

    return_image …
Run Code Online (Sandbox Code Playgroud)

python pytorch starlette fastapi

6
推荐指数
1
解决办法
3544
查看次数

FastAPI:如何通过 API 下载字节

有没有办法通过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).

python starlette fastapi

5
推荐指数
1
解决办法
9124
查看次数

如何使用 ReactJS 在前端使用 Axios,在后端使用 FastAPI 下载文件?

我正在尝试创建一个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文件,我该怎么办?

javascript web reactjs axios fastapi

5
推荐指数
1
解决办法
8170
查看次数

如何使用FastAPI下载大文件?

我正在尝试从 FastAPI 后端下载一个大文件 ( .tar.gz)。在服务器端,我只是验证文件路径,然后Starlette.FileResponse返回整个文件\xe2\x80\x94,就像我在 StackOverflow 上的许多相关问题中看到的那样。

\n

服务器端:

\n
return FileResponse(path=file_name, media_type=\'application/octet-stream\', filename=file_name)\n
Run Code Online (Sandbox Code Playgroud)\n

之后,我收到以下错误:

\n
  File "/usr/local/lib/python3.10/dist-packages/fastapi/routing.py", line 149, in serialize_response\n    return jsonable_encoder(response_content)\n  File "/usr/local/lib/python3.10/dist-packages/fastapi/encoders.py", line 130, in jsonable_encoder\n    return ENCODERS_BY_TYPE[type(obj)](obj)\n  File "pydantic/json.py", line 52, in pydantic.json.lambda\nUnicodeDecodeError: \'utf-8\' codec can\'t decode byte 0x8b in position 1: invalid start byte\n
Run Code Online (Sandbox Code Playgroud)\n

我也尝试使用StreamingResponse,但得到了同样的错误。还有其他方法可以做到吗?

\n

我的代码中的StreamingResponse

\n
  File "/usr/local/lib/python3.10/dist-packages/fastapi/routing.py", line 149, in serialize_response\n    return jsonable_encoder(response_content)\n  File "/usr/local/lib/python3.10/dist-packages/fastapi/encoders.py", line 130, in jsonable_encoder\n    return ENCODERS_BY_TYPE[type(obj)](obj)\n  File …
Run Code Online (Sandbox Code Playgroud)

python download starlette pydantic fastapi

5
推荐指数
1
解决办法
7604
查看次数

FastAPI返回大量JSON数据非常慢

我有一个 FastAPIGET端点,它返回大量 JSON 数据(约 160,000 行和 45 列)。毫不奇怪,使用返回数据非常json.dumps()慢。我首先使用文件中的数据读取数据json.loads(),并根据输入的参数对其进行过滤。有没有比使用更快的方法将数据返回给用户return data?以目前的状态,需要将近一分钟的时间。

我的代码目前如下所示:

# helper function to parse parquet file (where data is stored)
def parse_parquet(file_path):
    df = pd.read_parquet(file_path)
    result = df.to_json(orient = 'records')
    parsed = json.loads(result)
    return parsed
    

@app.get('/endpoint')
# has several more parameters
async def some_function(year = int | None = None, id = str | None = None):
    if year is None:
        data = parse_parquet(f'path/{year}_data.parquet')
    # no year
    if year is …
Run Code Online (Sandbox Code Playgroud)

python json dataframe pandas fastapi

5
推荐指数
1
解决办法
1万
查看次数

如何使用FastAPI返回并下载Excel文件?

如何使用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 中查看该文件。 …

python excel media-type fastapi

4
推荐指数
1
解决办法
1万
查看次数