python tornado motor 异步操作mongodb

# -*- coding: utf-8 -*-
import logging
import logging.handlers

import motor.motor_tornado

import tornado.ioloop

import tornado
import tornado.web
import tornado.httpserver

from http_handler import ScooterNotifyHandler

from tornado.options import define, options, parse_command_line

__author__ = 'Ennis'

LISTEN_PORT=7900
define("port", default=LISTEN_PORT, help="http server listen port")

db_con = motor.motor_tornado.MotorClient("mongodb://192.168.1.205:12345")


def init_logging():
    """
    日志文件设置,每天切换一个日志文件
    :return:
    """
    logger = logging.getLogger()
    logger.setLevel(log_level)


    sh = logging.StreamHandler()
    file_log = logging.handlers.RotatingFileHandler('scooter_notify.log', maxBytes=10 * 1024 * 1024, backupCount=50)
    formatter = logging.Formatter(
        '[%(asctime)s] [%(levelname)-7s] [%(module)s:%(filename)s-%(funcName)s-%(lineno)d] %(message)s')
    sh.setFormatter(formatter)
    file_log.setFormatter(formatter)


    logger.addHandler(sh)
    logger.addHandler(file_log)


    logging.info("Current log level is : %s", logging.getLevelName(logger.getEffectiveLevel()))




def start_http_serv():
    try:
        # 装载url配置


        app = tornado.web.Application(
            handlers=[
                (r'/scooter_notify', ScooterNotifyHandler),
            ],
            db=db_con
        )


        # 配置server
        api_server = tornado.httpserver.HTTPServer(app)
        api_server.listen(options.port)
        logging.info("start scooter notify http server at: %d", options.port)
    except Exception as e:
        logging.error('Exception: %s', e)


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


if __name__ == '__main__':
    try:
        # 隐藏窗口
        whnd = ctypes.windll.kernel32.GetConsoleWindow()
        if whnd != 0:
            ctypes.windll.user32.ShowWindow(whnd, 0)
            ctypes.windll.kernel32.CloseHandle(whnd)
        # 解析参数
        parse_command_line()


        init_logging()
        start_http_serv()
    except Exception as e:
        print("start scooter notify fail: %s", e)


以下为具体操作实现,tornado的post接口实现过程,http_handler.py

# coding: utf8


from tornado.web import RequestHandler
import tornado.gen
import tornado.httpclient
import json
import logging


class ScooterNotifyHandler(RequestHandler):
    def data_received(self, chunk):
        pass


    @tornado.gen.coroutine
    def post(self):
        try:
            # 获取request 内容
            db = self.settings['db']


            req_body = self.request.body.decode()
            logging.info('req_body = [%s]', req_body)
            data_info = json.loads(req_body)

           reader_pos = yield db[DB_SG]['tReader'].find_one({'serial': reader_serial}, {'positioninfo': 1, '_id': 0})  # 查找一个,具体需根据实际数据库操作

            control_info = db[DB_SG]['tControlRule'].find({'targets': vehicle_info['vin']}, {'distance': 1})   # 多个查询操作,插入、更新与pymongo相同,需加yield
            for one_control in (yield control_info.to_list(1000)):

                  pass

                  # do one_control operate

        except Exception as e:
            msg = "ScooterNotifyHandler post api err=%s" % e
            logging.error(msg)
            msg_dict = dict()
            msg_dict['status'] = 1
            msg_dict['text'] = msg
            self.write(msg_dict)
            self.finish()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值