#coding: utf-8
'''
Author:
Time: 
Target: 
'''

import logging
import logging.handlers
import os
import json
import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado.options import define, options
import time
import gc



define("port", default=8000, help="Please send email to me", type=int)




def init_log(log_filename, pattern='test'):
    '''
    记录log日志
    :param log_filename:日志记录名
    :param pattern: 类型
    :return:
    '''
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    logger = logging.getLogger()
    if pattern == 'production':
        fh = logging.handlers.TimedRotatingFileHandler(
            filename=log_filename, when='midnight')
        fh.suffix = '%Y%m%d.log'
        logger.setLevel(logging.INFO)
    elif pattern == 'rotating_test':
        fh = logging.handlers.TimedRotatingFileHandler(
            filename=log_filename, when='M')
        fh.suffix = '%Y%m%d-%H%M.log'
        logger.setLevel(logging.DEBUG)
    elif pattern == 'test':
        fh = logging.FileHandler(filename=log_filename, mode='w')
        logger.setLevel(logging.DEBUG)
    else:
        #print('No Legal Pattern')
        raise TypeError
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    return logger




if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(
        handlers = [
            (r"/update", update),
            (r"/Cleantext",clean)
        ]
    )
    '''
    # 第一种多进程启动模式
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    http_server.start(4)
    #http_server.start()
    tornado.ioloop.IOLoop.instance().start()

    '''
    
    # 第二种多进程启动模式
    sockets = tornado.netutil.bind_sockets(options.port)
    task_id = tornado.process.fork_processes(4)
    #取到的task_id 是0~3。os.getpid()取子进程ID,os.getppid()取父进程ID
    if task_id is None:
        task_id = str(os.getpid()) + "_" + str(os.getppid())
    
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.add_sockets(sockets)

    #global LOGGER    
    LOG_FOLDER = './server_%s_log'%(options.port)
    if not os.path.exists(LOG_FOLDER):
        os.makedirs(LOG_FOLDER)
    LOG_PATH = os.path.join(LOG_FOLDER, 'ServerLog')
    # print(LOG_PATH)
    # 每个子进程自己创建一个日志文件
    LOGGER = init_log(LOG_PATH + str(task_id) , pattern='production')

    tornado.ioloop.IOLoop.instance().start()   

 

class update(tornado.web.RequestHandler):
    
    def post(self):

        result = {
            'status': 'success'
        }

    post_data = self.request.body
        time1=time.time()
        post_data=post_data.decode('utf-8')
        try:
            post_data=json.loads(post_data)
        except Exception as e:
            post_data=post_data.replace('\n','').replace('\r','')
            post_data = json.loads(post_data)

    #print(post_data)
        channel=post_data['channel']
        #print(channel)
        sentence=post_data['content']
        

        self.write(json.dumps(post_data))
        self.add_header('Content-Type', 'application/json')

    time2=time.time()
        LOGGER.info('INFO 200 POST/clean  %2.5f ms'%(1000*(time2-time1)))

 

posted on 2019-09-26 10:43  凌度  阅读(994)  评论(0编辑  收藏  举报