gpt4 book ai didi

python - Flask-RESTful 别名

转载 作者:行者123 更新时间:2023-12-02 23:12:09 25 4
gpt4 key购买 nike

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

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 函数映射正在覆盖现有端点函数:api_v1_help

我可以像这样更改代码:

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

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

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

最佳答案

使用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')

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

关于python - Flask-RESTful 别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37436362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com