Exemplo n.º 1
0
 def completeAppleAppOrder(self):
     try:
         obj = json.loads(self.request.body)
     except Exception, e:
         log.err("JSON Error:[%d/%s] , error:%s", len(self.request.body), self.request.body, str(e))
         self.write(ERR_INVALID.message)
         return
Exemplo n.º 2
0
    def unfollow(user, followee, is_user=True):
        if not user or not followee:
            log.err("FollowHelper-->unfollow userId:%s, followeeId %s", user,
                    followee)
            return
        if is_user:
            fieldname = "followee"
        else:
            fieldname = "backupFollowee"

        followHelper = ClassHelper(FollowHelper.classame)
        result = followHelper.find_one({
            'user': followee,
            'followee': user,
            'effect': {
                '$gte': 2
            }
        })
        if result:
            #双向关注,需要处理followee的双向关注effect和粉丝数量
            followHelper.updateOne({
                'user': followee,
                fieldname: user
            }, {"$set": {
                'effect': 1,
                'updateAt': result['updateAt']
            }})

        # 取消我的关注
        followee_action = {
            'destClass': 'StatCount',
            'query': {
                'name': 'followees_' + user
            },
            'action': {
                '@inc': {
                    'count': -1
                }
            }
        }
        follower_action = {
            'destClass': 'StatCount',
            'query': {
                'name': 'followers_' + followee
            },
            'action': {
                '@inc': {
                    'count': -1
                }
            }
        }
        actions = [follower_action, followee_action]
        followHelper.updateOne({
            'user': user,
            fieldname: followee
        }, {"$set": {
            'effect': 0
        }},
                               transactions=actions,
                               upsert=True)
Exemplo n.º 3
0
 def setex(key, value, expireSeconds, dbid=0):
     try:
         return RedisDb.get_connection(dbid).setex(key, value,
                                                   expireSeconds)
     except Exception, e:
         log.err("redis setex operation fail , error:%s", str(e))
         return False
Exemplo n.º 4
0
 def post(self):
     try:
         xml = self.request.body
         log.debug('xml: %s', xml)
         pub = Wxpay_server_pub()
         pub.saveData(xml)
         log.debug('pub.data: %s', pub.data)
         if pub.data['return_code'] == 'SUCCESS' and pub.data[
                 'result_code'] == 'SUCCESS':
             print 'wx call back result is success'
             order_no = pub.data.get('out_trade_no', None)
             log.debug('out_trade_no:%s', order_no)
             if order_no:
                 flow = ClassHelper("RechargeFlow").find_one({
                     'orderNo': order_no,
                     'status': 0
                 })
                 if flow:
                     payUtil.orderCallback(flow['_id'], flow['user'], 1,
                                           pub.data)
         else:
             order_no = pub.data.get('out_trade_no', None)
             if order_no:
                 flow = ClassHelper("RechargeFlow").find_one({
                     'orderNo': order_no,
                     'status': 0
                 })
                 if flow:
                     payUtil.orderCallback(flow['_id'], flow['user'], -1,
                                           pub.data)
     except Exception, e:
         log.err(e)
         msg = traceback.format_exc()
         log.err(msg)
Exemplo n.º 5
0
 def delete(self, className, objectId):
     if not objectId:
         self.write(ERR_PARA.message)
         return
     if BaseConfig.deleteClass.count(className) <= 0:
         self.write(ERR_USER_PERMISSION.message)
         return
     try:
         ObjectId(objectId)
     except Exception:
         self.write(ERR_OBJECTID_MIS.message)
         return
     classHelper = ClassHelper(className)
     obj = classHelper.find_one({"_id": objectId})
     if not obj:
         self.write(ERR_OBJECTID_MIS.message)
         return
     mo = MeObject(className, obj, False)
     mo.overLoadGet = False
     acl = MeACL(mo['acl'])
     if not acl.deleteAccess(self.user):
         self.write(ERR_USER_PERMISSION.message)
         return
     else:
         try:
             classHelper.delete(objectId)
             self.write(ERR_SUCCESS.message)
         except Exception, e:
             log.err("ClassHandler-->delete error, %s", e)
             self.write(ERR_DB_OPERATION.message)
