相关疑难解决方法(0)

在返回 FastAPI + uvicorn + Docker 应用程序上托管的状态 200 之前,不断收到“307 临时重定向” - 如何返回状态 200?

编辑:

我发现了问题,但不确定为什么会发生这种情况。每当我查询:最后http://localhost:4001/hello/带有“ ”时 - 我都会得到正确的 200 状态响应。/我不懂为什么。

原帖:

每当我向我的应用程序发送查询时,我都会收到 307 重定向。如何让我的应用返回常规状态 200,而不是通过 307 重定向

这是请求输出:

abm                  | INFO:     172.18.0.1:46476 - "POST /hello HTTP/1.1" 307 Temporary Redirect
abm                  | returns the apples data. nothing special here.
abm                  | INFO:     172.18.0.1:46480 - "POST /hello/ HTTP/1.1" 200 OK
Run Code Online (Sandbox Code Playgroud)

pytest 返回:

E       assert 307 == 200
E        +  where 307 = <Response [307]>.status_code

test_main.py:24: AssertionError
Run Code Online (Sandbox Code Playgroud)

在我的根目录:/__init__.py文件:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
# from .configs import …
Run Code Online (Sandbox Code Playgroud)

python redirect http-status-code-307 fastapi

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

使用fastapi下载文件

我正在查看这个,我看到了在 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获取路径的文件和目录的示例代码,您可以将路径作为列表返回,并在循环中添加新条目以深入了解文件树。传递文件名应该会触发下载功能,但我似乎无法启动下载功能。

python python-3.x

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

如何使用 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:如何通过 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返回并下载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万
查看次数

在 FastAPI 中渲染 NumPy 数组

我发现如何使用 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 文件。

如何将数组显示为图像?

python numpy bytesio fastapi

3
推荐指数
1
解决办法
7176
查看次数

如何在 React 上渲染来自 FastAPI 服务器的 Streamable 图像?

我想使用从 FastAPI 后端返回的 React 来渲染图像StreamingResponse。图像是数组的形式numpy,是cv2对象类型。

@app.post("/predict")
async def root(file: UploadFile = File(...)):
    global model
    global store_coordinates
    global store_faces
    global store_mesh

    content = await file.read()
    nparr = np.fromstring(content, np.uint8)
    bg_img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    ......................
    for i in range(len(store_coordinates)):
            x, y, w, h = store_coordinates[i]
            bg_img [b:b + d, a:a + c] = store_mesh[i]
    
    res,im_png = cv2.imencode(".png", bg_img)
    return StreamingResponse(io.BytesIO(im_png.tobytes()), media_type="image/png")
Run Code Online (Sandbox Code Playgroud)

在这里,我创建了一个 API 端点,其中使用POST请求接收上传的图像,并StreamableResponse(Image)返回 a。如何在 React 前端渲染这个返回的响应?

反应代码:

import React, { Component …
Run Code Online (Sandbox Code Playgroud)

javascript python image reactjs fastapi

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