【问题标题】:With Flask-Restplus how to create a POST api without making the URL same with GET使用 Flask-Restplus 如何创建 POST api 而不使 URL 与 GET 相同
【发布时间】:2019-12-18 06:58:34
【问题描述】:

我是 Flask 和 Flask-RestPlus 的新手。我正在创建一个 web api,我希望我的 POST url 与 Swagger 中可见的 GET url 不同。例如在 Flask-Restplus 中

@api.route('/my_api/<int:id>')
class SavingsModeAction(Resource):
    @api.expect(MyApiModel)
    def post(self):
        pass #my code goes here

    def get(self, id):
        pass #my code goes here

因此,两个 api 网址的招摇会看起来像

GET:/my_api/{id}

POST:/my_api/{id}

但到目前为止,我的帖子 api 中绝对没有使用 {id} 部分,它可能会给用户带来一些困惑,无论是更新现有记录还是创建新记录,但是 api 的目的是只是为了创造。

【问题讨论】:

  • 我在同一个 py 文件中创建了两个不同的类,因为我的 get 和 post 规范大不相同,因此将它们放在同一个类中毫无意义。
  • @IshanBhatt 是的,我最终也这样做了。但是,它们属于同一集团业务。

标签: python-3.x swagger flask-restful flask-restplus


【解决方案1】:

而不是 ==> GET:/my_api/{id}

使用查询参数 ==> GET: /my_api?id=

你上面的代码会是这样的

from flask import request

@api.route('/my_api')
class SavingsModeAction(Resource):
    
    @api.expect(MyApiModel)
    def post(self):
        id = request.args.get("id", type=int)
        ...

    def get(self):
        _id = request.args.get("_id", type=str)
        ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 2018-08-07
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    相关资源
    最近更新 更多