Exemplo n.º 6
0
 def zrange(key, start, end, withscores=False, dbid=0):
     try:
         return RedisDb.get_connection(dbid).zrange(key,
                                                    start,
                                                    end,
                                                    withscores=withscores)
     except Exception, e:
         log.err("redis zrangebyscore operation fail , error:%s", str(e))
         return None
Exemplo n.º 7
0
    def getFollowees(user, lastTime=None, count=10, skipNum=0):
        if not user:
            log.err("FollowHelper-->getFollowees userId is None")
            return None

        #sortDict = {"_sid": 1}
        #query = {'user':user, "_sid": {"$gt": start}, 'effect':{'$gte':1}}
        #followHelper = ClassHelper( FollowHelper.classame )
        #return followHelper.find( query, sort=sortDict, limit=count)
        return FollowHelper.find_list("Followee", user, lastTime, count,
                                      skipNum)
Exemplo n.º 8
0
 def charge(self):
     '''
     obj = {'id':Goods_id:True,'chargeFlowId':ChargeFlow_id:False} chargeFlowId是在重新发起支付时需要传递
     :return: 
     '''
     try:
         obj = json.loads(self.request.body)
     except Exception, e:
         log.err("JSON Error:[%d/%s] , error:%s", len(self.request.body), self.request.body, str(e))
         self.write(ERR_INVALID.message)
         return
Exemplo n.º 9
0
 def initMongodbIndex(self):
     db = MongoDb()
     haveIndex = {}
     for classname in BaseConfig.projectClass:
         try:
             haveIndex[classname] = db.listIndex(classname)
             if {"_sid": 1} not in haveIndex[classname]:
                 db.index(classname, [("_sid", 1)])
                 log.info("classname:%s, index:%s", classname, json.dumps([("_sid", 1)]))
         except Exception, e:
             log.err("Error:%s, error:%s", classname, str(e))
Exemplo n.º 10
0
def get_follow_ount(userId, isUser=1):
    '''
    # 粉丝数:Followee (backup)followee, 照片数(认领的照片):Face assign.user,贡献者个数:Face assign.assigner uploader
    :param userId: 注册用户Id
    :return:
    '''

    # classHelper = ClassHelper( 'StatCount' )
    # try:
    #     if is_mine:
    #         result = classHelper.find( {'name': {
    #             '$in': ['albumMost_' + userId, 'albumAnimal_' + userId, 'albumBaby_' + userId,
    #                     'albumChowhound_' + userId, 'followers_' + userId, 'medias_' + userId, 'followees_' + userId,
    #                     'uploaders_' + userId, 'faces_' + userId, 'assigners_' + userId]}}, {"_id": 0} )
    #     else:
    #         result = classHelper.find( {'name': {
    #             '$in': ['followers_' + userId, 'medias_' + userId, 'followees_' + userId, 'assigners_' + userId]}},
    #                                    {"_id": 0} )
    # except Exception, e:
    #     log.err( "%s find StatCount error", userId )
    # if result:
    #     return result
    # else:
    #     return None
    #
    obj = {}
    try:
        followeeHelper = ClassHelper( 'Followee' )
        faceHelper = ClassHelper( 'Face' )
        if isUser:
            # 关注数
            followeesCount = followeeHelper.query_count( {'user': userId, "effect": {"$gt": 0}} ) or 0
            obj['followees'] = followeesCount
            mediasCount = faceHelper.query_count( {'assign.user': userId,'assign.status': 1} ) or 0
            obj['medias'] = mediasCount
            # 粉丝数
            followersCount = followeeHelper.query_count( {'followee': userId, "effect": {"$gt": 0}} ) or 0
            obj['followers'] = followersCount
        else:
            mediaHelper = ClassHelper( 'Media' )
            mediasCount = mediaHelper.query_count( {'backupUser': userId} )
            obj['medias'] = mediasCount
            # 粉丝数
            followersCount = followeeHelper.query_count( {'backupFollowee': userId, "effect": {"$gt": 0}} ) or 0
            obj['followers'] = followersCount

        # 贡献者数
        assignersCount = faceHelper.distinct( {'assign.user': userId, 'assign.status': 1}, "assign.assigner" ) or []
        obj['assigners'] = len( assignersCount.cursor )

    except Exception, ex:
        log.err( ex.message )
        return None
