使用 sanic-openapi 时找不到 swagger.json

Can't find swagger.json when using sanic-openapi

我正在尝试使用 Sanic-OpenAPI module with sanic 自动记录我自己的 RESTful API。所以,我通过 运行 以下命令安装了它们:

pip install sanic sanic-openapi

# sanic version is 19.12.2
# sanic_openapi version is 0.6.1

我创建了这个简单的项目,顺便说一下,它在他们的官方 GitHub 存储库中提供。它看起来像下面这样:

from sanic import Sanic, response
from sanic_openapi import swagger_blueprint


app = Sanic("app")
app.blueprint(swagger_blueprint)


@app.route("/")
async def test(request):
    return response.json({"hello": "world"})


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000, debug=True)

这运行得很好!但是当我尝试访问 http://localhost:8000/swagger 时,它会抛出以下错误:

Traceback (most recent call last):
  File "/media/anwar/E/Chatbot/NLU_engine/py3.7/lib/python3.7/site-packages/sanic/app.py", line 974, in handle_request
    response = handler(request, *args, **kwargs)
  File "/media/anwar/E/Chatbot/NLU_engine/py3.7/lib/python3.7/site-packages/sanic_openapi/swagger.py", line 263, in spec
    return json(swagger_blueprint._spec)
  File "/media/anwar/E/Chatbot/NLU_engine/py3.7/lib/python3.7/site-packages/sanic/response.py", line 234, in json
    dumps(body, **kwargs),
TypeError: <sanic_openapi.spec.Spec object at 0x7effe3d2f910> is not JSON serializable
[2020-07-12 11:34:09 +0200] - (sanic.access)[INFO][127.0.0.1:37880]: GET http://localhost:8000/swagger/swagger.json  500 2649
[2020-07-12 11:34:09 +0200] [11014] [ERROR] Exception occurred while handling uri: 'http://localhost:8000/swagger/swagger.json'
Traceback (most recent call last):
  File "/media/anwar/E/Chatbot/NLU_engine/py3.7/lib/python3.7/site-packages/sanic/app.py", line 974, in handle_request
    response = handler(request, *args, **kwargs)
  File "/media/anwar/E/Chatbot/NLU_engine/py3.7/lib/python3.7/site-packages/sanic_openapi/swagger.py", line 263, in spec
    return json(swagger_blueprint._spec)
  File "/media/anwar/E/Chatbot/NLU_engine/py3.7/lib/python3.7/site-packages/sanic/response.py", line 234, in json
    dumps(body, **kwargs),
TypeError: <sanic_openapi.spec.Spec object at 0x7effe3d2f910> is not JSON serializable

经过大约两个小时的搜索,我在 this issue 官方 GitHub 存储库中找到了解决方案。根据问题,原因是 sanic-openapiujson.

的最后两个版本(2.x3.x)不兼容

因此,要解决此问题,您需要将 ujson 软件包降级为 1.35,如下所示:

pip install ujson==1.35

它现在完美运行: