Пример #1
0
def orderCallback(oId, userId, status, order):
    logger.debug('oId:%s, userId:%s, status:%d, order:%s', oId, userId, status,
                 order)
    '''
    根据支付结果更新订单的状态
    :param oId:RechargeFlow Id
    :param userId:用户Id
    :param status: 支付是否成功,1为成功,0为失败
    :param order:第三方平台返回订单信息,包括错误码
    :return: 
    '''
    item = {"$set": {"status": status, "order": order}}
    ###更新充值流水记录
    orderHelper = ClassHelper("RechargeFlow")
    rechargeFlow = orderHelper.update(oId, item)
    if rechargeFlow and status == 1:
        ###更新钱包
        walletHelper = ClassHelper("Wallet")
        walletInfo = walletHelper.find_one({"user": userId})
        if walletInfo:
            wallet = {"$inc": {'balance': rechargeFlow['amount']}}
            wallet = walletHelper.update(walletInfo['_id'], wallet)
        else:
            wallet = {"user": userId, 'balance': rechargeFlow['amount']}
            walletHelper.create(wallet)
        if wallet:
            return wallet.update(rechargeFlow)
        else:
            return None
    else:
        return None
Пример #2
0
 def on_message(self, message):
     try:
         logger.debug('on message: %s', message)
         obj = json.loads(message)
         if type(obj) != dict:
             self.go_to_close('wrong message, not json')
         else:
             if dict(obj).has_key('t'):
                 self.dict_body = obj
                 t = obj['t']
                 if t == MessageType.TYPE_MSG_INPUTTING:
                     InputtingExecute.execute(self)
                 elif t == MessageType.TYPE_COMMENT_INPUTTING:
                     InputtingExecute.execute(self)
                 elif t == MessageType.TYPE_FRIEND:
                     pass
                 else:
                     self.go_to_close('cannot find a right type of message')
             else:
                 self.go_to_close('wrong message, don not have t')
     except Exception, e:
         logger.error(e)
         msg = traceback.format_exc()
         logger.error(msg)
         self.go_to_close('wrong message')
Пример #3
0
def sub_pub_start():
    rc = RedisDb.get_connection()
    ps = rc.pubsub()
    ps.subscribe([Constants.REDIS_CHANNEL_FOR_PUSH])

    for item in ps.listen():
        try:
            if item['type'] == 'message':
                logger.debug('channel:' + item['channel'] + ' receive a message:')
                message_json = item['data']
                logger.debug(message_json)
                obj = json.loads(message_json)
                # logger.debug(obj)
                # logger.debug(obj.get('from_id'))
                # logger.debug(obj.get('to_id'))
                # logger.debug(s.split('_')[0])
                # logger.debug(s.split('_')[1])
                logger.debug(Pool.user_dict.__len__())
                handler = Pool.user_dict.get(str(obj.get('to_id')))
                if handler:
                    logger.debug(' handler exists')
                    # handler.write_message(crypto.encrypt(message_json))
                    handler.write_message(message_json)
                else:
                    logger.debug(' handler is None')
        except Exception as e:
            logger.error(e)
Пример #4
0
 def on_close(self):
     logger.debug('connect closed')
     if self.userid:
         WsHandler.remove_from_dict(str(self.userid))
     if self.cookie:
         WsHandler.remove_from_dict(str(self.cookie))
     # for test start
     # WsHandler.remove_from_dict(self)
     # for test end
     logger.debug('user dict length is: %d', Pool.user_dict.__len__())
Пример #5
0
def execute(from_handler):
    obj = from_handler.dict_body
    to_handler = Pool.user_dict.get(str(obj['to_id']))
    if to_handler:
        del obj['to_id']
        obj['from_id'] = to_handler.userid
        logger.debug(' handler exists')
        to_handler.write_message(obj)
    else:
        logger.debug(' handler is None')
Пример #6
0
def params_to_query(params, quotes=False, reverse=False):
    """
        生成需要签名的字符串
    :param params:
    :return:
    """
    """
    :param params:
    :return:
    """
    query = ""
    for key in sorted(params.keys(), reverse=reverse):
        value = params[key]
        if quotes == True:
            query += str(key) + "=\"" + str(value) + "\"&"
        else:
            query += str(key) + "=" + str(value) + "&"
    query = query[0:-1]
    logger.debug('query: %s', query)
    return query
