Search code examples
pythongoogle-app-engineurl-rewritingurl-routingfriendly-url

Basic html-mapping or url-rewriting for google appengine (python)


I'm trying to rewrite urls for a static site on Google Appengine. I only want http://www.abc.com/about for http://www.abc.com/about.html I don't need rewriting for stuff like abc.com/page?=1 or anything. I just wanna figure out how to explicity rewrite urls for html pages.

The code I'm currently using (which isn't working) -

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
import os

class MainHandler(webapp.RequestHandler):
    def get(self):
        template_values = {}

        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))


class PostHandler(webapp.RequestHandler):
    def get(self, slug):
        template_values = {}
        post_list =  { 
            'home' : 'index.html',
            'portfolio' : 'portfolio.html',            
            'contact' : 'contact.html',
            'about' : 'about.html'
        }

        if slug in post_list:
            self.response.out.write('Slugs not handled by C-Dan yet')
        else:
            self.response.out.write('no post with this slug')

def main():
    application = webapp.WSGIApplication([('/', MainHandler),('/(.*)', PostHandler)], debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()

Solution

  • For your constructor, you want:

    def main():
      application = webapp.WSGIApplication([
        ('/', MainHandler),
        ('/portfolio/', Portfolio),
        ('/contact/', Contant),
        ('/about/', About)
        ])
      util.run_wsgi_app(application)
    

    This mean anytime someone goes to http://www.abc.com/about/, they will be 'routed' to your About handler.

    Then you have to make an About handler.

    class About(webapp.RequestHandler):
      def get(self):
        self.response.out.write(template.render('about.html', None))
    

    I'm not familiar with your coding style, but what I've shown you has worked for me in all my projects.