问题
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)
]
回答1:
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.
回答2:
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()
来源:https://stackoverflow.com/questions/838078/working-with-subdomain-in-google-app-engine