Passing Function Into A Class And Using It As A Decorator Of Class Methods
Solution 1:
The proper way in CherryPy to handle a situation like this is to have a tool and to enable that tool on the parts of your site that require authentication. Consider first creating this user-auth tool:
@cherrypy.tools.register('before_handler')
def validate_user():
ifUSER== -1:
return
cherrypy.request.uid = user_data['fc_uid']
Note that the 'register' decorator was added in CherryPy 5.5.0.
Then, wherever you wish to validate the user, either decorate the handler with the tool:
classAnalyze:@cherrypy.expose
@cherrypy.tools.validate_user()
defindex(self):
return analysis_panel.pick_data_sets(user_id=cherrypy.request.uid)
Or in your cherrypy config, enable that tool:
config = {
'/analyze': {
'tools.validate_user.on': True,
},
}
Solution 2:
The function/method is defined in the class, it doesn't make sense to decorate it with an instance variable because it won't be the same decorator for each instance.
You may consider using a property
to create the decorated method when it is accessed:
@property
def index(self):
@cherrypy.expose
@self.validuser(['uid'])
def wrapped_index(**kw):
return analysis_panel.pick_data_sets(user_id=kw['uid'])
return wrapped_index
You may also consider trying to apply lru_cache
to save the method for each instance but I'm not sure how to apply that with the property.
Post a Comment for "Passing Function Into A Class And Using It As A Decorator Of Class Methods"