Flask + Flask-RESTful: 将特定变量匹配到路由

Flask + Flask-RESTful: Match specific variables to routes

如何实现以下目标?

# 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'>

您可以将 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)