Example #1
0
    def GET(self, cid, goodsid=None, range=None):
        ''' /bfdrest/client/(cid)/goods/(goodsid)/(items) '''
        myuuid = uuid.uuid1()
        LOG("info", _myuuid=myuuid)
        if goodsid == None:
            if cid in goods_fields_conf:
                return pub.callback(json.dumps(goods_fields_conf[cid]), myuuid)
            return pub.callback(json.dumps(goods_fields), myuuid)
        elif goodsid == "type":
            return pub.callback(json.dumps(type_define), myuuid)
        else:
            gv = cache.get('%s:Goods:%s' % (cid, goodsid))
            if gv:
                ret = json.loads(gv)
                ret['success'] = True
                if range == None:
                    if 'keys' in ret:
                        del ret['keys']
                        pass
                    return pub.callback(json.dumps(ret), myuuid)
                else:
                    iids = []
                    # 获取范围的item
                    for key in [goodsid]:
                        ids_str = cache.get('%s:GoodsItems:%s' % (cid, key))
                        if ids_str:
                            iids.extend(json.loads(ids_str))
                    return pub.callback(json.dumps(iids), myuuid)

            else:
                ret = {}
                ret['success'] = False
                ret['error_info'] = 'no such goods id.'
                return pub.callback(json.dumps(ret), myuuid)
Example #2
0
def rm_goods_solr(cid, gsid, items=[]):
    ret = cache.get("%s:GoodsItems:%s" % (cid, gsid))
    j = []
    if ret:
        j = json.loads(ret)
    new_items = set()
    for item in items:
        new_items.add(item['iid'])
    for iid in j:
        if iid in new_items:
            continue
        cache_key = "%s:ItemBase:%s" % (cid, iid)
        cache_str = cache.get(cache_key, 'ns1', 'item')
        if cache_str:
            ib = ItemProfile_pb2.ItemBase()
            ib.ParseFromString(cache_str)
            gsids = ib.goods
            gsid_set = set()
            for old_gsid in gsids:
                if old_gsid != gsid:
                    gsid_set.add(old_gsid)
            if len(gsid_set) == 0 and not ib.is_verified:
                del_url = '%s&cid=%s&iid=%s' % (delete_item_url, cid, iid)
                print "delete item, id: %s" % del_url
                urllib.urlopen(del_url)
            else:
                update_url = '%s&cid=%s&iid=%s&gsid=%s' % (
                    update_item_url, cid, iid, '|'.join(gsid_set))
                print "update item goods id: %s" % update_url
                urllib.urlopen(update_url)
Example #3
0
 def DELETE(self,cid,rid):
     ''' '/bfdrest/client/(cid)/operationrules/(rid)' '''
     myuuid = uuid.uuid1();LOG("info",_myuuid=myuuid)
     data = web.input()
     jdata = data
     rstr = cache.delete('%s:OperationRule:%s'%(cid,rid))
     rstr = cache.delete('%s:OperatorRules:%s'%(cid,rid))
     rlist = cache.get('%s:OperatorRules:_all_'%cid)
     if rlist:
         rlist = json.loads(rlist)
     else:
         rlist = {}
     if rid in rlist:
         del rlist[rid]
     cache.delete('%s:OperatorRulesItems:%s'%(cid,rid))
     rstr = cache.set('%s:OperatorRules:_all_'%(cid),json.dumps(rlist))
     for p_bid in json.loads(jdata["banner_id"]):
         p_bid_str = cache.get("%s:RecBanner:%s"%(cid,p_bid))
         p_banner = RecBanner_pb2.RecBanner()
         if p_bid_str:
             p_banner.ParseFromString(p_bid_str)
             for i in xrange(len(p_banner.logic_rule.operation_rules)):
                 if p_banner.logic_rule.operation_rules[i].operation_rule == rid:
                     del p_banner.logic_rule.operation_rules[i]
                     break
         cache.set("%s:RecBanner:%s"%(cid,p_bid),p_banner.SerializeToString())
     ret = {}
     if rstr:
         ret["success"] = True
     else:
         ret["success"] = False
         ret["error_info"] = "can't delete operation rule."
     return pub.callback(json.dumps(ret),myuuid)
Example #4
0
 def DELETE(self, cid, goodsid):
     ''' /bfdrest/client/(cid)/goods/(goodsid) '''
     myuuid = uuid.uuid1()
     LOG("info", _myuuid=myuuid)
     data = web.input()
     jdata = data
     ret = {}
     g_str = cache.get('%s:Goods:%s' % (cid, goodsid))
     pgs = RecBanner_pb2.Goods()
     if g_str:
         pgs.ParseFromString(g_str)
         if not pgs.is_ranges:
             rm_goods_solr(cid, goodsid)
     cache.delete('%s:Goods:%s' % (cid, goodsid))
     remove_goods_relation(cid, goodsid, jdata)
     goods_list = cache.get('%s:Goods:_all_' % cid)
     if goods_list:
         goods_list = json.loads(goods_list)
     else:
         goods_list = {}
     if goodsid in goods_list:
         del goods_list[goodsid]
         cache.set('%s:Goods:_all_' % cid, json.dumps(goods_list))
     ret['success'] = True
     return pub.callback(json.dumps(ret), myuuid)
Example #5
0
def ParseFromJson(cid, bid, json_banner):
    rb = RecBanner_pb2.RecBanner()
    lr = RecBanner_pb2.RecBanner.LogicRule()
    opr = RecBanner_pb2.RecBanner.LogicRule.OperationRule()
    pr = RecBanner_pb2.RecBanner.LogicRule.PositionRule()
    uopr = RecBanner_pb2.OperationRule()
    gd = RecBanner_pb2.Goods()

    bstr = cache.get('%s:RecBanner:%s' % (cid, bid))
    if bstr:
        try:
            rb.ParseFromString(bstr)
        except:
            print "parse from str failed"

    rb.banner_id = bid
    rb.name = json_banner["name"]
    rb.description = json_banner["description"]
    if "is_active" in json_banner:
        rb.is_active = json_banner["is_active"]
    else:
        rb.is_active = True
    rb.update_time = int(time.time())

    if "operation_rules" in json_banner:
        for r_num in json_banner["operation_rules"]:
            opr.Clear()
            opr.operation_rule = r_num[0]
            if r_num[1]:
                opr.rec_num = r_num[1]
            else:
                opr.rec_num = -1
            opstr = cache.get('%s:OperationRule:%s' % (cid, r_num[0]))
            uopr.Clear()
            if opstr:
                try:
                    uopr.ParseFromString(opstr)
                    opr.user_level = uopr.user_level
                except:
                    pass
            lr.operation_rules.add()
            lr.operation_rules[len(lr.operation_rules) - 1].CopyFrom(opr)
    if "position_rules" in json_banner:
        for position in sorted(json_banner["position_rules"]):
            pr.Clear()
            pr.position = int(position)
            goodsid = json_banner["position_rules"][position]
            pr.goods_id.append(goodsid)
            goods_data = cache.get('%s:Goods:%s' % (cid, goodsid))
            if goods_data:
                try:
                    gd.ParseFromString(goods_data)
                    pr.user_level = gd.user_level
                except Exception, e:
                    #        logging.error('except: %s', e)
                    pass
            lr.position_rules.add()
            lr.position_rules[len(lr.position_rules) - 1].CopyFrom(pr)
Example #6
0
File: cache.py Project: emeitu/test
def get(key, pattern=None):
    if key.encode('utf8') == 'keys':
        if pattern:
            r = re.compile(pattern)
            keys = json.loads(cache.get('keys'))
            ret = {}
            for k in keys:
                if r.match(k):
                    ret[k] = keys[k]
            return json.dumps(sorted(ret.keys()))
        else:
            pass

    return cache.get(key)
Example #7
0
File: cache.py Project: emeitu/test
def get(key,pattern = None):
    if key.encode('utf8') == 'keys':
        if pattern:
            r = re.compile(pattern)
            keys = json.loads(cache.get('keys'))
            ret = {}
            for k in keys:
                if r.match(k):
                    ret[k] = keys[k]
            return json.dumps(sorted(ret.keys()))
        else:
            pass
            
    return cache.get(key)
Example #8
0
 def POST(self, cid, rid):
     ''' '/bfdrest/client/(cid)/operationrules/(rid)' '''
     myuuid = uuid.uuid1()
     LOG("info", _myuuid=myuuid)
     data = web.data()
     rv = json.loads(data)
     range_iids = {}
     #range_iids = goods.generalize_ranges(cid,rv["rec_ranges"])
     riids = []
     for key in range_iids:
         riids.extend(range_iids[key])
     operation_rule = ParseFromJson(rv)
     operation_rule.operation_rule_id = rid
     rlist = cache.get('%s:OperatorRules:_all_' % cid)
     if rlist:
         rlist = json.loads(rlist)
     else:
         rlist = {}
     rlist[rid] = time.time()
     cache.set('%s:OperatorRules:_all_' % (cid), json.dumps(rlist))
     cache.set('%s:OperationRule:%s' % (cid, rid),
               operation_rule.SerializeToString())
     rstr = cache.set('%s:OperatorRules:%s' % (cid, rid), data)
     ret = {}
     if rstr:
         ret["success"] = True
     else:
         ret["success"] = False
         ret["error_info"] = "can't save operation rule."
     return pub.callback(json.dumps(ret), myuuid)
Example #9
0
 def POST(self, cid, abid, method=None):
     ''' '/bfdrest/client/(cid)/ABtest/(abid)' '''
     myuuid = uuid.uuid1()
     LOG("info", _myuuid=myuuid)
     stop = False
     if method == "stop":
         stop = True
     data = web.data()
     ret = {}
     rv = json.loads(data)
     if not SetBannerABtest(cid, abid, rv, stop):
         ret["success"] = False
         ret["error_info"] = "can't save banner abtest."
         return pub.callback(json.dumps(ret), myuuid)
     rlist = cache.get('%s:ABtest:_all_' % cid)
     if rlist:
         rlist = json.loads(rlist)
     else:
         rlist = {}
     rlist[abid] = time.time()
     rstr = cache.set('%s:ABtest:_all_' % (cid), json.dumps(rlist))
     rstr = cache.set('%s:ABtest:%s' % (cid, abid), data)
     if rstr:
         ret["success"] = True
     else:
         ret["success"] = False
         ret["error_info"] = "can't save abtest rule."
     return pub.callback(json.dumps(ret), myuuid)
Example #10
0
    def POST(self,cid,rid):
        ''' '/bfdrest/client/(cid)/operationrules/(rid)' '''
        myuuid = uuid.uuid1();LOG("info",_myuuid=myuuid)
        data = web.data()
        rv = json.loads(data)
        range_iids = {}
#range_iids = goods.generalize_ranges(cid,rv["rec_ranges"])
        riids = []
        for key in range_iids:
            riids.extend(range_iids[key])
        operation_rule = ParseFromJson(rv)
        operation_rule.operation_rule_id = rid
        rlist = cache.get('%s:OperatorRules:_all_'%cid)
        if rlist:
            rlist = json.loads(rlist)
        else:
            rlist = {}
        rlist[rid] = time.time()
        cache.set('%s:OperatorRules:_all_'%(cid),json.dumps(rlist))
        cache.set('%s:OperationRule:%s'%(cid,rid),operation_rule.SerializeToString())
        rstr = cache.set('%s:OperatorRules:%s'%(cid,rid),data)
        ret = {}
        if rstr:
            ret["success"] = True
        else:
            ret["success"] = False
            ret["error_info"] = "can't save operation rule."
        return pub.callback(json.dumps(ret),myuuid)
Example #11
0
 def DELETE(self,cid,abid):
     ''' '/bfdrest/client/(cid)/ABtest/(abid)' '''
     myuuid = uuid.uuid1();LOG("info",_myuuid=myuuid)
     data = web.input()
     rv = data
     ret = {}
     if not SetBannerABtest(cid,abid,rv,False,True):
         ret["success"] = False
         ret["error_info"] = "can't delete banner abtest."
         return pub.callback(json.dumps(ret),myuuid)
     rlist = cache.get('%s:ABtest:_all_'%cid)
     if rlist:
         rlist = json.loads(rlist)
     else:
         rlist = {}
     if abid in rlist:
         del rlist[abid]
     rstr = cache.set('%s:ABtest:_all_'%(cid),json.dumps(rlist))
     rstr = cache.delete('%s:ABtest:%s'%(cid,abid))
     rstr = cache.delete('%s:ABtestRule:%s'%(cid,abid))
     if rstr:
         ret["success"] = True
     else:
         ret["success"] = True
         ret["error_info"] = "can't delete abtest rule."
     return pub.callback(json.dumps(ret),myuuid)
Example #12
0
 def POST(self,cid,abid,method=None):
     ''' '/bfdrest/client/(cid)/ABtest/(abid)' '''
     myuuid = uuid.uuid1();LOG("info",_myuuid=myuuid)
     stop = False
     if method == "stop":
         stop = True
     data = web.data()
     ret = {}
     rv = json.loads(data)
     if not SetBannerABtest(cid,abid,rv,stop):
         ret["success"] = False
         ret["error_info"] = "can't save banner abtest."
         return pub.callback(json.dumps(ret),myuuid)
     rlist = cache.get('%s:ABtest:_all_'%cid)
     if rlist:
         rlist = json.loads(rlist)
     else:
         rlist = {}
     rlist[abid] = time.time()
     rstr = cache.set('%s:ABtest:_all_'%(cid),json.dumps(rlist))
     rstr = cache.set('%s:ABtest:%s'%(cid,abid),data)
     if rstr:
         ret["success"] = True
     else:
         ret["success"] = False
         ret["error_info"] = "can't save abtest rule."
     return pub.callback(json.dumps(ret),myuuid)
Example #13
0
 def DELETE(self, cid, abid):
     ''' '/bfdrest/client/(cid)/ABtest/(abid)' '''
     myuuid = uuid.uuid1()
     LOG("info", _myuuid=myuuid)
     data = web.input()
     rv = data
     ret = {}
     if not SetBannerABtest(cid, abid, rv, False, True):
         ret["success"] = False
         ret["error_info"] = "can't delete banner abtest."
         return pub.callback(json.dumps(ret), myuuid)
     rlist = cache.get('%s:ABtest:_all_' % cid)
     if rlist:
         rlist = json.loads(rlist)
     else:
         rlist = {}
     if abid in rlist:
         del rlist[abid]
     rstr = cache.set('%s:ABtest:_all_' % (cid), json.dumps(rlist))
     rstr = cache.delete('%s:ABtest:%s' % (cid, abid))
     rstr = cache.delete('%s:ABtestRule:%s' % (cid, abid))
     if rstr:
         ret["success"] = True
     else:
         ret["success"] = True
         ret["error_info"] = "can't delete abtest rule."
     return pub.callback(json.dumps(ret), myuuid)
