【发布时间】:2022-01-17 11:02:51
【问题描述】:
简介
FastAPI 可以在您使用 FastAPI 创建 API 时自动生成您的文档。
我正在尝试在我的一个端点的描述(降价)中插入一张图片,但是当图片位于本地硬盘中时我无法执行此操作。
我尝试过直接插入(查看本文末尾),但不起作用。
我尝试创建一个端点来提供图像,在这种情况下,它仅在地址的 IP 是我的公共 IP 时才有效。如果我输入localhost 或127.0.0.1,它不起作用。我想我在这里遗漏了一些东西。
小例子
安装:
$ pip install fastapi
$ pip install "uvicorn[standard]"
文件:main.py
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/my-endpoint")
def example_function():
"""
Documentation for my enpoint. Insert some images
1) This online image works:

2) This local image doesn't work:

3) This local image served by the api works if the link is to the public IP:

4) This local image served by the api doesn't work because when specified as localhost:


"""
return {"This is my endpoint"}
# An endpoint to serve images for documentation
@app.get("/img/example-photo.jpg")
async def read_image():
return FileResponse("example-photo.jpg")
使用以下命令执行 API:
$ uvicorn main:app --reload --host 0.0.0.0 --port 8000
您可以在以下位置访问自动文档:
http://<you-ip>:8000/docs
示例结果
额外
在我的实际情况下,文件夹结构如下:
/myProject/
|
|---/docs/
| |---/img/
| |---example-photo.jpg
|
|---/src/
|---/myApp/
|----main.py
如果我尝试直接插入图像,它不会显示任何内容。

【问题讨论】: