探究Python的Tornado框架对子域名和泛域名的支持


Posted in Python onMay 02, 2015

其实Tornado对子域名和泛域名(除了特别说明外,以下子域名和泛域名均简称为泛域名)的支持并不是什么新鲜事,两年多前我用Tornado写的开源网站 http://poweredsites.org 就有了对泛域名的支持,但是Tornado的官方文档里并没有明确对此功能进行说明,虽然源代码里是有注释的,终是有点隐晦,这不,近日mywaiting同学就遇到了这个问题,我应邀特撰此博文,分享下我对此的一点点经验。

通常,用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)

这种方式其实添加的是一个域名通配的url映射表,即域名&子域名不限,只要访问能够解析到这个chatdemo上,“/auth/login” “/auth/login”这些url就都能够正常运行。假设www.feilong.me、abc.feilong.me、feilong2.me这个三个(子)域名均配置为可由这个chatdemo程序来host,那么访问这三个(子)域名均可以正常使用这个chatdemo,总之域名是无关的。

实际上,这种方式它的内部是通过Application里的这个add_handlers来实现的(原码注释如下):

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.
    """

只不过它是隐式的调用这个add_handlers而已,其关键点就在于第一个参数host_pattern(匹配域名的)上,上面那种方式,默认添加的host_pattern是”.*$”,即域名通配,若要支持泛域名,只需要显式的调用add_handlers来添加相应的host_pattern和handlers即可。

接下来就以poweredsites的源码来介绍Tornado对泛域名的支持,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循环显式添加的是子域名和泛域名的handlers。这里的sub_handlers依次放有各子域名的handlers,其最后一个是泛域名的handlers:

sub_handlers.append(site.sub_handlers)
sub_handlers.append(blog.sub_handlers)
sub_handlers.append(admin.sub_handlers)
# wildcard subdomain handler for project should be the last one.
sub_handlers.append(project.sub_handlers)

指定的子域名的sub_handlers(site.sub_handlers)是这个样子的,这里的第一个元素就是host_pattern:

sub_handlers = ["^sites.poweredsites.org$",
        [
         (r"/", _WebsiteIndexHandler),
         (r"/feeds", _WebsitesFeedsHandler),
         (r"/([a-z0-9]{32})", _WebsiteHandler),
         (r"/([^/]+)", WebsiteHandler),
         ]
        ]

泛域名(project.sub_handlers)的区别也就在于这第一个元素,即用来做host_pattern的是通配一些子域名的:

sub_handlers = ["^[a-zA-Z_\-0-9]*\.poweredsites.org$",
        [(r"/", ProjectIndexHandler),
         (r"/top", ProjectTopHandler),
         (r"/opensource", ProjectOpensourceHandler),
         ]
        ]

在用到了泛域名的ProjectIndexHandler里,运行时具体的子域名就可以通过下面这样的方式获得:

class ProjectIndexHandler(ProjectBaseHandler):
  def get(self):
    subdomain = self.request.host.split(".")[0]

需要说明的是,Tornado里面的url映射表和Django一样是有顺序的,即url依次序由上到下匹配,只要匹配到就立即结束,不再往下匹配,而带子域名和泛域名的url路由其匹配优先级是要高于通配域名”.*$”的(这个不用你操心,add_handlers会自动为你做到这一点)。同样的,对于泛域名,因为其子域名是通配的,因此指定子域名的handlers需要放到泛域名前添加,如admin、blog这类子域名的handlers要放在泛域名之前,这就是poweredsites里sub_handlers.append(project.sub_handlers)放到最后一条的原因,project这条是对应泛域名的,http://tornado.poweredsites.org 就是靠这一条来实现的。

备注:需要支持泛域名,首先要你的域名解析支持泛域名。

转载请注明出处:http://feilong.me/2012/08/wildcard-subdomain-support-in-tornado

Python 相关文章推荐
Python tempfile模块学习笔记(临时文件)
May 25 Python
Python创建文件和追加文件内容实例
Oct 21 Python
python时间序列按频率生成日期的方法
May 14 Python
django框架模板语言使用方法详解
Jul 18 Python
PyCharm更改字体和界面样式的方法步骤
Sep 27 Python
Python如何计算语句执行时间
Nov 22 Python
python的faker库用法
Nov 28 Python
TFRecord文件查看包含的所有Features代码
Feb 17 Python
使用python3 实现插入数据到mysql
Mar 02 Python
python 已知平行四边形三个点,求第四个点的案例
Apr 12 Python
pytorch加载语音类自定义数据集的方法教程
Nov 10 Python
深度学习详解之初试机器学习
Apr 14 Python
Python编程中运用闭包时所需要注意的一些地方
May 02 #Python
按日期打印Python的Tornado框架中的日志的方法
May 02 #Python
详细解读Python的web.py框架下的application.py模块
May 02 #Python
使用Python的web.py框架实现类似Django的ORM查询的教程
May 02 #Python
在ironpython中利用装饰器执行SQL操作的例子
May 02 #Python
用Python编写简单的定时器的方法
May 02 #Python
用Python程序抓取网页的HTML信息的一个小实例
May 02 #Python
You might like
PHP中数组的三种排序方法分享
2012/05/07 PHP
php实现文件下载代码分享
2014/08/19 PHP
用PHP去掉文件头的Unicode签名(BOM)方法
2017/06/22 PHP
PHP与以太坊交互详解
2018/08/24 PHP
List the Stored Procedures in a SQL Server database
2007/06/20 Javascript
IE6/7/8中Option元素未设value时Select将获取空字符串
2011/04/07 Javascript
疯狂Jquery第一天(Jquery学习笔记)
2012/05/11 Javascript
Jquery Ajax方法传值到action的方法
2014/05/11 Javascript
JavaScript中的函数重载深入理解
2014/08/04 Javascript
排序算法的javascript实现与讲解(99js手记)
2014/09/28 Javascript
AngularJS的内置过滤器详解
2015/05/14 Javascript
javascript弹性运动效果简单实现方法
2016/01/08 Javascript
angular.js分页代码的实例
2016/07/27 Javascript
jQuery实现隔行变色的方法分析(对比原生JS)
2016/11/18 Javascript
解析AngularJS中get请求URL出现的跨域问题
2016/12/01 Javascript
vue2.0开发实践总结之疑难篇
2016/12/07 Javascript
Node.js安装配置图文教程
2017/05/10 Javascript
Vue.js搭建移动端购物车界面
2020/06/28 Javascript
js+SVG实现动态时钟效果
2018/07/14 Javascript
解决vue接口数据赋值给data没有反应的问题
2018/08/27 Javascript
浅谈Vue使用Cascader级联选择器数据回显中的坑
2020/10/31 Javascript
[01:15:36]加油刀塔第二期网络版
2014/08/09 DOTA
使用Python编写一个模仿CPU工作的程序
2015/04/16 Python
Python+Opencv识别两张相似图片
2020/03/23 Python
Python走楼梯问题解决方法示例
2018/07/25 Python
浅析python中的迭代与迭代对象
2018/10/08 Python
win10下opencv-python特定版本手动安装与pip自动安装教程
2020/03/05 Python
pytorch 计算Parameter和FLOP的操作
2021/03/04 Python
社区班子对照检查材料
2014/08/27 职场文书
离婚协议书怎么写
2014/09/12 职场文书
党员个人总结范文
2015/02/14 职场文书
工厂员工辞职信范文
2015/05/12 职场文书
居委会工作总结2015
2015/05/18 职场文书
2016年小学教师师德承诺书
2016/03/25 职场文书
Python字典和列表性能之间的比较
2021/06/07 Python
Python代码实现双链表
2022/05/25 Python