Example #14
0
File: brand.py Project: emeitu/test
    def POST(self, cid):
        ''' /bfdrest/client/(cid)/brand '''
        value = web.data()
        value_error = '{"stat":false,"info":"Wrong json data","format":{"brand":["brand1","brand2"],"category":["cate1","cate2"]}}'
        try:
            v = json.loads(value)
        except:
            return "json error:" + value_error + value
        if 'brand' not in v or 'category' not in v:
            return value_error

        if len(v['category']) > 0 and v['category'][0] == '_all_':
            v['category'] = v['category'][1:]
        cates = v['category']
        brands = v['brand']
        # 更新_all_的子品牌和子类目
        cate = "_all_"
        catestr = cache.get(u'%s:category:%s' % (cid, cate))
        if catestr:
            cateobj = json.loads(catestr)
        else:
            cateobj = {'brand': [], 'category': []}
        for brand in brands:
            if brand not in cateobj['brand']:
                cateobj['brand'].append(brand)
        if len(cates) > 0 and cates[0] not in cateobj['category']:
            cateobj['category'].append(cates[0])
        cache.set('%s:category:%s' % (cid, cate.decode('utf8')),
                  json.dumps(cateobj))
        # 更新各级类目的子品牌和子类目
        for i in range(len(cates)):
            cate = cate + ':' + cates[i]
            catestr = cache.get(u'%s:category:%s' % (cid, cate))
            if catestr:
                cateobj = json.loads(catestr)
            else:
                cateobj = {'brand': [], 'category': []}
            for brand in brands:
                if brand not in cateobj['brand']:
                    cateobj['brand'].append(brand)
            if len(cates) > i + 1 and cates[i + 1] not in cateobj['category']:
                cateobj['category'].append(cates[i + 1])
            cache.set('%s:category:%s' % (cid, cate), json.dumps(cateobj))

        ret = json.loads(cache.get('%s:category:%s' % (cid, cate)))
        ret['category'] = cates
        return json.dumps(ret)
Example #15
0
 def GET(self,cid,colid):
     ''' /bfdrest/(cid)/collocations/(colid) '''
     ret = get_data_ret
     if cache.get('%s:goods:%s' % (cid,goodsid)):
         ret["stat"]=True
     else:
         pass
     return json.dumps(ret)
Example #16
0
File: cache.py Project: emeitu/test
def delete(key, pattern=None):
    if key == 'keys' and not pattern:
        return False
    if key == 'keys' and pattern:
        r = re.compile(pattern)
        keys = json.loads(cache.get('keys'))
        klist = sorted(keys)
        for k in klist:
            if r.match(k):
                cache.delete(k)
                del keys[k]
        return cache.set('keys', json.dumps(keys))

    keys = json.loads(cache.get('keys'))
    if cache.delete(key):
        del keys[key]
        return cache.set('keys', json.dumps(keys))
    else:
        return False
Example #17
0
File: cache.py Project: emeitu/test
def delete(key,pattern=None):
    if key == 'keys' and not pattern:
        return False
    if key == 'keys' and pattern:
        r = re.compile(pattern)
        keys = json.loads(cache.get('keys'))
        klist = sorted(keys)
        for k in klist:
            if r.match(k):
                cache.delete(k)
                del keys[k]
        return cache.set('keys',json.dumps(keys))
        
    keys = json.loads(cache.get('keys'))
    if cache.delete(key):
        del keys[key]
        return cache.set('keys',json.dumps(keys))
    else:
        return False
Example #18
0
File: brand.py Project: emeitu/test
 def getbrd(brd):
     ret = []
     brdstr = cache.get('%s:brand:%s' % (cid, brd))
     try:
         brd = json.loads(brdstr)
         for c in brd:
             ret.append({c: getbrd('%s:%s' % (brd, c))})
         return ret
     except:
         return []
Example #19
0
File: cache.py Project: emeitu/test
def set(key, value):
    if key == 'keys':
        return False
    now = time.ctime()
    keystr = cache.get('keys')
    if keystr:
        keys = json.loads(keystr)
        keys[key] = now
    else:
        keys = {key: now}
    if cache.set(key, value):
        return cache.set('keys', json.dumps(keys))
    else:
        return False
Example #20
0
File: cache.py Project: emeitu/test
def set(key,value):
    if key == 'keys':
        return False
    now = time.ctime()
    keystr = cache.get('keys')
    if keystr:
        keys = json.loads(keystr)
        keys[key] = now
    else:
       keys = {key:now} 
    if cache.set(key,value):
        return cache.set('keys',json.dumps(keys))
    else:
        return False
Example #21
0
 def DELETE(self, cid, rid):
     ''' '/bfdrest/client/(cid)/operationrules/(rid)' '''
     myuuid = uuid.uuid1()
     LOG("info", _myuuid=myuuid)
     data = web.input()
     jdata = data
     rstr = cache.delete('%s:OperationRule:%s' % (cid, rid))
     rstr = cache.delete('%s:OperatorRules:%s' % (cid, rid))
     rlist = cache.get('%s:OperatorRules:_all_' % cid)
     if rlist:
         rlist = json.loads(rlist)
     else:
         rlist = {}
     if rid in rlist:
         del rlist[rid]
     cache.delete('%s:OperatorRulesItems:%s' % (cid, rid))
     rstr = cache.set('%s:OperatorRules:_all_' % (cid), json.dumps(rlist))
     for p_bid in json.loads(jdata["banner_id"]):
         p_bid_str = cache.get("%s:RecBanner:%s" % (cid, p_bid))
         p_banner = RecBanner_pb2.RecBanner()
         if p_bid_str:
             p_banner.ParseFromString(p_bid_str)
             for i in xrange(len(p_banner.logic_rule.operation_rules)):
                 if p_banner.logic_rule.operation_rules[
                         i].operation_rule == rid:
                     del p_banner.logic_rule.operation_rules[i]
                     break
         cache.set("%s:RecBanner:%s" % (cid, p_bid),
                   p_banner.SerializeToString())
     ret = {}
     if rstr:
         ret["success"] = True
     else:
         ret["success"] = False
         ret["error_info"] = "can't delete operation rule."
     return pub.callback(json.dumps(ret), myuuid)
Example #22
0
 def GET(self,cid,rid=None):
     ''' '/bfdrest/client/(cid)/operationrules','/bfdrest/client/(cid)/operationrules/(rid)' '''
     myuuid = uuid.uuid1();LOG("info",_myuuid=myuuid)
     if rid == None:
         return pub.callback(json.dumps(GET_ret),myuuid)
     else:
         rstr = cache.get('%s:OperatorRules:%s'%(cid,rid))
         ret = {}
         if rstr:
             ret = json.loads(rstr)
             ret["success"] = True
         else:
             ret["success"] = False
             ret["error_info"] = "no such operation rule."
         return pub.callback(json.dumps(ret),myuuid)
Example #23
0
 def GET(self, cid, bid=None):
     ''' '/bfdrest/client/(cid)/banners','/bfdrest/client/(cid)/banners/(bid)' '''
     myuuid = uuid.uuid1()
     LOG("info", _myuuid=myuuid)
     if bid == None:
         return pub.callback(json.dumps(GET_ret), myuuid)
     else:
         rstr = cache.get('%s:Banners:%s' % (cid, bid))
         ret = {}
         if rstr:
             ret = json.loads(rstr)
             ret["success"] = True
         else:
             ret["success"] = False
             ret["error_info"] = "no such banner id."
         return pub.callback(json.dumps(ret), myuuid)
