有没有办法在中间件中获取响应内容?以下代码是从此处复制的。
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
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获取路径的文件和目录的示例代码,您可以将路径作为列表返回,并在循环中添加新条目以深入了解文件树。传递文件名应该会触发下载功能,但我似乎无法启动下载功能。
我想从 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 文件作为响应。
有没有办法通过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).
如何使用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 文件。
如何将数组显示为图像?
我正在使用 Python 3.10 和 FastAPI0.92.0编写服务器发送事件 (SSE) 流 api。Python 代码如下所示:
from fastapi import APIRouter, FastAPI, Header
from src.chat.completions import chat_stream
from fastapi.responses import StreamingResponse
router = APIRouter()
@router.get("/v1/completions",response_class=StreamingResponse)
def stream_chat(q: str, authorization: str = Header(None)):
auth_mode, auth_token = authorization.split(' ')
if auth_token is None:
return "Authorization token is missing"
answer = chat_stream(q, auth_token)
return StreamingResponse(answer, media_type="text/event-stream")
Run Code Online (Sandbox Code Playgroud)
这是chat_stream函数:
import openai
def chat_stream(question: str, key: str):
openai.api_key = key
# create a completion
completion = openai.Completion.create(model="text-davinci-003",
prompt=question,
stream=True)
return …Run Code Online (Sandbox Code Playgroud) 我是 webdev 的新手,我有这样的用例:用户向 API 发送一个大文件(例如视频文件),然后该文件需要可供其他 API 访问(可能位于不同的服务器上) )进行进一步处理。
我使用 FastAPI 作为后端,定义一个类型为 的文件参数UploadFile来接收和存储文件。但是,让其他 API 可以访问此文件的最佳方法是什么?有没有办法可以URL从保存的文件中获取公开访问权限,其他 API 可以使用哪些文件来下载该文件?
fastapi ×7
python ×7
python-3.x ×2
amazon-s3 ×1
boto3 ×1
bytesio ×1
excel ×1
media-type ×1
middleware ×1
numpy ×1
openai-api ×1
pdf ×1
response ×1
rest ×1
starlette ×1
streaming ×1