Search code examples
pythongoogle-app-enginesubdomain

Working with subdomain in google app engine


How can I work with sub domain in google app engine (python).

I wanna get first domain part and take some action (handler).

Example:
     product.example.com -> send it to products handler
     user.example.com -> send it to users handler

Actually, using virtual path I have this code:

  application = webapp.WSGIApplication(
    [('/', IndexHandler),
     ('/product/(.*)', ProductHandler),
     ('/user/(.*)', UserHandler)
  ]

Solution

  • WSGIApplication isn't capable of routing based on domain. Instead, you need to create a separate application for each subdomain, like this:

    applications = {
      'product.example.com': webapp.WSGIApplication([
        ('/', IndexHandler),
        ('/(.*)', ProductHandler)]),
      'user.example.com': webapp.WSGIApplication([
        ('/', IndexHandler),
        ('/(.*)', UserHandler)]),
    }
    
    def main():
      run_wsgi_app(applications[os.environ['HTTP_HOST']])
    
    if __name__ == '__main__':
      main()
    

    Alternately, you could write your own WSGIApplication subclass that knows how to handle multiple hosts.