Example #24
0
 def GET(self, cid, rid=None):
     ''' '/bfdrest/client/(cid)/operationrules','/bfdrest/client/(cid)/operationrules/(rid)' '''
     myuuid = uuid.uuid1()
     LOG("info", _myuuid=myuuid)
     if rid == None:
         return pub.callback(json.dumps(GET_ret), myuuid)
     else:
         rstr = cache.get('%s:OperatorRules:%s' % (cid, rid))
         ret = {}
         if rstr:
             ret = json.loads(rstr)
             ret["success"] = True
         else:
             ret["success"] = False
             ret["error_info"] = "no such operation rule."
         return pub.callback(json.dumps(ret), myuuid)
Example #25
0
 def GET(self,cid,abid=None):
     ''' '/bfdrest/client/(cid)/ABtest','/bfdrest/client/(cid)/ABtest/(ABid)' '''
     myuuid = uuid.uuid1();LOG("info",_myuuid=myuuid)
     if abid == None:
         return pub.callback(json.dumps(GET_ret),myuuid)
     else:
         rstr = cache.get('%s:ABtest:%s'%(cid,abid))
         if abid == "_all_":
             return rstr
         ret = {}
         if rstr:
             ret = json.loads(rstr)
             ret["success"] = True
         else:
             ret["success"] = False
             ret["error_info"] = "no such ABtest id."
         return pub.callback(json.dumps(ret),myuuid)
Example #26
0
    def GET(self,n,b,k,proto=None):
        ''' /bfdrest/bfdcache/namesapce/business/key for get key;
        '''
        myuuid = uuid.uuid1();LOG("info",_myuuid=myuuid)
        v = cache.get(k,n,b)
#        print '%s\t%s\t%s' % (n,b,k)
        if proto:
            if proto == 'DELETE':
                return pub.callback(json.dumps(cache.delete(k,n,b)),myuuid)
            if v == None or v == 'None':
                return pub.callback(json.dumps({}),myuuid)
            ib = eval("%s()"%proto)
            try:
                ib.ParseFromString(v)
            except Exception,e:
                return pub.callback(str(e),myuuid)
            return pub.callback(json.dumps(proto2json(ib)),myuuid)
Example #27
0
 def GET(self, cid, abid=None):
     ''' '/bfdrest/client/(cid)/ABtest','/bfdrest/client/(cid)/ABtest/(ABid)' '''
     myuuid = uuid.uuid1()
     LOG("info", _myuuid=myuuid)
     if abid == None:
         return pub.callback(json.dumps(GET_ret), myuuid)
     else:
         rstr = cache.get('%s:ABtest:%s' % (cid, abid))
         if abid == "_all_":
             return rstr
         ret = {}
         if rstr:
             ret = json.loads(rstr)
             ret["success"] = True
         else:
             ret["success"] = False
             ret["error_info"] = "no such ABtest id."
         return pub.callback(json.dumps(ret), myuuid)
Example #28
0
 def GET(self, n, b, k, proto=None):
     ''' /bfdrest/bfdcache/namesapce/business/key for get key;
     '''
     myuuid = uuid.uuid1()
     LOG("info", _myuuid=myuuid)
     v = cache.get(k, n, b)
     #        print '%s\t%s\t%s' % (n,b,k)
     if proto:
         if proto == 'DELETE':
             return pub.callback(json.dumps(cache.delete(k, n, b)), myuuid)
         if v == None or v == 'None':
             return pub.callback(json.dumps({}), myuuid)
         ib = eval("%s()" % proto)
         try:
             ib.ParseFromString(v)
         except Exception, e:
             return pub.callback(str(e), myuuid)
         return pub.callback(json.dumps(proto2json(ib)), myuuid)
Example #29
0
 def POST(self, cid, goodsid):
     ''' /bfdrest/client/(cid)/goods/(goodsid) '''
     myuuid = uuid.uuid1()
     LOG("info", _myuuid=myuuid)
     value = web.data()
     put_value = {}
     ret = {}
     data = {}
     pgs = RecBanner_pb2.Goods()
     g_str = cache.get('%s:Goods:%s' % (cid, goodsid))
     if g_str:
         pgs.ParseFromString(g_str)
     pgs.goods_id = goodsid
     try:
         put_value = json.loads(value)
     except Exception, e:
         ret["success"] = False
         ret["error_info"] = "wrong json format: %s" % str(e)
         return pub.callback(json.dumps(ret), myuuid)
Example #30
0
 def DELETE(self, cid, bid):
     ''' '/bfdrest/client/(cid)/banners/(bid)' '''
     myuuid = uuid.uuid1()
     LOG("info", _myuuid=myuuid)
     rlist = cache.get('%s:Banners:_all_' % cid)
     if rlist:
         rlist = json.loads(rlist)
     else:
         rlist = {}
     if bid in rlist:
         del rlist[bid]
     cache.set('%s:Banners:_all_' % (cid), json.dumps(rlist))
     rstr = cache.delete('%s:Banners:%s' % (cid, bid))
     rstr = cache.delete('%s:RecBanner:%s' % (cid, bid))
     ret = {}
     if rstr:
         ret["success"] = True
     else:
         ret["success"] = False
         ret["error_info"] = "can't delete banner info."
     return pub.callback(json.dumps(ret), myuuid)
Example #31
0
def generalize_items(client, gsid, items):
    iids = []
    info = {'success': True, 'error_info': '', 'faild_items': {}}
    for item_info in items:
        if 'iid' not in item_info:
            info['success'] = False
            info['error_info'] += "item error, some item have no iid. "
            continue
        iid = item_info['iid']
        add_item_url = 'http://ds.api.baifendian.com/2.0/AddItem.do?ignore_domain=1&store=1&cid=%s&iid=%s' % (
            quote(client), quote(iid))
        for key in item_info:
            try:
                add_item_url += '&%s=%s' % (
                    key, urllib.quote(item_info[key].encode('utf-8')))
                pass
            except Exception, e:
                info['success'] = False
                info['error_info'] += "item info error."
                info['faild_items'][iid] = key + str(e)
        cache_key = "%s:ItemBase:%s" % (client, iid)
        cache_str = cache.get(cache_key, 'ns1', 'item')
        if not cache_str:
            try:
                add_item_url += "&gsid=%s" % quote(gsid)
                print add_item_url
                add_ret = urllib.urlopen(add_item_url)
                ret = json.loads(add_ret.readline())
                print ret
                if ret[0] == 0:
                    iids.append(iid)
                else:
                    info['success'] = False
                    info['error_info'] += "AddItem error."
                    info['faild_items'][iid] = json.dumps(ret)
            except Exception, e:
                info['success'] = False
                info['error_info'] += "AddItem error."
                info['faild_items'][iid] = str(e)
Example #32
0
File: brand.py Project: emeitu/test
    def GET(self, cid, brd):
        '''  
            /bfdrest/client/(cid)/brand/(brd)/all for get all children;
            /bfdrest/client/(cid)/brand/(brd) for get brand's child;
            /bfdrest/client/Czouxiu/brand/_all_(/all) for example;
        '''
        if method == None:
            return cache.get('%s:brand:%s' % (cid, brd))
        elif method == 'all':

            def getbrd(brd):
                ret = []
                brdstr = cache.get('%s:brand:%s' % (cid, brd))
                try:
                    brd = json.loads(brdstr)
                    for c in brd:
                        ret.append({c: getbrd('%s:%s' % (brd, c))})
                    return ret
                except:
                    return []

            return json.dumps(getbrd(brd))
