【问题标题】:Flask-RESTful aliasFlask-RESTful 别名
【发布时间】:2016-05-25 11:54:46
【问题描述】:

我想在两个资源之间创建一个别名。

from flask import Flask
from flask_restful import Api, Resource

class api_v1_help(Resource):
    def get(self):
        html_file = "API V1"
        return (html_file, 200, {'Content-Type': 'text/html; charset=utf-8'})

class api_v2_help(Resource):
    def get(self):
        html_file = "API V2"
        return (html_file, 200, {'Content-Type': 'text/html; charset=utf-8'})


app = Flask(__name__)
api = Api(app)

# API (current)
api.add_resource(api_v1_help, '/api/help')

# API v1
api.add_resource(api_v1_help, '/api/v1/help')

# API v2
api.add_resource(api_v2_help, '/api/v2/help')

if __name__ == '__main__':
    # Start app
    app.run(debug=True,port=5000)

这给出了以下错误:AssertionError: View function mapping is overwriting an existing endpoint function: api_v1_help

我可以像这样更改代码:

api.add_resource(api_v1_help, '/api/help', '/api/v1/help') 

但我想知道是否有另一种使用 flask-restful 的解决方案通过将两个 API 端点链接到同一个函数来处理别名?

我搜索以对特定 API 版本的调用进行分组。

【问题讨论】:

标签: python flask flask-restful


【解决方案1】:

改用Flask.add_url_route

# API v1
api.add_resource(api_v1_help, '/api/v1/help')

# API v2
api.add_resource(api_v2_help, '/api/v2/help')

# API (current)
app.add_url_rule('/api/help', endpoint='api_v1_help')

默认情况下,endpoint 设置为the name of the view class,因此您可以在add_resource 调用之后使用'api_v1_help' 作为名称。

【讨论】:

    猜你喜欢
    • 2018-10-23
    • 1970-01-01
    • 2013-10-16
    • 2020-04-27
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多