python Tornado简单服务器搭建

来源:互联网 发布:血族第四季 知乎 编辑:程序博客网 时间:2024/06/06 04:01

官方网站http://old.sebug.net/paper/books/tornado/


FriendFeed使用了一款使用 Python 编写的,相对简单的 非阻塞式 Web 服务器。其应用程序使用的 Web 框架看起来有些像 web.py 或者 Google 的 webapp, 不过为了能有效利用非阻塞式服务器环境,这个 Web 框架还包含了一些相关的有用工具 和优化。

Tornado 就是我们在 FriendFeed 的 Web 服务器及其常用工具的开源版本。Tornado 和现在的主流 Web 服务器框架(包括大多数 Python 的框架)有着明显的区别:它是非阻塞式服务器,而且速度相当快。得利于其 非阻塞的方式和对 epoll 的运用,Tornado 每秒可以处理数以千计的连接,因此 Tornado 是实时 Web 服务的一个 理想框架。我们开发这个 Web 服务器的主要目的就是为了处理 FriendFeed 的实时功能 ——在 FriendFeed 的应用里每一个活动用户都会保持着一个服务器连接。(关于如何扩容 服务器,以处理数以千计的客户端的连接的问题)


以下是经典的 “Hello, world” 示例:

import tornado.ioloopimport tornado.webclass 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()


写过的一个例子:

IN:http://10.10.177.179:10081/slquery?dept=PEK&dest=CDG&type=flight&pay_method=mioji

OUT:源列表

#!/usr/bin/python#! -*- coding:utf-8 -*-import tornado.httpserverimport tornado.ioloopimport tornado.optionsimport tornado.webimport jsonimport syssys.path.append('/home/workspace/ProxyServer/bin')sys.path.append('/home/fangwang/statistic_scripts/')import osfrom DBHandle import DBHandleimport remonitor_source = DBHandle("10.10.87.87","root","miaoji@2014!","devdb")source_mioji_dict=dict()source_self_mioji_dict=dict()source_raw=[]flight_validation_dict=dict()def init_source_tab():    #初始化源列表    res=monitor_source.QueryBySQL("SELECT * FROM source WHERE pay_method != 'NULL'")        for line in res:        if  line['pay_method'].find('mioji') != -1:            tmp_type=line['type']            source_mioji_dict.setdefault(tmp_type,[])            source_mioji_dict[tmp_type].append(line['name'])        elif  line['pay_method'] == 'self+mioji':            tmp_type=line['type']            source_self_mioji_dict.setdefault(tmp_type,[])            source_self_mioji_dict[tmp_type].append(line['name'])def init_flight_validation_tab():    #初始化过滤列表    res=monitor_source.QueryBySQL("SELECT * FROM flight_validation where status != 0")    for line in res:        if line['type']=='oneway':            key=line['dept_id']+'|'+line['dest_id']            flight_validation_dict.setdefault(key,[])            flight_validation_dict[key].append(line['source'])def add_source(_type,pay_method):    #取出source所有源    source_list=[]    global source_raw    if  _type == 'flight':        if pay_method == 'mioji':            source_raw=source_mioji_dict['flight_one_way']        elif pay_method == 'self+mioji':            source_raw=source_self_mioji_dict['flight_one_way']        for source in source_raw:            source_list.append(source)    return source_listdef validation_source(dept,dest,_type,source_list):    #过滤source表    if _type == 'flight':        source_validation=[]        key=dept+'|'+dest        if key not in flight_validation_dict.keys():            source_validation.append('ctripFlight')            source_validation.append('expediaFligh')            return source_validation        tmp_source = flight_validation_dict[key]        for source in source_raw:            if source in tmp_source:                source_validation.append(source)        if len(source_validation)<=1:            source_validation.append('ctripFlight')            source_validation.append('expediaFlight')        return source_validationclass hello(tornado.web.RequestHandler):    def get(self):        print self.request        try:            dept = self.get_argument('dept')        except:            print 'put in dept error'        try:            dest = self.get_argument('dest')        except:            print 'put in dest error'        try:            pay_method = self.get_argument('pay_method')        except:            print 'put in pay_method error'        try:            trans_type = self.get_argument('type')        except:            print 'put in trans_type error'        print("dept: %s, dest: %s, trans_type: %s, pay_method: %s" % (dept, dest, trans_type,pay_method))        source_list = []        #根据类型计算source_list        #...                        source_list = add_source(trans_type,pay_method)        source_list = validation_source(dept,dest,trans_type,source_list)                source_list = list(set(source_list))        if 'mioji' in source_list:            source_list.remove('mioji')        self.write(json.dumps(source_list))if __name__ == '__main__':    init_source_tab()    init_flight_validation_tab()    print 'inited over'    application = tornado.web.Application([        (r"/slquery", hello)            ])    http_server = tornado.httpserver.HTTPServer(application)    http_server.listen(10081)    http_server.start()    tornado.ioloop.IOLoop.instance().start()







0 0
原创粉丝点击