在Google App Engine中使用子域名
我该如何在Google App Engine(使用Python)中处理子域名呢?
我想获取主域名的第一部分,然后执行一些操作(处理程序)。
举个例子:
product.example.com -> 发送到产品处理程序
user.example.com -> 发送到用户处理程序
实际上,使用虚拟路径我有以下代码:
application = webapp.WSGIApplication(
[('/', IndexHandler),
('/product/(.*)', ProductHandler),
('/user/(.*)', UserHandler)
]
2 个回答
2
我喜欢Nick的想法,但我遇到了一个稍微不同的问题。我想要针对一个特定的子域名进行不同的处理,而其他所有的子域名都应该用相同的方式处理。所以这是我的例子。
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()
26
WSGIApplication 这个东西不能根据域名来进行路由。也就是说,如果你想根据不同的子域名来处理请求,你需要为每个子域名创建一个单独的应用程序,像这样:
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()
另外,你也可以自己写一个 WSGIApplication 的子类,让它能够处理多个主机。