Tornado服务器中绑定域名、虚拟主机的方法
Jun 16, 2016 am 08:42 AMTornado默认是监听IP加端口形式,由于Tornado在国内用的人极少,资料更是鳞毛凤角。下面说说Tornado如何绑定域名。
默认Tornado的hello word是这么来的
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
运行后,使用浏览器访问IP+8888端口
如果你想支持域名访问,可以用Nginx监听80端口做代理,或者你只有这么一个应用,直接就用Tornado监听80端口免去Nginx这一步,关键是这么干别人使用IP或者域名都能访问。谷歌了一大堆英文站点也找不到绑定域名教程,反正Tornado源文件也就那一点就翻开看看,里边怎么写?结果看到这么一段话
大喜!不知道为什么,这段在文档里是没有的,然后再往下细看,返现默认是有host机制的,并且任何host访问,截图
既然这样,那我们就可以使用域名绑定的方式来运行tornado应用了,而且支持多域名,因为那就是一串正则,在刚才那个例子的基础上加个域名绑定
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
class DomainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, a.com")
application = tornado.web.Application([
(r"/", MainHandler),
])
application.add_handlers(r"^a\.com$", [
(r"/", DomainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
a.com访问结果
甚至也可以支持正则匹配,比如让它也支持www前缀
application.add_handlers(r"^(www\.)?a\.com$", [(r"/", DomainHandler),])
执行结果
结合这个机制,你可以在一个应用上绑定多个域名及子域名泛域名的多站部署。更易于管理!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to Use Python to Find the Zipf Distribution of a Text File

How Do I Use Beautiful Soup to Parse HTML?

How to Work With PDF Documents Using Python

How to Cache Using Redis in Django Applications

Introducing the Natural Language Toolkit (NLTK)

How to Perform Deep Learning with TensorFlow or PyTorch?