Exemplo n.º 11
0
 def get(self,action=None):
     '''
     # where 条件格式:[{
                         "condition": {
                             "user": "******"
                         },
                         "key": "xxx",
                         "method": "count/id/list/jsonObject",
                         "classname": "xxx"
                     },
                     {
                         "condition": {
                             "user": "******"
                         },
                         "key": "xxx",
                         "method": "count/id/list/jsonObject",
                         "classname": "xxx"
                     }]
     #返回数据格式:{"a":11,"b":10}
     '''
     if self.request.arguments.has_key('where'):
         where = eval(self.get_argument('where'))
         result = {}
         for item in where:
             className = item['classname']
             if self.user['_id'] not in BaseConfig.adminUser:
                 if className == 'User':
                     continue
             query = item["condition"]
             try:
                 if query.has_key('_id'):
                     ObjectId(query['_id'])
                     # if query.has_key('$or'):
                     #     for item in query['$or']:
                     #         if "_id" in item:
                     #             item["_id"] = ObjectId(item["_id"])
             except Exception:
                 self.write(ERR_OBJECTID_MIS.message)
                 return
             try:
                 if item['method'] == 1:
                     result[item['key']] = self.getCount(className, query)
                 elif item['method'] == 2:
                     result[item['key']] = self.getId(className, query)
                 elif item['method'] == 3:
                     result[item['key']] = self.getList(className, query)
                 elif item['method'] == 4:
                     result[item['key']] = self.getJson(className, query)
                 elif item['method'] == 5:
                     result[item['key']] = self.getDistinct(className, query, item['distinct'])
             except Exception,e:
                 log.err("%s param error", item['key'])
         self.write(json.dumps(result,cls=MeEncoder))
Exemplo n.º 12
0
 def recharge(self):
     '''
     添加充值记录
     :return: 
     '''
     try:
         obj = json.loads(self.request.body)
     except Exception, e:
         log.err("JSON Error:[%d/%s] , error:%s", len(self.request.body),
                 self.request.body, str(e))
         self.write(ERR_INVALID.message)
         return
Exemplo n.º 13
0
 def post(self, className):
     try:
         try:
             obj = json.loads(self.request.body)
             obj = self.check_field(className, obj)
             if not obj:
                 return
         except Exception, e:
             log.err("JSON Error:%s , error:%s", self.request.body, str(e))
             self.write(ERR_INVALID.message)
             return
         print 'className:' + className
         if type(obj) == list:
             objectIdError = False
             for index in range(len(obj) - 1):
                 try:
                     for key, value in obj[index].items():
                         if value.has_key('_sid'):
                             ObjectId(value['_sid'])
                         value = self.sentiveCheck(key, value)
                         value = self.blacklistCheck(className, value)
                         if value:
                             meobj = MeObject(key, value)
                             meobj.save()
                         else:
                             self.write(ERR_BLACK_PERMISSION.message)
                 except bson.errors.InvalidId:
                     objectIdError = True
                     break
                 except Exception, e:
                     log.err("Error:%s , error:%s", self.request.body,
                             str(e))
             if objectIdError:
                 self.write(ERR_OBJECTID_MIS.message)
                 return
             mainObj = obj[len(obj) - 1]
             try:
                 if mainObj.has_key('_sid'):
                     ObjectId(mainObj['_sid'])
                 mainObj = self.sentiveCheck(className, mainObj)
                 mainObj = self.blacklistCheck(className, mainObj)
                 if mainObj:
                     meobj = MeObject(className, mainObj)
                     meobj.save()
                     self.write(json.dumps(meobj, cls=MeEncoder))
                 else:
                     self.write(ERR_BLACK_PERMISSION.message)
             except bson.errors.InvalidId:
                 self.write(ERR_OBJECTID_MIS.message)
Exemplo n.º 14
0
    def getFollowers(user, lastTime=None, count=10, is_user=True, skipNum=0):
        if not user:
            log.err("FollowHelper-->getFollowers userId is None")
            return None
        #if is_user:
        #    fieldname = "followee"
        #else:
        #    fieldname = "backupFollowee"

        #followHelper = ClassHelper(FollowHelper.classame)
        #sortDict = {"_sid": 1}
        #query = {fieldname:user, "_sid": {"$gt": start}, 'effect':{'$gte':1}}
        #return followHelper.find(query, sort=sortDict, limit=count)

        return FollowHelper.find_list("Follower", user, lastTime, count,
                                      is_user, skipNum)
