I have got an API for random tea photos but would like it to return the photo in JSON as a URL for discord bots and things. This is what I have so far
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)
How to i swap the reply of images to JSON reply
CodePudding user response:
You could use a static files
direcotry to serve static files such as images. Include your teacuppics
folder inside the static
directory and mount a StaticFiles()
instance in that directory. You can then use request.url_for()
function to get the URL of a randomly selected image. Example below:
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}
CodePudding user response:
You can use request.url_for
what generate url according to host. (on localhost it will be 127.0.0.1, on hosting it will be www.your-page.com). Argument is name of function. It was solved here as well.
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})