Flask-RESTful 别名
Flask-RESTful alias
我想在两个资源之间创建一个别名。
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:视图函数映射正在覆盖现有端点函数:api_v1_help
我可以这样更改代码:
api.add_resource(api_v1_help, '/api/help', '/api/v1/help')
但我想知道是否有另一种使用 flask-restful 的解决方案,通过将两个 API 端点链接到同一函数来处理别名?
我搜索以对特定 API 版本的调用进行分组。
# 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'
作为名称。
我想在两个资源之间创建一个别名。
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:视图函数映射正在覆盖现有端点函数:api_v1_help
我可以这样更改代码:
api.add_resource(api_v1_help, '/api/help', '/api/v1/help')
但我想知道是否有另一种使用 flask-restful 的解决方案,通过将两个 API 端点链接到同一函数来处理别名?
我搜索以对特定 API 版本的调用进行分组。
# 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'
作为名称。