【问题标题】:Insert local image in the FastAPI automatic documentation在 FastAPI 自动文档中插入本地图像
【发布时间】:2022-01-17 11:02:51
【问题描述】:

简介

FastAPI 可以在您使用 FastAPI 创建 API 时自动生成您的文档。

我正在尝试在我的一个端点的描述(降价)中插入一张图片,但是当图片位于本地硬盘中时我无法执行此操作。

我尝试过直接插入(查看本文末尾),但不起作用。

我尝试创建一个端点来提供图像,在这种情况下,它仅在地址的 IP 是我的公共 IP 时才有效。如果我输入localhost127.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:

    ![This image works](https://upload.wikimedia.org/wikipedia/commons/0/08/STockholmspanorama_1928b.jpg)
    
    2) This local image doesn't work:
    
    ![This image doesn't work](/home/test01/example-photo.jpg)

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

    ![This image works](http://10.0.0.15:8000/img/example-photo.jpg)

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

    ![This image doesn't work](http://127.0.0.1:8000/img/example-photo.jpg)

    ![This image doesn't work](http://localhost:8000/img/example-photo.jpg)

    """
    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

如果我尝试直接插入图像,它不会显示任何内容。

![This image does not work](../../docs/img/example-photo.jpg)

【问题讨论】:

    标签: python markdown fastapi


    【解决方案1】:

    您可以在文档中使用相对 URL,例如:

    ![This image uses a relative URL](/img/example-photo.jpg)
    

    然后浏览器使用与获取文档页面相同的域来访问图像。

    【讨论】:

    • 谢谢,但它不起作用。如果我尝试以下操作,图像将不起作用。 ![This image uses a relative URL](../../docs/img/example-photo.jpg)
    • 答案中的示例怎么样,以斜杠开头(即,相对于域,而不是文档地址)?这个想法是,然后浏览器将从您在 read_image 函数中公开的 /img/example-photo.jpg 端点获取它
    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多