简体   繁体   English

Flask-RESTful别名

[英]Flask-RESTful alias

I would like to create an alias between two resources. 我想在两个资源之间创建一个别名。

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)

This is giving the following error : AssertionError: View function mapping is overwriting an existing endpoint function: api_v1_help 这将产生以下错误:AssertionError:视图函数映射正在覆盖现有的终结点函数:api_v1_help

I can change the code like this : 我可以这样更改代码:

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

but I would like to know if there is another solution with flask-restful to handle an alias by linking two API endpoints to the same function? 但我想知道是否存在通过将两个API端点链接到同一函数来解决烧瓶问题的另一种解决方案?

I search to group the calls for a specific API version. 我搜索将特定API版本的调用分组。

Use Flask.add_url_route instead: 改用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')

By default, endpoint is set as the name of the view class , so you can use 'api_v1_help' as the name after the add_resource call. 默认情况下,将endpoint设置为视图类的名称 ,因此可以在add_resource调用之后使用'api_v1_help'作为名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM