我有以下代码:
import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/ping")
async def ping(request: Request):
print("Hello")
time.sleep(5)
print("bye")
return {"ping": "pong!"}
Run Code Online (Sandbox Code Playgroud)
如果我在本地主机上运行我的代码 - 例如http://localhost:8501/ping- 在同一浏览器窗口的不同选项卡中,我得到:
Hello
bye
Hello
bye
Run Code Online (Sandbox Code Playgroud)
代替:
Hello
Hello
bye
bye
Run Code Online (Sandbox Code Playgroud)
我已经阅读过有关使用的内容httpx,但仍然无法实现真正的并行化。有什么问题?
python asynchronous concurrent-processing python-asyncio fastapi
我想从 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 创建一个应用程序,该应用程序应该生成上传图像的调整大小版本。上传应该通过 POST/images 完成,在调用路径 /images/800x400 后,它应该显示来自数据库的随机图像,大小为 800x400。我在尝试显示图像时遇到错误。
from fastapi.responses import FileResponse
import uuid
app = FastAPI()
db = []
@app.post("/images/")
async def create_upload_file(file: UploadFile = File(...)):
contents = await file.read()
db.append(file)
with open(file.filename, "wb") as f:
f.write(contents)
return {"filename": file.filename}
@app.get("/images/")
async def show_image():
return db[0]
Run Code Online (Sandbox Code Playgroud)
作为回应我得到:
{
"filename": "70188bdc-923c-4bd3-be15-8e71966cab31.jpg",
"content_type": "image/jpeg",
"file": {}
}
Run Code Online (Sandbox Code Playgroud)
我想使用: return FileResponse(some_file_path) 并在文件路径中输入上面的文件名。这是正确的思维方式吗?
我发现如何使用 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 文件。
如何将数组显示为图像?
我想使用从 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)