Example #33
0
 def POST(self, cid, bid):
     ''' '/bfdrest/client/(cid)/banners/(bid)' '''
     myuuid = uuid.uuid1()
     LOG("info", _myuuid=myuuid)
     data = web.data()
     ret = {}
     rv = json.loads(data)
     rec_banner = ParseFromJson(cid, bid, rv)
     rlist = cache.get('%s:Banners:_all_' % cid)
     if rlist:
         rlist = json.loads(rlist)
     else:
         rlist = {}
     rlist[bid] = time.time()
     rstr = cache.set('%s:Banners:_all_' % (cid), json.dumps(rlist))
     rstr = cache.set('%s:RecBanner:%s' % (cid, bid),
                      rec_banner.SerializeToString())
     rstr = cache.set('%s:Banners:%s' % (cid, bid), data)
     if rstr:
         ret["success"] = True
     else:
         ret["success"] = False
         ret["error_info"] = "can't save banner info."
     return pub.callback(json.dumps(ret), myuuid)
Example #34
0
File: wx_qr.py Project: emeitu/test
    def GET(self):
        ''' '/wx/qr' '''
        myuuid = uuid.uuid1();LOG("info",_myuuid=myuuid)
        args = web.input()
        if "method" in args:
            method = args["method"]
            if method == "getQrTicket":
                web.header('Content-Type', 'application/javascript')
                data = args["data"]
                ret = urllib2.urlopen(
                "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=FoYOQEtQ-QHjnSv9tPDqpGOA49AFUZNqnQtPhhlRq_8i9XfxII3ofQGVtYpB6rjv",
                data)
                retstr = ret.read()
                return pub.callback(retstr,myuuid)
            elif method == "getQr":
                gid = web.cookies().get("bfdid")
                print gid
                param_index = int(cache.get("G:weixin:paramindex"))
                web.header('Content-Type', 'image/png')
                if param_index == None:
                    param_index = 0
                    cache.set("G:weixin:paramindex","0")
                else:
                    param_index = (int(param_index) + 1)%100
                    cache.set("G:weixin:paramindex",str(param_index))
                access_token = cache.get("G:weixin:access_token")
                data = {"expire_seconds":"1800","action_name":"QR_SCENE","action_info":{"scene":{"scene_id":str(param_index)}}}
                def getTicket(access_token):
                    ret = urllib2.urlopen(
                    "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+access_token,
                    json.dumps(data))
                    retstr = ret.read()
                    ticket = json.loads(retstr)["ticket"]
                    return ticket
                try:
                    ticket = getTicket(access_token)
                except:
                    appid = "wx68cc9091ef2be695"
                    secret = "c27b72cd1d51114cda5e816bbb95ab6d"
                    get_access_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (appid,secret)
                    access_token_ret = urllib2.urlopen(get_access_url)
                    access_token = json.loads(access_token_ret.read())["access_token"]
                    cache.set("G:weixin:access_token",access_token)
                    ticket = getTicket(access_token)
                    
                qrurl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s"%ticket
                qrimg = urllib2.urlopen(qrurl)
                img = qrimg.read()
                cache.set("G:weixin:scene:%d"%param_index,gid)
                return img
            elif method == "getgid":
                web.header('Content-Type', 'application/javascript')
                open_id = args["open_id"]
                cid = args["cid"]
                if "scene_id" in args:
                    scene_id = args["scene_id"]
                    gid = cache.get("G:weixin:scene:%s"%scene_id)
                    cache.set("G:weixin:openid:%s:%s"%(cid,open_id),gid)
                    return pub.callback('"%s"'%gid,myuuid)
                else:
                    gid = cache.get("G:weixin:openid:%s:%s"%(cid,open_id))
                    return pub.callback('"%s"'%gid,myuuid)
            elif method == "getopenid":
                web.header('Content-Type', 'application/javascript')
                code = args['code']
                access_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx68cc9091ef2be695&secret=c27b72cd1d51114cda5e816bbb95ab6d&code=%s&grant_type=authorization_code' % code
                ret = urllib2.urlopen(access_url)
                return pub.callback(ret.read(),myuuid)

        else:
            web.header('Content-Type', 'application/javascript')
            return pub.callback(json.dumps(None),myuuid)
Example #35
0
def generalize_ranges(client, ranges):
    range_iids = {}
    if client not in client_conf:
        main_property = client_conf["Cdemo"]['main_property']
        all_properties = client_conf["Cdemo"]["properties"]
    else:
        main_property = client_conf[client]['main_property']
        all_properties = client_conf[client]["properties"]
    print main_property
    # find main property path and other property
    print ranges
    if client not in client_property_tree:
        client_property_tree[client] = cPickle.load(
            open('./data/%s.ptree.pkl' % client, 'rb'))
    property_tree = client_property_tree[client]
    for range in ranges:
        iids = []
        main_path = []
        property_path = []
        print range
        if len(range) > 0:
            tag = range[0]
            if tag in all_properties:
                del range[0]
            elif tag == "_all_":
                del range[0]
                continue
            elif tag == "goods":
                goodsid = range[1]
                gstr = cache.get("%s:Goods:%s" % (client, goodsid))
                if gstr:
                    gv = json.loads(gstr)
                    if "keys" in gv:
                        for key in gv["keys"]:
                            rstr = cache.get("%s:GoodsItems:%s" %
                                             (client, key))
                            if rstr:
                                iids.extend(json.loads(rstr))
                    rstr = cache.get("%s:GoodsItems:%s" % (client, goodsid))
                    if rstr:
                        iids.extend(json.loads(rstr))
                range_iids[goodsid] = iids
                continue
        for pv in range:
            property = pv[0]
            value = pv[1]
            if value == "_all_":
                continue
            if property == main_property:
                main_path.append(value)
            else:
                property_path.append(pv)
        print("main_path", main_path)
        print("property_apth", property_path)
        cur_tree = property_tree
        find_path = True
        for path_node in main_path:
            if path_node in cur_tree['nodes']:
                cur_tree = cur_tree['nodes'][path_node]
            else:
                find_path = False
        if not find_path:
            continue

        def add_iids(tree_node):
            for id in tree_node['items']:
                id_in_range = True
                for pv in property_path:
                    property = pv[0]
                    value = pv[1]
                    #                    print "property:%s" % str(pv)
                    if property not in tree_node['items'][
                            id] or value not in tree_node['items'][id][
                                property]:
                        id_in_range = False
                if id_in_range:
                    iids.append(id)
            for next_node in tree_node['nodes']:
                add_iids(tree_node['nodes'][next_node])

        add_iids(cur_tree)
        path_key = md5.new(json.dumps([main_path, property_path])).hexdigest()
        range_iids[path_key] = iids
    return range_iids
Example #36
0
def StopBannerABtest(cid, abid, jab):
    bannerstr = cache.get("%s:RecBanner:%s" % (cid, jab["banner_id"]))
    if not bannerstr:
        return False
