其實(shí)Tornado對(duì)子域名和泛域名(除了特別說(shuō)明外,以下子域名和泛域名均簡(jiǎn)稱為泛域名)的支持并不是什么新鮮事,兩年多前我用Tornado寫的開源網(wǎng)站 http://poweredsites.org 就有了對(duì)泛域名的支持,但是Tornado的官方文檔里并沒有明確對(duì)此功能進(jìn)行說(shuō)明,雖然源代碼里是有注釋的,終是有點(diǎn)隱晦,這不,近日mywaiting同學(xué)就遇到了這個(gè)問題,我應(yīng)邀特撰此博文,分享下我對(duì)此的一點(diǎn)點(diǎn)經(jīng)驗(yàn)。
通常,用Tornado添加url映射路由表是直接傳handlers給Application這種方式的,比如官方的chatdemo:
class Application(tornado.web.Application): def __init__(self): handlers = [ (r"/", MainHandler), (r"/auth/login", AuthLoginHandler), (r"/auth/logout", AuthLogoutHandler), (r"/a/message/new", MessageNewHandler), (r"/a/message/updates", MessageUpdatesHandler), ] settings = dict( cookie_secret="43oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=", login_url="/auth/login", template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), xsrf_cookies=True, autoescape="xhtml_escape", ) tornado.web.Application.__init__(self, handlers, **settings)
這種方式其實(shí)添加的是一個(gè)域名通配的url映射表,即域名&子域名不限,只要訪問能夠解析到這個(gè)chatdemo上,“/auth/login” “/auth/login”這些url就都能夠正常運(yùn)行。假設(shè)www.feilong.me、abc.feilong.me、feilong2.me這個(gè)三個(gè)(子)域名均配置為可由這個(gè)chatdemo程序來(lái)host,那么訪問這三個(gè)(子)域名均可以正常使用這個(gè)chatdemo,總之域名是無(wú)關(guān)的。
實(shí)際上,這種方式它的內(nèi)部是通過(guò)Application里的這個(gè)add_handlers來(lái)實(shí)現(xiàn)的(原碼注釋如下):
def add_handlers(self, host_pattern, host_handlers): """Appends the given handlers to our handler list. Note that host patterns are processed sequentially in the order they were added, and only the first matching pattern is used. This means that all handlers for a given host must be added in a single add_handlers call. """
只不過(guò)它是隱式的調(diào)用這個(gè)add_handlers而已,其關(guān)鍵點(diǎn)就在于第一個(gè)參數(shù)host_pattern(匹配域名的)上,上面那種方式,默認(rèn)添加的host_pattern是”.*$”,即域名通配,若要支持泛域名,只需要顯式的調(diào)用add_handlers來(lái)添加相應(yīng)的host_pattern和handlers即可。
接下來(lái)就以poweredsites的源碼來(lái)介紹Tornado對(duì)泛域名的支持,app.py里的Application里面有這么幾句:
super(Application, self).__init__(handlers, **settings) # add handlers for sub domains for sub_handler in sub_handlers: # host pattern and handlers self.add_handlers(sub_handler[0], sub_handler[1])
常見的方式super(Application, self).__init__(handlers, **settings)添加的是根域名poweredsites的handlers,接著用for循環(huán)顯式添加的是子域名和泛域名的handlers。這里的sub_handlers依次放有各子域名的handlers,其最后一個(gè)是泛域名的handlers:
新聞熱點(diǎn)
疑難解答
圖片精選