Exemplo n.º 15
0
 def post(self, action=None):
     if action == 'signup':
         self.signup()
     elif action == 'login':
         self.login()
     elif action == 'modifyPwd':
         self.modifyPwd()
     elif action == 'update':
         pass
     elif action == 'check':
         self.check()
     # elif action=='loginWithoutPwd':
     #			self.loginWithoutPwd()
     else:
         log.err("userHandler path error %s", action)
         self.write(ERR_PATH_PERMISSION.message)
Exemplo n.º 16
0
 def put(self, action=None):
     if action == "update":
         try:
             obj = json.loads(self.request.body)
         except Exception, e:
             log.err("JSON Error:[%d/%s] , error:%s",
                     len(self.request.body), self.request.body, str(e))
             self.write(ERR_INVALID.message)
             return
         classHelper = ClassHelper("User")
         # 只返回了更新时间
         try:
             data = classHelper.update(self.user['_id'], obj)
             # 默认返回整个对象
             self.write(json.dumps(data, cls=MeEncoder))
         except Exception, e:
             log.err("UserHandler-->update in put() error, %s", e)
             self.write(e.message)
Exemplo n.º 17
0
    def create_core(self, obj):
        log.debug('[%s] create object start: %s' % (self.className, obj))
        embed = None
        for key in obj.keys():
            # 如果是pointer类型,则递归处理对象
            if isinstance(
                    obj[key], dict) and obj[key].has_key('_type') and obj[key][
                        '_type'] == 'pointer' and obj[key].has_key('_content'):
                # 创建对应的classhelper
                c = ClassHelper(obj[key]['_class'], self.appName)
                # 用于保存递归对象,递归对象内容不存到父对象
                embed = {}
                embed[key] = deepcopy(obj[key])
                # 如果存在_id,则递归update
                if obj[key].has_key('_id'):
                    o = c.update_core(obj[key]['_id'], obj[key]['_content'])
                else:
                    o = c.create_core(obj[key]['_content'])
                # 删除_content,使得父对象存储pointer对象
                ''' TODO 此处无法保存updateAt和createAt返回客户端 '''
                del obj[key]['_content']

                obj[key]['_id'] = o[0]['_id']
                print "Key:" + key
                print "O: " + str(o)
                print "embed1: " + str(embed)
                embed[key]['_id'] = o[0]['_id']
                # 将递归对象拼接起来
                if o[1] != None:
                    if embed[key]['_content'].has_key('$set'):
                        del embed[key]['_content']['$set']
                    # 内部还有递归的情况,同级可能有多个递归对象
                    for embed_key in o[1].keys():
                        embed[key]['_content'][embed_key] = o[1][embed_key]
                else:
                    embed[key]['_content'] = o[0]
                print "embed2: " + str(embed)
        obj['updateAt'] = datetime.now()
        obj['createAt'] = obj['updateAt']
        try:
            if obj.has_key("_id"):
                obj["_sid"] = MongoDb.toId(obj['_id'])
        except Exception, e:
            log.err("Error:%s", str(e))