Example #37
0
def SetBannerABtest(cid, abid, jab, stop=False, delete=False):
    bannerstr = cache.get("%s:RecBanner:%s" % (cid, jab["banner_id"]))
    if not bannerstr:
        print "no banner_id"
        return False
    rb = RecBanner_pb2.RecBanner()
    lr = RecBanner_pb2.RecBanner.LogicRule()
    opr = RecBanner_pb2.RecBanner.LogicRule.OperationRule()
    pr = RecBanner_pb2.RecBanner.LogicRule.PositionRule()
    abr = RecBanner_pb2.RecBanner.ABtestRule()
    ablr = RecBanner_pb2.RecBanner.ABtestRule.LogicRule()
    absr = RecBanner_pb2.RecBanner.ABtestRule.LogicRule.SortRule()
    tr = RecBanner_pb2.TimeRange()
    tp = RecBanner_pb2.TimeRange.TimePoint()
    ir = RecBanner_pb2.ItemRange()
    try:
        rb.ParseFromString(bannerstr)
        if stop:
            abrstr = cache.get("%s:ABtestRule:%s" % (cid, abid))
            if not abrstr:
                print "no abtest_id"
                return False
            abr.ParseFromString(abrstr)
            abr.is_active = False
            cache.set("%s:ABtestRule:%s" % (cid, abid),
                      abr.SerializeToString())
            for i in xrange(len(rb.abtest_rules)):
                if abid == rb.abtest_rules[i].abtest_id:
                    rb.abtest_rules[i].is_active = False
                    break
            rb.update_time = int(time.time())
            return cache.set("%s:RecBanner:%s" % (cid, jab["banner_id"]),
                             rb.SerializeToString())
        if delete:
            for i in xrange(len(rb.abtest_rules)):
                if abid == rb.abtest_rules[i].abtest_id:
                    del (rb.abtest_rules[i])
                    break
            rb.update_time = int(time.time())
            return cache.set("%s:RecBanner:%s" % (cid, jab["banner_id"]),
                             rb.SerializeToString())
        abr.abtest_id = abid
        abr.name = jab["name"]
        abr.description = jab["description"]
        abr.traffic_ratio = jab["traffic_ratio"]
        abr.is_active = jab["is_active"]
        abr.banner_id = jab["banner_id"]
        if "user_level" in jab:
            abr.user_level = jab["user_level"]

        tr.type = jab["time_type"]
        tp.day = jab["start_time"]["day"]
        tp.time = jab["start_time"]["time"]
        tp.wday = jab["start_time"]["wday"]
        tr.start_time.CopyFrom(tp)
        tp.day = jab["end_time"]["day"]
        tp.time = jab["end_time"]["time"]
        tp.wday = jab["end_time"]["wday"]
        tr.end_time.CopyFrom(tp)
        abr.time_range.CopyFrom(tr)

        def parse_item_range(jir, has_ratio=False):
            ir.Clear()
            if len(jir) > 0:
                ir.type = jir[0]
                if has_ratio and len(jir) > 1:
                    ir.ratio = int(jir[1])
                    del jir[0:2]
                else:
                    del jir[0]
                if ir.type == "goods":
                    ir.goods_id = jir[0]
                    del jir[0]
                if ir.type != "_all_":
                    for pv in jir:
                        if pv[0] == 'price_less_than' or pv[
                                0] == 'price_greater_than':
                            setattr(ir, pv[0], float(pv[1]))
                        else:
                            eval("ir.%s.append(pv[1])" % pv[0])
            return ir

        if len(jab["condition"]) > 0:
            abr.condition.CopyFrom(parse_item_range(jab["condition"]))

        def parse_logic_rule(jlr):
            ablr.Clear()
            if "rec_ranges" in jlr:
                for jir in jlr["rec_ranges"]:
                    ablr.rec_ranges.add()
                    ablr.rec_ranges[len(ablr.rec_ranges) - 1].CopyFrom(
                        parse_item_range(jir, True))
            if "filter_ranges" in jlr:
                for jir in jlr["filter_ranges"]:
                    ablr.filter_ranges.add()
                    ablr.filter_ranges[len(ablr.filter_ranges) - 1].CopyFrom(
                        parse_item_range(jir))
            if "sort" in jlr:
                for jsr in jlr["sort"]:
                    absr.Clear()
                    absr.property = jsr[0]
                    absr.type = int(jsr[1])
                    ablr.sort_rules.add()
                    ablr.sort_rules[len(ablr.sort_rules) - 1].CopyFrom(absr)
            return ablr

        abr.logic_rules.add()
        abr.logic_rules.add()
        abr.logic_rules[0].CopyFrom(parse_logic_rule(jab["test_a"]))
        abr.logic_rules[1].CopyFrom(parse_logic_rule(jab["test_b"]))

        new_abtest = True
        for i in xrange(len(rb.abtest_rules)):
            if abid == rb.abtest_rules[i].abtest_id:
                rb.abtest_rules[i].Clear()
                rb.abtest_rules[i].CopyFrom(abr)
                new_abtest = False
                break
        if new_abtest:
            rb.abtest_rules.add()
            rb.abtest_rules[len(rb.abtest_rules) - 1].CopyFrom(abr)
        rb.update_time = int(time.time())
        rstr = cache.set('%s:ABtestRule:%s' % (cid, abid),
                         abr.SerializeToString())
        return cache.set("%s:RecBanner:%s" % (cid, jab["banner_id"]),
                         rb.SerializeToString())
    except Exception, e:
        print "err: " + str(e)
        return False
Example #38
0
def StopBannerABtest(cid,abid,jab):
    bannerstr = cache.get("%s:RecBanner:%s"%(cid,jab["banner_id"]))
    if not bannerstr:
        return False
