1. 程式人生 > >在python中配置tornado服務

在python中配置tornado服務

配置 ice http mar for -o cati ptr pytho

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() #啟動服務

在python中配置tornado服務