ITeye博客

python笔记(2)——Tornado

mywebcode · 2013-11-19 01:25 · Markdown

搭建tornado的环境,首先安装pip.

了解下pip——A tool for installing and managing Python packages.也就是一个python的包管理工具,类似于node里面的npm等等,根据https://pypi.python.org/pypi/pip网站上提示安装即可。

运行命令pip install pylint和命令pip install tornado分别安装上述两者,其中Pylint 是一个 Python 代码分析工具,它分析 Python 代码中的错误,查找不符合代码风格标准和有潜在问题的代码;Tornado是FriendFeed使用的可扩展的非阻塞式 web 服务器及其相关工具的开源版本。它是非阻塞式服务器,而且速度相当快。

经典的hello world示例:

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()

当用tornado进行开发时,为了避免重复开启服务器的麻烦,添加一小段从而让服务器能够自动reload新的代码,如下:

application = tornado.web.Application([
    (r"/", MainHandler),
    (r"/story/([0-9]+)", StoryHandler),
], debug = True)

加入debug = True这句,开启tornado的调试模式。

tornado的请求路径匹配

Tornado是基于正则表达式来匹配HTTP请求的路径,这个路径是URL中主机名后面的部分,不包括查询字符串和碎片。如果一个正则表达式包含一个捕获分组(即,正则表达式中的部分被括号括起来),匹配的内容将作为相应HTTP请求的参数传到RequestHandler对象中。get方法有一个额外的参数input。这个参数将包含匹配处理函数正则表达式第一个括号里的字符串。

例如,写一个简单的路径处理,实现的功能是输出“/firstInput/xxx” 路径后面的第一个字符,代码如下:

class firstInputHandler(tornado.web.RequestHandler):
	def get(self, input):
		self.write(input[0])

if __name__ == "__main__":	
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[
    		(r"/", IndexHandler),
    		(r"/firstInput/(\w+)", firstInputHandler),
    	],debug = True)

此外,对于每个RequestHandler类可以定义多个HTTP处理的方法,从而实现更完备的功能。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。