Home Backend Development Python Tutorial 探究Python的Tornado框架对子域名和泛域名的支持

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

Jun 10, 2016 pm 03:13 PM
python

其实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)

Copy after login

这种方式其实添加的是一个域名通配的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.
    """

Copy after login

只不过它是隐式的调用这个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])
Copy after login

常见的方式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)

Copy after login

指定的子域名的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),
         ]
        ]

Copy after login

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

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

Copy after login

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

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

Copy after login

需要说明的是,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

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

Python hourglass graph drawing: How to avoid variable undefined errors? Python hourglass graph drawing: How to avoid variable undefined errors? Apr 01, 2025 pm 06:27 PM

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Apr 01, 2025 pm 05:24 PM

Choice of Python Cross-platform desktop application development library Many Python developers want to develop desktop applications that can run on both Windows and Linux systems...

Do Google and AWS provide public PyPI image sources? Do Google and AWS provide public PyPI image sources? Apr 01, 2025 pm 05:15 PM

Many developers rely on PyPI (PythonPackageIndex)...

How to efficiently count and sort large product data sets in Python? How to efficiently count and sort large product data sets in Python? Apr 01, 2025 pm 08:03 PM

Data Conversion and Statistics: Efficient Processing of Large Data Sets This article will introduce in detail how to convert a data list containing product information to another containing...

How to optimize processing of high-resolution images in Python to find precise white circular areas? How to optimize processing of high-resolution images in Python to find precise white circular areas? Apr 01, 2025 pm 06:12 PM

How to handle high resolution images in Python to find white areas? Processing a high-resolution picture of 9000x7000 pixels, how to accurately find two of the picture...

How to solve the problem of file name encoding when connecting to FTP server in Python? How to solve the problem of file name encoding when connecting to FTP server in Python? Apr 01, 2025 pm 06:21 PM

When using Python to connect to an FTP server, you may encounter encoding problems when obtaining files in the specified directory and downloading them, especially text on the FTP server...

See all articles