Exemplo n.º 18
0
    def initWxPay(self):
        ##>> 微信支付相关
        # =======【基本信息设置】=====================================
        # # 微信公众号身份的唯一标识。审核通过后,在微信发送的邮件中查看
        # APPID = "wx9cfa3027bbe4e110"
        # # JSAPI接口中获取openid,审核后在公众平台开启开发模式后可查看
        # APPSECRET = "40ed3f5c3569b12a157962af67afcffe"
        # # 受理商ID,身份标识
        # MCHID = "1384167002"
        # # 商户支付密钥Key。审核通过后,在微信发送的邮件中查看(可以在商户平台设置)
        # KEY = "CE0ModS4VMgWlZpqjZDo4fjzMPBTH6Gf"

        # # =======【异步通知url设置】===================================
        # # 异步通知url,商户根据实际开发过程设定
        # NOTIFY_URL = "http://n01.me-yun.com:8000/1.0/wxpaycallback"
        # NOTIFY_URL_RELEASE = "http://api.videer.net/1.0/wxpaycallback"

        # # =======【JSAPI路径设置】===================================
        # # 获取access_token过程中的跳转uri,通过跳转将code传入jsapi支付页面
        # JS_API_CALL_URL = "http://******.com/pay/?showwxpaytitle=1"

        # # =======【证书路径设置】=====================================
        # # 证书路径,注意应该填写绝对路径
        # SSLCERT_PATH = "/******/cacert/apiclient_cert.pem"
        # SSLKEY_PATH = "/******/cacert/apiclient_key.pem"
        try:
            WxPaySDK.WxPayConf_pub.APPID = self.config.get('wxpay', 'WX_APPID')
            WxPaySDK.WxPayConf_pub.APPSECRET = self.config.get(
                'wxpay', 'WX_APPSECRECT')
            WxPaySDK.WxPayConf_pub.MCHID = self.config.get('wxpay', 'WX_MCHID')
            WxPaySDK.WxPayConf_pub.KEY = self.config.get('wxpay', 'WX_KEY')
            WxPaySDK.WxPayConf_pub.NOTIFY_URL = self.config.get(
                'wxpay', 'WX_NOTIFY_URL')
            WxPaySDK.WxPayConf_pub.NOTIFY_URL_RELEASE = self.config.get(
                'wxpay', 'WX_NOTIFY_URL_RELEASE')
            WxPaySDK.WxPayConf_pub.JS_API_CALL_URL = self.config.get(
                'wxpay', 'WX_JS_API_CALL_URL')
            WxPaySDK.WxPayConf_pub.SSLCERT_PATH = self.config.get(
                'wxpay', 'WX_SSLCERT_PATH')
            WxPaySDK.WxPayConf_pub.SSLKEY_PATH = self.config.get(
                'wxpay', 'WX_SSLKEY_PATH')
        except Exception, e:
            log.err("Not WeixinPay Config")
Exemplo n.º 19
0
def getIFCCount(userId=None, backupUser=None, keys=None):
    '''
    # 粉丝数:Followee (backup)followee, 照片数(认领的照片):Face assign.user,贡献者个数:Face assign.assigner uploader
    :param userId: 注册用户Id
    :param backupUser: 非注册用户Id
    :param keys: 查询某一个Count
    :return: 
    '''
    uid = userId or backupUser
    isUser = bool(userId)
    condition = {
        'imageCount': {'classname': 'Face', 'key': 'imageCount', 'condition': {'assign.status': 1, 'assign.user': uid},
                       'method': 1},
        'fansCount': {'classname': 'Followee', 'key': 'fansCount', 'condition': {'followee': uid, 'effect': 1},
                      'method': 1},
        'contributeCount': {'classname': 'Face', 'distinct': 'assign.assigner', 'key': 'contributeCount',
                            'condition': {'assign.status': 1, 'assign.user': uid}, 'method': 2}
    }
    where = []
    if not keys:
        if isUser:
            keys = {'imageCount': 1, 'fansCount': 1, 'contributeCount': 1}
        else:
            keys = {'fansCount': 1}
    for key in keys:
        where.append(condition[key])

    result = {}
    for item in where:  # 获取三种个数
        className = item['classname']
        query = item["condition"]
        try:
            if item['method'] == 1:
                classHelper = ClassHelper(className)
                result[item['key']] = classHelper.query_count(query)
            elif item['method'] == 2:
                classHelper = ClassHelper(className)
                obj = classHelper.distinct(query, item['distinct'])
                result[item['key']] = len(obj)
        except Exception, e:
            log.err("%s param error", item['key'])
Exemplo n.º 20
0
 def sentMessage(self, obj):
     item = self.autoMessage.get((self.className, self.method), None)
     if not item:
         return
     userClassHelper = ClassHelper("UserInfo")
     userInfo = userClassHelper.find_one({"user": self.userId},
                                         {'nickName': 1})
     if not userInfo:
         return
     obj.update(userInfo)
     title = item['title'].format(**obj)
     template = item['template'].format(**obj)
     # TODO
     pushData = {"userid": obj['to'], "title": title, "text": template}
     log.info("Push Data:%s", json.dumps(pushData))
     try:
         res = requests.post(self.pushUrl,
                             data=json.dumps(pushData),
                             headers={'X-MeCloud-Debug': '1'})
         print res.text
     except Exception, ex:
         log.err("Push Err:%s", ex)
