【问题标题】:Python REST-API with Flask-RestX and JavaScript REST-Client served togetherPython REST-API 与 Flask-RestX 和 JavaScript REST-Client 一起提供服务
【发布时间】:2021-01-04 11:36:29
【问题描述】:

我运行这个例子:https://flask-restx.readthedocs.io/en/latest/example.html (带有 Flask-RESTX 的 Python REST-API)

代码 sn-p

app = Flask(__name__)
api = Api(app, ...)
ns = api.namespace('todos', ...)

@ns.route('/')
...
@ns.route('/<int:id>')
...

结果

我得到了 REST-API 的以下 URL:

http://127.0.0.1:5000 -> Swagger 文档

http://127.0.0.1:5000/swagger.json

http://127.0.0.1:5000/todos/

http://127.0.0.1:5000/todos/{id}

问题

我想用 Javascript 实现一个 Webclient,应该通过以下 URL 访问:

http://127.0.0.1:5000 -> index.html

http://127.0.0.1:5000/style.css

http://127.0.0.1:5000/app.js

REST-API 的 URL 应更改为:

http://127.0.0.1:5000/api -> Swagger 文档

http://127.0.0.1:5000/api/swagger.json

http://127.0.0.1:5000/api/todos/

http://127.0.0.1:5000/api/todos/{id}

如何扩展示例以生成所需的 URL?

【问题讨论】:

    标签: python rest flask swagger flask-restx


    【解决方案1】:

    不确定您现在是否已经得到答案。我经常为烧瓶 restx 样板克隆下面的 github 项目。它被设计为一个休息样板,以帮助您启动和运行。

    https://github.com/cosmic-byte/flask-restplus-boilerplate

    模板和静态文件可以添加到应用程序和控制器中以托管页面。为静态页面添加了以下文档。每一个都应该在那里让你运行一个完整的网站

    https://flask.palletsprojects.com/en/1.1.x/tutorial/static/

    【讨论】:

      【解决方案2】:

      您可以使用flask.Blueprint 包装flask-restx 应用程序以将swagger 逻辑移动到特定的url_path 下。

      以下示例显示了如何实现这一点:

      
      import flask
      import flask_restx
      
      
      APP = flask.Flask("my-app")
      api_bp = flask.Blueprint("api", __name__, url_prefix="/api")
      
      API = flask_restx.Api(api_bp)
      APP.register_blueprint(api_bp)
      
      
      NAMESPACE = API.namespace("todos")
      
      
      @NAMESPACE.route("/")
      class TODOSAPI(flask_restx.Resource):
          def get(self):
              return ['todo-1', 'todo-2']
      
      
      

      【讨论】:

        猜你喜欢
        • 2016-12-17
        • 1970-01-01
        • 1970-01-01
        • 2020-11-03
        • 2019-12-07
        • 1970-01-01
        • 1970-01-01
        • 2018-11-24
        • 2016-07-29
        相关资源
        最近更新 更多