快速 API return 图像为 json

fast API return image as json

我有一张 API 的随机茶照片,但想 return JSON 中的照片作为 URL 不和谐机器人和其他东西。这是我目前所拥有的

def getRandomFile(path):
  """
  Returns a random filename, chosen among the files of the given path.
  """
  files = os.listdir(path)
  index = random.randrange(0, len(files))
  return files[index]



@app.get("/")
async def home():
  return RedirectResponse("/docs")

@app.get("/tea")
def tea():
    x = "teacuppics/{}".format(getRandomFile("teacuppics"))
    return FileResponse(x)

如何将图片回复换成JSON回复

你可以使用request.url_for根据主机生成的url。 (在本地主机上它将是 127.0.0.1,在托管上它也将是 www.your-page.com). Argument is name of function. It was solved


from fastapi import FastAPI, Request
from fastapi.responses import FileResponse
from fastapi.responses import JSONResponse


app = FastAPI(title='FASTAPI BLANK', version='1')


@app.get("/tea/{img}")
async def tea(img: str) -> FileResponse:
    return FileResponse(img)


@app.get('/json_tea')
async def tea2(request: Request) -> JSONResponse:
    rnd_pic = '11dfdvf.jpg'
    pic_url = request.url_for('tea', img=rnd_pic)
    return JSONResponse(content={'teacuppics': pic_url})

您可以使用 static files 目录来提供图片等静态文件。将您的 teacuppics 文件夹包含在 static 目录中,并在该目录中安装一个 StaticFiles() 实例。然后,您可以使用 request.url_for() 函数来获取随机选择的图像的 URL。示例如下:

from fastapi.staticfiles import StaticFiles
from fastapi import FastAPI, Request

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")
  
@app.get('/tea')
def tea(request: Request):
    img = "teacuppics/{}".format(getRandomFile("static/teacuppics"))
    img_url = request.url_for('static', path=img)
    return {'img_url': img_url}