Exemplo n.º 21
0
 def put(self, className, objectId=None):
     try:
         if not objectId and not self.request.arguments.has_key('where'):
             self.write(ERR_OBJECTID_MIS.message)
             return
         try:
             if objectId:
                 try:
                     ObjectId(objectId)
                 except Exception:
                     self.write(ERR_OBJECTID_MIS.message)
                     return
             obj = json.loads(self.request.body)
         except Exception, e:
             log.err("JSON Error:[%d/%s] , error:%s", len(self.request.body), self.request.body, str(e))
             self.write(ERR_INVALID.message)
             return
         if self.request.arguments.has_key('where'):
             classHelper = ClassHelper(className)
             query = eval(self.get_argument('where'))
             if "$set" in obj:
                 obj['$set'] = self.check_field(className, obj['$set'])
             else:
                 obj = self.check_field(className, obj)
             if not obj:
                 return
             returnObj = classHelper.updateOneCreate(query, obj)
             data = copy.deepcopy(ERR_SUCCESS)
             data.message['data'] = self.filter_field(returnObj)
             self.write(json.dumps(data.message, cls=MeEncoder))
         elif type(obj) == list:
             objectIdError = False
             for index in range(len(obj) - 1):
                 try:
                     for key, value in obj[index].items():
                         if value.has_key('_sid'):
                             ObjectId(value['_sid'])
                         value = self.sentiveCheck(key, value)
                         meobj = MeObject(key, value)
                         meobj.save()
                 except bson.errors.InvalidId:
                     objectIdError = True
                     break
                 except Exception, e:
                     log.err("Error:%s , error:%s", self.request.body, str(e))
             if objectIdError:
                 self.write(ERR_OBJECTID_MIS.message)
                 return
             mainObj = obj[len(obj) - 1]
             mainObj = self.sentiveCheck(className, mainObj)
             classHelper = ClassHelper(className)
             # 只返回了更新时间
             try:
                 data = classHelper.update(objectId, mainObj)
                 # 默认返回整个对象
                 self.write(json.dumps(data, cls=MeEncoder))
             except Exception, e:
                 log.err("ClassV2Handler-->put error, %s", e)
                 self.write(ERR_DB_OPERATION.message)
Exemplo n.º 22
0
    def modifyPwd(self):
        obj = self.jsonBody
        print 'newPwd:', obj['newPwd']
        if 'newPwd' not in obj:
            self.write(ERR_PARA.message)
        else:
            user = self.user
            if user == None:
                self.write(ERR_OBJECTID_MIS.message)
                return
            # if str(user['password']) == str(obj['oldPwd']):
            updateObj = {'$set': {'password': obj['newPwd']}}

            try:
                userQuery = MeQuery("User")
                userQuery.update_core(user['_id'], updateObj)
                self.set_secure_cookie("u", user['_id'])
                self.write(ERR_SUCCESS.message)
                # else:
                #     self.write(ERR_PASSWD_INVALID.message)
            except Exception, e:
                log.err("UserHandler-->update_core in modifyPwd() error, %s",
                        e)
                self.write(e.message)
