【发布时间】:2019-01-11 12:24:23
【问题描述】:
我正在构建一个 web 应用程序,其中不同的视图将具有不同数量的“包装功能”(例如身份验证、日志记录/错误处理、数据库访问等),并且能够轻松地在视图之间共享此功能。
我认为 Pluggable Views 是处理这个问题的好方法,它通过重复子类化视图来构建包装视图主要操作的功能层。
但是,我正在努力找出实现这一点的最佳方法。我正在考虑链接装饰器,但继承似乎效果不佳。
例如,带有一些自定义日志记录和错误处理的简化视图:
from flask.views import View
class LoggedView(View):
def __init__(self,template):
self.template=template
#Decorator method for error handling and logging
def log_view(self,view):
def decorator(**kwargs):
try:
#Set up custom logging
self.log = .....
#Execute view
return view(**kwargs)
except CustomApplicationError as e:
#Log and display error
self.log.error(e)
return render_template('error.html',error=str(e))
return decorator
decorators=[log_view]
#This can be overridden for more complex views
def dispatch_request(self):
return render_template(self.template)
视图可以像这样使用:
app.add_url_rule('/index', view_func=LoggedView.as_view('index',template='index.html'))
那么,如果我想在此视图的基础上添加用户身份验证:
class RestrictedView(LoggedView):
#Decorator method for user access validation
def validate_access(self,view):
def decorator(**kwargs):
g.user=session.get('user')
if g.user is None:
return redirect(url_for('login'))
#Execute view
return view(**kwargs)
return decorator
#How to add this functionality to the decorator chain? e.g. I dont think this works:
decorators.append(validate_access)
然后我想重复这个子类化来添加更多的功能,比如数据库访问
- 有没有更好的方法来实现我想要做的事情?
- 将装饰器作为视图方法有意义吗?在装饰器中使用“自我”有效吗?
任何建议将不胜感激!
【问题讨论】:
标签: python inheritance flask views decorator