Example #39
0
def SetBannerABtest(cid,abid,jab,stop = False,delete = False):
    bannerstr = cache.get("%s:RecBanner:%s"%(cid,jab["banner_id"]))
    if not bannerstr:
        print "no banner_id"
        return False
    rb  = RecBanner_pb2.RecBanner()
    lr  = RecBanner_pb2.RecBanner.LogicRule()
    opr = RecBanner_pb2.RecBanner.LogicRule.OperationRule()
    pr  = RecBanner_pb2.RecBanner.LogicRule.PositionRule()
    abr = RecBanner_pb2.RecBanner.ABtestRule()
    ablr= RecBanner_pb2.RecBanner.ABtestRule.LogicRule()
    absr= RecBanner_pb2.RecBanner.ABtestRule.LogicRule.SortRule()
    tr  = RecBanner_pb2.TimeRange()
    tp  = RecBanner_pb2.TimeRange.TimePoint()
    ir  = RecBanner_pb2.ItemRange()
    try:
        rb.ParseFromString(bannerstr)
        if stop:
            abrstr = cache.get("%s:ABtestRule:%s"%(cid,abid))
            if not abrstr:
                print "no abtest_id"
                return False
            abr.ParseFromString(abrstr)
            abr.is_active = False
            cache.set("%s:ABtestRule:%s"%(cid,abid),abr.SerializeToString())
            for i in xrange(len(rb.abtest_rules)):
                if abid == rb.abtest_rules[i].abtest_id:
                    rb.abtest_rules[i].is_active = False
                    break
            rb.update_time = int(time.time())
            return cache.set("%s:RecBanner:%s"%(cid,jab["banner_id"]),rb.SerializeToString())
        if delete:
            for i in xrange(len(rb.abtest_rules)):
                if abid == rb.abtest_rules[i].abtest_id:
                    del(rb.abtest_rules[i])
                    break
            rb.update_time = int(time.time())
            return cache.set("%s:RecBanner:%s"%(cid,jab["banner_id"]),rb.SerializeToString())
        abr.abtest_id = abid
        abr.name = jab["name"]
        abr.description = jab["description"]
        abr.traffic_ratio = jab["traffic_ratio"]
        abr.is_active = jab["is_active"]
        abr.banner_id = jab["banner_id"]
        if "user_level" in jab:
            abr.user_level = jab["user_level"]

        tr.type = jab["time_type"]
        tp.day  = jab["start_time"]["day"]
        tp.time = jab["start_time"]["time"]
        tp.wday = jab["start_time"]["wday"]
        tr.start_time.CopyFrom(tp)
        tp.day  = jab["end_time"]["day"]
        tp.time = jab["end_time"]["time"]
        tp.wday = jab["end_time"]["wday"]
        tr.end_time.CopyFrom(tp)
        abr.time_range.CopyFrom(tr)

        def parse_item_range(jir,has_ratio=False):
            ir.Clear()
            if len(jir) > 0:
                ir.type = jir[0]
                if has_ratio and len(jir) > 1:
                    ir.ratio = int(jir[1])
                    del jir[0:2]
                else:
                    del jir[0]
                if ir.type == "goods":
                    ir.goods_id = jir[0]
                    del jir[0]
                if ir.type != "_all_":
                    for pv in jir:
                        if pv[0] == 'price_less_than' or pv[0] == 'price_greater_than':
                            setattr(ir,pv[0],float(pv[1]))
                        else:
                            eval("ir.%s.append(pv[1])"%pv[0])
            return ir
        if len(jab["condition"]) > 0:
            abr.condition.CopyFrom(parse_item_range(jab["condition"]))

        def parse_logic_rule(jlr):
            ablr.Clear()
            if "rec_ranges" in jlr:
                for jir in jlr["rec_ranges"]:
                    ablr.rec_ranges.add()
                    ablr.rec_ranges[len(ablr.rec_ranges)-1].CopyFrom(parse_item_range(jir,True))
            if "filter_ranges" in jlr:
                for jir in jlr["filter_ranges"]:
                    ablr.filter_ranges.add()
                    ablr.filter_ranges[len(ablr.filter_ranges)-1].CopyFrom(parse_item_range(jir))
            if "sort" in jlr:
                for jsr in jlr["sort"]:
                    absr.Clear()
                    absr.property = jsr[0]
                    absr.type = int(jsr[1])
                    ablr.sort_rules.add()
                    ablr.sort_rules[len(ablr.sort_rules)-1].CopyFrom(absr)
            return ablr
        abr.logic_rules.add()
        abr.logic_rules.add()
        abr.logic_rules[0].CopyFrom(parse_logic_rule(jab["test_a"]))
        abr.logic_rules[1].CopyFrom(parse_logic_rule(jab["test_b"]))

        new_abtest = True
        for i in xrange(len(rb.abtest_rules)):
            if abid == rb.abtest_rules[i].abtest_id:
                rb.abtest_rules[i].Clear()
                rb.abtest_rules[i].CopyFrom(abr)
                new_abtest = False
                break
        if new_abtest:
            rb.abtest_rules.add()
            rb.abtest_rules[len(rb.abtest_rules)-1].CopyFrom(abr)
        rb.update_time = int(time.time())
        rstr = cache.set('%s:ABtestRule:%s'%(cid,abid),abr.SerializeToString())
        return cache.set("%s:RecBanner:%s"%(cid,jab["banner_id"]),rb.SerializeToString())
    except Exception,e:
        print "err: " + str(e)
        return False
Example #40
0
class handler:
    def GET(self, cid, goodsid=None, range=None):
        ''' /bfdrest/client/(cid)/goods/(goodsid)/(items) '''
        myuuid = uuid.uuid1()
        LOG("info", _myuuid=myuuid)
        if goodsid == None:
            if cid in goods_fields_conf:
                return pub.callback(json.dumps(goods_fields_conf[cid]), myuuid)
            return pub.callback(json.dumps(goods_fields), myuuid)
        elif goodsid == "type":
            return pub.callback(json.dumps(type_define), myuuid)
        else:
            gv = cache.get('%s:Goods:%s' % (cid, goodsid))
            if gv:
                ret = json.loads(gv)
                ret['success'] = True
                if range == None:
                    if 'keys' in ret:
                        del ret['keys']
                        pass
                    return pub.callback(json.dumps(ret), myuuid)
                else:
                    iids = []
                    # 获取范围的item
                    for key in [goodsid]:
                        ids_str = cache.get('%s:GoodsItems:%s' % (cid, key))
                        if ids_str:
                            iids.extend(json.loads(ids_str))
                    return pub.callback(json.dumps(iids), myuuid)

            else:
                ret = {}
                ret['success'] = False
                ret['error_info'] = 'no such goods id.'
                return pub.callback(json.dumps(ret), myuuid)

    def POST(self, cid, goodsid):
        ''' /bfdrest/client/(cid)/goods/(goodsid) '''
        myuuid = uuid.uuid1()
        LOG("info", _myuuid=myuuid)
        value = web.data()
        put_value = {}
        ret = {}
        data = {}
        pgs = RecBanner_pb2.Goods()
        g_str = cache.get('%s:Goods:%s' % (cid, goodsid))
        if g_str:
            pgs.ParseFromString(g_str)
        pgs.goods_id = goodsid
        try:
            put_value = json.loads(value)
        except Exception, e:
            ret["success"] = False
            ret["error_info"] = "wrong json format: %s" % str(e)
            return pub.callback(json.dumps(ret), myuuid)
        if put_value.has_key('name'):
            data['name'] = put_value['name']
            pgs.name = put_value['name']
        else:
            data['name'] = ""
        if put_value.has_key('description'):
            data['description'] = put_value['description']
            pgs.description = put_value['description']
        else:
            data['description'] = ""
        if "user_level" in put_value:
            data["user_level"] = put_value["user_level"]
            pgs.user_level = put_value["user_level"]
        pgs.is_ranges = False
        if put_value.has_key('items') and len(put_value['items']) > 0:
            ret["success"] = True
            # save goods
            data['items'] = put_value['items']
            # 待添加具体功能,更新ItemBase,更新商品库商品
            rm_goods_solr(cid, goodsid, data['items'])
            iids, info = generalize_items(cid, goodsid, data['items'])
            data['keys'] = [goodsid]
            del data['items']
            goods_list = cache.get('%s:Goods:_all_' % cid)
            if goods_list:
                goods_list = json.loads(goods_list)
            else:
                goods_list = {}
            goods_list[goodsid] = time.time()
            cache.set('%s:Goods:_all_' % cid, json.dumps(goods_list))
            cache.set('%s:GoodsItems:%s' % (cid, goodsid), json.dumps(iids))
            cache.set('%s:Goods:%s' % (cid, goodsid), pgs.SerializeToString())
            return pub.callback(json.dumps(info), myuuid)
        elif put_value.has_key('ranges') and len(put_value['ranges']) > 0:
            pgs.is_ranges = True
            for i in xrange(len(pgs.ranges)):
                del pgs.ranges[0]
            ret["success"] = True
            # save goods
            data['ranges'] = put_value['ranges']

            def parse_item_range(jir, has_ratio=False):
                ir = RecBanner_pb2.ItemRange()
                if len(jir) > 0:
                    ir.type = jir[0][0]
                    for pv in jir:
                        if len(pv) > 1 and pv[1] != "_all_":
                            eval("ir.%s.append(pv[1])" % pv[0])
                return ir

            for range in put_value['ranges']:
                pgs.ranges.add()
                pgs.ranges[len(pgs.ranges) - 1].CopyFrom(
                    parse_item_range(range))

            #rm_goods_solr(cid,goodsid)
            range_iids = generalize_ranges(cid, data['ranges'])
            data["keys"] = range_iids.keys()
            iids = []
            for key in range_iids:
                iids.extend(range_iids[key])
            goods_list = cache.get('%s:Goods:_all_' % cid)
            if goods_list:
                goods_list = json.loads(goods_list)
            else:
                goods_list = {}
            goods_list[goodsid] = time.time()
            cache.set('%s:Goods:_all_' % cid, json.dumps(goods_list))
            cache.set('%s:GoodsItems:%s' % (cid, goodsid), json.dumps(iids))
            cache.set('%s:Goods:%s' % (cid, goodsid), pgs.SerializeToString())
            # 待添加具体功能,更新商品库商品
            return pub.callback(json.dumps(ret), myuuid)
        else:
            ret["success"] = True
            cache.set('%s:Goods:%s' % (cid, goodsid), pgs.SerializeToString())
            return pub.callback(json.dumps(ret), myuuid)
Example #41
0
File: wx_qr.py Project: emeitu/test
    def GET(self):
        ''' '/wx/qr' '''
        myuuid = uuid.uuid1()
        LOG("info", _myuuid=myuuid)
        args = web.input()
        if "method" in args:
            method = args["method"]
            if method == "getQrTicket":
                web.header('Content-Type', 'application/javascript')
                data = args["data"]
                ret = urllib2.urlopen(
                    "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=FoYOQEtQ-QHjnSv9tPDqpGOA49AFUZNqnQtPhhlRq_8i9XfxII3ofQGVtYpB6rjv",
                    data)
                retstr = ret.read()
                return pub.callback(retstr, myuuid)
            elif method == "getQr":
                gid = web.cookies().get("bfdid")
                print gid
                param_index = int(cache.get("G:weixin:paramindex"))
                web.header('Content-Type', 'image/png')
                if param_index == None:
                    param_index = 0
                    cache.set("G:weixin:paramindex", "0")
                else:
                    param_index = (int(param_index) + 1) % 100
                    cache.set("G:weixin:paramindex", str(param_index))
                access_token = cache.get("G:weixin:access_token")
                data = {
                    "expire_seconds": "1800",
                    "action_name": "QR_SCENE",
                    "action_info": {
                        "scene": {
                            "scene_id": str(param_index)
                        }
                    }
                }

                def getTicket(access_token):
                    ret = urllib2.urlopen(
                        "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="
                        + access_token, json.dumps(data))
                    retstr = ret.read()
                    ticket = json.loads(retstr)["ticket"]
                    return ticket

                try:
                    ticket = getTicket(access_token)
                except:
                    appid = "wx68cc9091ef2be695"
                    secret = "c27b72cd1d51114cda5e816bbb95ab6d"
                    get_access_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (
                        appid, secret)
                    access_token_ret = urllib2.urlopen(get_access_url)
                    access_token = json.loads(
                        access_token_ret.read())["access_token"]
                    cache.set("G:weixin:access_token", access_token)
                    ticket = getTicket(access_token)

                qrurl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s" % ticket
                qrimg = urllib2.urlopen(qrurl)
                img = qrimg.read()
                cache.set("G:weixin:scene:%d" % param_index, gid)
                return img
            elif method == "getgid":
                web.header('Content-Type', 'application/javascript')
                open_id = args["open_id"]
                cid = args["cid"]
                if "scene_id" in args:
                    scene_id = args["scene_id"]
                    gid = cache.get("G:weixin:scene:%s" % scene_id)
                    cache.set("G:weixin:openid:%s:%s" % (cid, open_id), gid)
                    return pub.callback('"%s"' % gid, myuuid)
                else:
                    gid = cache.get("G:weixin:openid:%s:%s" % (cid, open_id))
                    return pub.callback('"%s"' % gid, myuuid)
            elif method == "getopenid":
                web.header('Content-Type', 'application/javascript')
                code = args['code']
                access_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx68cc9091ef2be695&secret=c27b72cd1d51114cda5e816bbb95ab6d&code=%s&grant_type=authorization_code' % code
                ret = urllib2.urlopen(access_url)
                return pub.callback(ret.read(), myuuid)

        else:
            web.header('Content-Type', 'application/javascript')
            return pub.callback(json.dumps(None), myuuid)
Example #42
0
def remove_goods_relation(cid, goods_id, jdata):
    for p_bid in json.loads(jdata["banner_id"]):
        p_bid_str = cache.get("%s:RecBanner:%s" % (cid, p_bid))
        p_banner = RecBanner_pb2.RecBanner()
        if p_bid_str:
            p_banner.ParseFromString(p_bid_str)
            n = 0
            for i in xrange(len(p_banner.logic_rule.position_rules)):
                for j in xrange(
                        len(p_banner.logic_rule.position_rules[i -
                                                               n].goods_id)):
                    if p_banner.logic_rule.position_rules[
                            i - n].goods_id[j] == goods_id:
                        del p_banner.logic_rule.position_rules[i -
                                                               n].goods_id[j]
                        break
                if len(p_banner.logic_rule.position_rules[i -
                                                          n].goods_id) == 0:
                    del p_banner.logic_rule.position_rules[i - n]
                    n += 1
            cache.set("%s:RecBanner:%s" % (cid, p_bid),
                      p_banner.SerializeToString())
    for ab_id in json.loads(jdata["abtest_id"]):
        ab_str = cache.get('%s:ABtestRule:%s' % (cid, ab_id))
        p_ab = RecBanner_pb2.RecBanner.ABtestRule()
        if ab_str:
            p_ab.ParseFromString(ab_str)
            for logic_rule in p_ab.logic_rules:
                for i in xrange(len(logic_rule.rec_ranges)):
                    if logic_rule.rec_ranges[
                            i].type == "goods" and logic_rule.rec_ranges[
                                i].goods_id == goods_id:
                        del logic_rule.rec_ranges[i]
                        break
                for i in xrange(len(logic_rule.filter_ranges)):
                    if logic_rule.filter_ranges[
                            i].type == "goods" and logic_rule.filter_ranges[
                                i].goods_id == goods_id:
                        del logic_rule.filter_ranges[i]
                        break
            cache.set('%s:ABtestRule:%s' % (cid, ab_id),
                      p_ab.SerializeToString())
            p_bid = p_ab.banner_id
            p_bid_str = cache.get("%s:RecBanner:%s" % (cid, p_bid))
            p_banner = RecBanner_pb2.RecBanner()
            if p_bid_str:
                p_banner.ParseFromString(p_bid_str)
                for ab in p_banner.abtest_rules:
                    if ab.abtest_id == ab_id:
                        ab.Clear()
                        ab.CopyFrom(p_ab)
                        break
                cache.set("%s:RecBanner:%s" % (cid, p_bid),
                          p_banner.SerializeToString())
    for op_id in json.loads(jdata["operation_id"]):
        op_str = cache.get('%s:OperationRule:%s' % (cid, op_id))
        p_op = RecBanner_pb2.OperationRule()
        if op_str:
            p_op.ParseFromString(op_str)
            for i in xrange(len(p_op.rec_ranges)):
                if p_op.rec_ranges[i].type == "goods" and p_op.rec_ranges[
                        i].goods_id == goods_id:
                    del p_op.rec_ranges[i]
                    break
            for i in xrange(len(p_op.filter_ranges)):
                if p_op.filter_ranges[i].type == "goods" and p_op.filter_ranges[
                        i].goods_id == goods_id:
                    del p_op.rec_ranges[i]
                    break
            cache.set('%s:OperationRule:%s' % (cid, op_id),
                      p_op.SerializeToString())