Пример #7
0
def check():
    while True:
        logger.debug('check ping')
        logger.debug('ws handler num is below:')
        logger.debug(Pool.user_dict.__len__())
        if Pool.user_dict.__len__() > 0:
            for k, v in Pool.user_dict.items():
                # print k, v
                try:
                    v.write_message('1')
                except Exception, e:
                    logger.error(e)
                    msg = traceback.format_exc()  # 方式1
                    logger.error(msg)
                    WsHandler.remove_from_dict(k)
        time.sleep(10)
Пример #8
0
 def open(self):
     logger.debug('connect open')
     try:
         logger.debug('cookies blow:')
         # logger.debug(self.cookies)
         # logger.debug(self.locale)
         logger.debug(self)
         # for test start
         logger.debug('X-Cookie: %s', self.request.headers['X-Cookie'])
         cookie = self.request.headers['X-Cookie'].split('"')[1]
         logger.debug('cookie: %s', cookie)
         if cookie:
             self.cookie = cookie
             self.userid = RedisUtil.getUid(cookie)
         logger.debug(self.userid)
         # for test end
         # for test start
         # WsHandler.add_to_dict(self, self)
         # logger.debug('user dict length is below:')
         # logger.debug(Pool.user_dict.__len__())
         # for test end
         if cookie and self.userid:
             WsHandler.add_to_dict(str(self.userid), self)
         else:
             logger.warn('error cookie,非法链接')
             self.go_to_close('error cookie,非法链接')
     except Exception as e:
         logger.error(e)
         msg = traceback.format_exc()
         logger.error(msg)
         self.close()
Пример #9
0
 def check_origin(self, origin):
     logger.debug('check_origin')
     return True
Пример #10
0
 def data_received(self, chunk):
     logger.debug('data received')
     pass
Пример #11
0
class Application(Application):
    pass


threads = []
t1 = threading.Thread(target=RedisThread.sub_pub_start)
# t2 = threading.Thread(target=PingThread.check)
threads.append(t1)
# threads.append(t2)

if __name__ == '__main__':
    config = ConfigParser()
    config.read('./config')
    mode = config.get('global', 'mode')
    # set redis config and create redis pool
    RedisDBConfig.HOST = config.get('redis', 'REDIS_HOST')
    RedisDBConfig.PASSWORD = config.get('redis', 'REDIS_PASSWORD')
    Constants.REDIS_CHANNEL_FOR_PUSH = config.get('redis', 'REDIS_SUB_CHANNEL')
    EsClient.ES_SERVERS = [{
        'host': config.get('es', 'ES_HOST'),
        'port': config.get('es', 'ES_PORT')
    }]
    EsClient.init()
    for t in threads:
        t.setDaemon(True)
        t.start()
    logger.info('redis sub has run')
    Application().start()
    logger.debug('server has run')
Пример #12
0
threads = []
t1 = threading.Thread(target=RedisThread.sub_pub_start)
# t2 = threading.Thread(target=PingThread.check)
threads.append(t1)
# threads.append(t2)

if __name__ == '__main__':
    config = ConfigParser()
    configFile = ''
    opts, args = getopt.getopt(sys.argv[1:], "c:p:")
    if opts:
        for opt, arg in opts:
            if opt == '-c':
                configFile = arg
    logger.debug('configFile:%s', configFile)
    config.read(configFile)

    # config = ConfigParser()
    # config.read('./config_test')
    # mode = config.get('global', 'mode')
    # set redis config and create redis pool
    RedisDBConfig.HOST = config.get('redis', 'REDIS_HOST')
    RedisDBConfig.PASSWORD = config.get('redis', 'REDIS_PASSWORD')
    Constants.REDIS_CHANNEL_FOR_PUSH = config.get('redis', 'REDIS_SUB_CHANNEL')
    EsClient.ES_SERVERS = [{
        'host': config.get('es', 'ES_HOST'),
        'port': config.get('es', 'ES_PORT')
    }]
    EsClient.init()
    for t in threads: