I have a question about splitting up a main.py file.
right now, I have everything in my main.py. I have no other .py files. And I always have to scroll long lines of code before reaching the section I wish to edit.
How do I split it up?
(i’m going to have more than 20 pages, so that means the main.py will be HUGE if I don’t split it up.
PS: also, I noticed that I had to setup the template values, template path, and call template.render each time. Any way of shortening them all?
Code:
# everything here in main.py
class MainPage(webapp.RequestHandler):
def get(self):
# Models are queried here, results transferred to template_values
template_values = {
'value1': value1,
'value2': value2,
'value3': value3,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
class Page2(webapp.RequestHandler):
def get(self):
# Models are queried here, results transferred to template_values
template_values = {
'value1': value1,
'value2': value2,
'value3': value3,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
class Page3(webapp.RequestHandler):
def get(self):
# Models are queried here, results transferred to template_values
template_values = {
'value1': value1,
'value2': value2,
'value3': value3,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
application = webapp.WSGIApplication(
[('/', MainPage),
('/page2', Page2)
('/page3', Page3)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
Splitting the code is no different than splitting code for any Python app – find a bunch of related code that you want to move to another file, move it to that file, and import it into the main handler file.
For example, you could move the Page2 code to page2.py, put
at the top of your file, and change your mapping to load
/page2frompage2.Page2(you might want to rename these classes in this case…Alternatively, you could have separate .py files handle different (groups of) pages by editing the
app.yamlfile as described in Script Handlers.You can wrap your template-handling code in a convenience function and call it, to reduce repeated code a little bit. You may be able to streamline the loading of the template values, but once you want to render, you could call a method something like
It’s not much of a savings, but it’s a little more readable. Probably you’d want to move
renderto a different file andimportit where you want it.