我目前正在编写Flask应用程序,该应用程序将端点路由到各种“操作”。这些操作都实现了一个名为“run()”的父函数
在代码中:
import abc
class Action(object):
__metaclass__ = abc.ABCMeta
@classmethod
def authenticated(self):
print("bypassing action authentication")
return True
@classmethod
def authorized(self):
print("bypassing action authorization")
return True
@classmethod
@abc.abstractmethod
def execute(self):
raise NotImplementedError("must override execute!")
@classmethod
def response(self, executeResult):
return executeResult
@classmethod
def run(self):
result = ""
if self.authenticated() & self.authorized():
result = self.execute()
return self.response(result)
意图是所有实际使用的动作都是此Action类的派生成员,它们至少实现了区分它们的execute()函数。不幸的是,当我尝试为这些
添加路线时app.add_url_rule('/endone/', methods=['GET'], view_func=CoreActions.ActionOne.run)
app.add_url_rule('/endtwo/', methods=['GET'], view_func=CoreActions.ActionTwo.run)
我收到以下错误:
AssertionError: View function mapping is overwriting an existing endpoint function: run
有谁知道这个问题的可能解决方案?谢谢!
答案 0 :(得分:0)
生成视图函数的常用方法是使用Flask views。从[{1}} Action
类中对flask.views.View
类进行子类化,使用dispatch_request
方法代替run
:
import abc
from flask.views import View
class Action(View):
__metaclass__ = abc.ABCMeta
def authenticated(self):
print("bypassing action authentication")
return True
def authorized(self):
print("bypassing action authorization")
return True
@abc.abstractmethod
def execute(self):
raise NotImplementedError("must override execute!")
def response(self, executeResult):
return executeResult
def dispatch_request(self):
result = ""
if self.authenticated() & self.authorized():
result = self.execute()
return self.response(result)
您可以使用View.as_view()方法添加路线,将您的班级转换为查看功能:
app.add_url_rule(
'/endone/',
methods=['GET'],
view_func=CoreActions.ActionOne.as_view('endone')
)