Exemplo n.º 23
0
    def initAlipay(self):
        ##>> 阿里支付相关
        # """
        # 注意,这里面的数据为了安全性,其实我都篡改了一些字母,是错的,但是大家配置的适合按照这个格式来配置,尤其是RSA_ALIPAY_PUBLIC
        # """

        # RSA_ALIPAY_PUBLIC = """-----BEGIN PUBLIC KEY-----
        # MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB
        # -----END PUBLIC KEY-----"""
        # '''
        # MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB
        # '''
        # #商户私钥
        # RSA_PRIVATE ="""-----BEGIN RSA PRIVATE KEY-----
        # MIICXQIBAAKBgQDOnWu84FGGyyXE8wlGFQ20NYBeVzgmtfTHYhulQOfCvKUDZF4NNXxTmsGF9wsGQ6CP3bV5L8cVTsAWhqMvCIn4+TPCnfO2vxbkPTt0c1RLMvxX3Mahr0dz6Giz7S3mpWy0vhHFgWORyD25mCnHo7wN3hZRdGoPGYYnQBFqY5icPwIDAQABAoGAG2fsI4iJp9yIbQBjyYT/ZVj3ZwwgqZnXFx9fVWMvmrgVF0cX5p6imCBd7RwgvTr5MDwTVzjMKnpgplxDhviV/FBSvlNXITxIVAi8SKlsouwicPH6AJ6Am+tRhqRqzuEVws98LbDHH0k/qmHagnWR2eY6E2TEqWbFLZxXFN2eaHECQQDx4Bk5U4pIUnJQF3W9BaENCBTsVOfMkLNsjsa7AqlmW9/Gdxk1kVKebv39BIKP9ERyanxeHDHW+eWrCkB0tf3HAkEA2q4yvZtqWoJaKLxpRGPMfhWQ4N4FnQ9wl0FStVJHpR34Hz4rKebM3GM5uIJoYl7gLq7gdYLWiGnKJrieB6TNyQJBANk8icsYAfG0wuC2QVPUs3IN2STtmQb8y3lrvoeF+3loeNI6c5TOAaM0UsAlhdIe9D7C7xJjRkwrQ6Bb48ovDk8CQQCna9y/G4C2YLwkGfPB/2ItWdd8wZ6sm4iI1OM8nQzrFmHDkbY8M06+oF0trPG79oVOWGbSsOQMtmmlcYzTr1I5AkBt5LSdGbvyD6ymk8xXb4/qGY2Jz/h+CBQHMziqqXVvbcFJfsvErQHu2P3Vsmse0pPIfqzecwrDCfk5O9EvqXPi
        # -----END RSA PRIVATE KEY-----"""
        # RSA_PUBLIC = """-----BEGIN PUBLIC KEY-----
        # MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOnWu84FGGyyXE8wlGFQ20NYBeVzgmtfTHYhulQOfCvKUDZF4NNXxTmsGF9wsGQ6CP3bV5L8cVTsAWhqMvCIn4+TPCnfO2vxbkPTt0c1RLMvxX3Mahr0dz6Giz7S3mpWy0vhHFgWORyD25mCnHo7wN3hZRdGoPGYYnQBFqY5icPwIDAQAB
        # -----END PUBLIC KEY-----"""
        # """
        # MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOnWu84FGGyyXE8wlGFQ20NYBeVzgmtfTHYhulQOfCvKUDZF4NNXxTmsGF9wsGQ6CP3bV5L8cVTsAWhqMvCIn4+TPCnfO2vxbkPTt0c1RLMvxX3Mahr0dz6Giz7S3mpWy0vhHFgWORyD25mCnHo7wN3hZRdGoPGYYnQBFqY5icPwIDAQAB
        # """
        # partner_id = 2088221500684729  # 支付宝后台的合作商ID
        # # key = "x6lmikee5cfkpv0sicx3i24qpa3yggdk"
        # appid = 2017062307555172  # your appid
        # #AES UVII/HdiItvKU3HuBFRiBQ==
        try:
            alipay_config.RSA_ALIPAY_PUBLIC = self.config.get(
                'alipay', 'RSA_ALIPAY_PUBLIC')
            alipay_config.RSA_PRIVATE = self.config.get(
                'alipay', 'RSA_PRIVATE')
            alipay_config.RSA_PUBLIC = self.config.get('alipay', 'RSA_PUBLIC')
            alipay_config.partner_id = self.config.get('alipay', 'partner_id')
            alipay_config.appid = self.config.get('alipay', 'appid')
        except Exception, e:
            log.err("Not AliPay Config")
Exemplo n.º 24
0
 def hgetall(key, dbid=0):
     try:
         return RedisDb.get_connection(dbid).hgetall(key)
     except Exception, e:
         log.err("redis hgetall operation fail , error:%s", str(e))
         return {}
