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)
]
Custom subdomains To create unique pages within your website, you can use resource records to customize your domain with subdomains, such as “blog.example.com” and “shop.example.com”. Learn more about resource records.
In the Google Cloud console, go to the Custom Domains tab of the App Engine Settings page. Click Add a custom domain. If your domain is already verified, the domain appears in the Select the domain you want to use section. Select the domain from the drop-down menu and click Continue.
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.
I liked the idea from Nick but I had a slightly different issue. I wanted to match one specific subdomain to handle it a bit different, but all other sub domains should be handled the same. So here is my example.
import os
def main():
if (os.environ['HTTP_HOST'] == "sub.example.com"):
application = webapp.WSGIApplication([('/(.*)', OtherMainHandler)], debug=True)
else:
application = webapp.WSGIApplication([('/', MainHandler),], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With