I’m still quite new to python with less than a year of experience, and I’ve been learning it through building a rather large project on google app engine. It’s grown to be a behemoth of 10k+ lines of code and html templates, so I’m in the process of refactoring a rather large portion of the code to follow a much more rigorous MVC architecture.
My question is one concerning python directly. I don’t know the words to say exactly what I want to build, so I would just like to use an example.
This is my current “basic” code for displaying a view:
class MainHandler(webapp.RequestHandler):
def get(self):
tUser = users.get_current_user()
tContext = {
'user': tUser,
'login': users.create_login_url(self.request.uri),
'logout': users.create_logout_url(self.request.uri),
}
#User is logged in
if (tUser):
#code for loading view information and adding to the context dict
#CUSTOMIZATION GOES HERE
else:
self.redirect("/")
tmpl = os.path.join(os.path.dirname(__file__), 'logged-in.html')
self.response.out.write(render(tmpl, tContext))
I would like to take this boilerplate code and abstract it somehow, maybe with a way of prepending/appending the “customizable” code for each class method?
I think I might be able to use a decorator to do this somehow, but I have no python mentors outside of stackoverflow to point me in the right direction. I would prefer the most pythonic method possible, or at least what’s generally considered “best practices” in this situation.
The python version is 2.7.2.
edit
Note, if I can do this with decorators, then what is necessary for me to be able to call the decorator from an entirely different class and python file? I would like to be able put my decorators in one file and reference it from elsewhere so my code is as normalized as is reasonable. =)
edit 2
This is the testing code that I worked out in the console, and I have to leave for the evening or I would refine it more. However, it appears that this successfully accesses and modifies the class’s properties, which is pretty much what I think you need to pull this off in GAE.
class Decorators():
@staticmethod
def BeginInit(pInFunction):
def OutFunction1(self):
print str(self.innerv)
pInFunction(self)
return OutFunction1
@staticmethod
def EndInit(pInFunction):
def OutFunction2(self):
self.innerv = 5
pInFunction(self)
print "this is test 3"
return OutFunction2
class Test2Handler():
innerv = 10
@Decorators.BeginInit
@Decorators.EndInit
def TestPrint(self):
print self.innerv
print "this is test 2"
Prints
10
5
this is test 2
this is test 3
Instead of using decorators, you could use a base class for your request handlers, like so