在python中配置tornado服务

####################################################################
####################################################################
import tornado.httpserver
import tornado.options
import tornado.web
from tornado.options import define, options

from data_util import UtilsLTPTranslate

define("port", default=8005, help="run on the given port", type=int)

启动的服务

class HandlerLTPTranslate(tornado.web.RequestHandler):
def post(self):
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
self.api_response()

def api_response(self):
    post_data = {}
    response = {}
    data=[]
    try:
        for key in self.request.arguments:
            post_data[key] = self.get_arguments(key)[0]
            text = post_data["text"]
        if post_data["flag"] == "companyName":
            data.append(self.application.UtilsLTPTranslate.getEnCompanyName(text))
        elif post_data["flag"] == "address":
            data.append(self.application.UtilsLTPTranslate.getEnAddress_2(text))
        elif post_data["flag"] != "common" :
            data.append(self.application.UtilsLTPTranslate.zh2en(text))
        else:
            data.append(self.application.UtilsLTPTranslate.zh2en(text))
        response["data"] = data
except:
        response["data"] = data
self.finish(json.dumps(response, ensure_ascii=False))

为了防止重复加载数据模型,需要初始化

class Application(tornado.web.Application):
def init(self):
self.UtilsLTPTranslate = UtilsLTPTranslate()
handlers = [(r"/LTPTranslate", HandlerLTPTranslate)]
tornado.web.Application.init(self,handlers,)

def forService():
print("启动.............................")
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.bind(options.port)
http_server.start(0)
tornado.ioloop.IOLoop.instance().start()

if name == 'main':
forService() #启动服务

posted @ 2017-11-29 17:56  wdan2016  阅读(1488)  评论(0编辑  收藏  举报