为了避免为我的模型编写api方法视图。我希望创建一种更优雅的继承方式。
class ModelCrudAPI(MethodView):
def __init__(self, model):
self.model = model
def get(self):
store_id = request.args.get("store_id", None, int)
waiters = self.model.query.filter_by(store_id=store_id).all()
if waiters is None or store_id is None:
return jsonify({'items': [], 'store_id': store_id}), 204
# TODO: change personnel_data to list
else:
items = []
for waiter in waiters:
items.append(row2dict(waiter))
return jsonify({"items": items, 'store_id': store_id})
我之前在这个问题中设置过类似的继承。 previous question about inheritance and decorators in methodviews
注意我想将sqlalcdhemy模型传递给我的班级。
第一个场景
class Test(ModelCrudAPI):
def __init__(self, model):
super(Test, self).__init__(model)
api.add_url_rule("/test", view_func=Test(MYMODEL).as_view("test"), methods=['GET','POST','PUT','DELETE'])
ERROR:
flask debuger :TypeError: __init__() takes exactly 2 arguments (1 given)
第二种情景)
class Test(ModelCrudAPI):
def __init__(self, MYMODEL):
super(Test, self).__init__(MYMODEL)
api.add_url_rule("/test", view_func=Test.as_view("test"), methods=['GET','POST','PUT','DELETE'])
ERROR:
flask debuger :TypeError: __init__() takes exactly 2 arguments (1 given)
我真的会帮助你。这将清理我的代码。
编辑此作品
class Test(ModelCrudAPI):
def __init__(self):
ModelCrudAPI.__init__(self, Personnel)
api.add_url_rule("/test", view_func=Test.as_view("test"), methods=['GET','POST','PUT','DELETE'])
答案 0 :(得分:2)
as_view
is a classmethod
, and it forwards arguments provided to it to the class' constructor. So all you have to do is pass your model as the second argument to as_view
:
class Test(ModelCrudAPI):
def __init__(self, model):
super(Test, self).__init__(model)
api.add_url_rule("/test", view_func=Test.as_view("test", MYMODEL), methods=['GET','POST','PUT','DELETE'])