Exemplo n.º 25
0
                        self.write(ERR_BLACK_PERMISSION.message)
                except bson.errors.InvalidId:
                    self.write(ERR_OBJECTID_MIS.message)
            else:
                try:
                    obj = self.sentiveCheck(className, obj)
                    obj = self.blacklistCheck(className, obj)
                    if obj:
                        meobj = MeObject(className, obj)
                        meobj.save()
                        self.filter_field(meobj)
                        self.write(json.dumps(meobj, cls=MeEncoder))
                    else:
                        self.write(ERR_BLACK_PERMISSION.message)
                except Exception,e:
                    log.err(json.dumps(e.message))
                    if e.message["errCode"] == 137:
                        field = re.search(r"index: ([0-9a-zA-Z]+)_-?\d{1} dup key",e.message['info'])
                        if field:
                            field = field.group(1)
                            classHelper = ClassHelper(className)
                            item = classHelper.find_one({field:obj[field]})
                            item = self.filter_field(item)
                            e.message['data'] = item
                    self.write(e.message)
        except Exception, e:
            log.err("ClassHandler-->put error, %s", e)
            self.write(ERR_DB_OPERATION.message)


    ### 更新对象
Exemplo n.º 26
0
    def post(self, action=None, blackee=None, isuser=1):
        userId = self.get_current_user()
        if not userId:
            log.err("black error,user not exist!")
            self.write(ERR_USER_NOTFOUND.message)
            return

        if not blackee:
            log.err("request param error")
            self.write(ERR_NOPARA.message)
            return

        is_user = True
        if int(isuser) == 0:
            is_user = False

        # 查找用户是否存在
        if is_user == True:
            userHelper = ClassHelper("User")
        else:
            userHelper = ClassHelper("BackupUser")
        findUser = userHelper.find_one({'_sid': blackee})
        if not findUser:
            log.err("%s error,blackee not exist!", action)
            self.write(ERR_USER_NOTFOUND.message)
            return

        blackHelper = ClassHelper("Blacklist")
        followHelper = ClassHelper("Followee")

        try:
            if action == 'block':  # 拉黑
                # 判断是否已经拉黑过
                blacked = blackHelper.find_one({
                    'user': userId,
                    'blacker': blackee
                })
                if blacked:
                    self.write(ERR_SUCCESS.message)
                    return
                blackHelper.create({'user': userId, 'blacker': blackee})

                if is_user:
                    fieldname = "followee"
                else:
                    fieldname = "backupFollowee"
                unfollowed = followHelper.find_one({
                    'user': userId,
                    fieldname: blackee,
                    'effect': {
                        '$gte': 1
                    }
                })
                if unfollowed:
                    FollowHelper.unfollow(userId, blackee, is_user)
                br = blackHelper.find_one({'user': userId, 'blacker': blackee})
                successInfo = deepcopy(ERR_SUCCESS)
                successInfo.message["data"] = br
                self.write(json.dumps(successInfo.message, cls=MeEncoder))
            elif action == 'unblock':  # 取消拉黑
                unblacked = blackHelper.find_one({
                    'user': userId,
                    'blacker': blackee
                })
                if not unblacked:
                    self.write(ERR_SUCCESS.message)
                    return
                blackHelper.delete(unblacked['_id'])
                self.write(ERR_SUCCESS.message)
            else:
                print "action error: " + action
                self.write(ERR_PATH_PERMISSION.message)
                return
        except Exception, e:
            log.err("BlacklistHandler-->action:%s in post() error, %s", action,
                    e)
            self.write(ERR_DB_OPERATION.message)
Exemplo n.º 27
0
 def hget(key, field, dbid=0):
     try:
         return RedisDb.get_connection(dbid).hget(key, field)
     except Exception, e:
         log.err("redis hget operation fail , error:%s", str(e))
         return None
Exemplo n.º 28
0
 def zadd(key, score, member, dbid=0):
     try:
         return RedisDb.get_connection(dbid).zadd(key, member, score)
     except Exception, e:
         log.err("redis zadd operation fail , error:%s", str(e))
         return None
Exemplo n.º 29
0
 def incrby(key, amount=1, dbid=0):
     try:
         return RedisDb.get_connection(dbid).incr(key, amount)
     except Exception, e:
         log.err("redis incrby operation fail , error:%s", str(e))
         return None
Exemplo n.º 30
0
 def expire(key, expireSeconds, dbid=0):
     try:
         return RedisDb.get_connection(dbid).expire(key, expireSeconds)
     except Exception, e:
         log.err("redis expire operation fail , error:%s", str(e))
         return False