如何实现以下目标?
# only if model_type in ['a', 'b', 'c']
api.add_resource(FooAPI, '/<string:model_type'>
# only if model_type in ['x', 'y', 'z']
api.add_resource(BarAPI, '/<string:model_type'>
而不是具有以下代码:
api.add_resource(FooAAPI, '/a'>
api.add_resource(FooBAPI, '/b'>
api.add_resource(FooCAPI, '/c'>
api.add_resource(BarXAPI, '/x'>
api.add_resource(BarYAPI, '/y'>
api.add_resource(BarZAPI, '/z'>
答案 0 :(得分:1)
您可以将any
转换器用于所需的路径,并同时将media_type用作变量:
api.add_resource(FooAPI, '/<any(a, b, c):model_type>')
api.add_resource(BarAPI, '/<any(x, y, z):model_type>')
如果您希望它们具有动态性:
FooAPIOptions = ['a', 'b', 'c']
api.add_resource(
FooAPI, "/<any({}):model_type>".format(str(FooAPIOptions)[1:-1]))
一个简单的应用将是:
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class FooAPI(Resource):
def get(self, model_type=None):
print(model_type) # for example it prints a for "/a" path
return {'hello': 'world'}
FooAPIOptions = ['a', 'b', 'c']
api.add_resource(
FooAPI, "/<any({}):model_type>".format(str(FooAPIOptions)[1:-1]))
if __name__ == '__main__':
app.run(debug=True)