Ejemplo n.º 1
0
def add_element_to_menu(event_code,
                        menu_type,
                        menu_kind,
                        element,
                        end_time=None):
    """
        为名单中增加元素
    :param event_code: 名单项目code
    :param menu_type: 名单类型  black white gray
    :param menu_kind: 名单维度 user_id / ip / ...
    :param element: 放入名单的元素
    :param end_time: 失效时间
    :return:
    """
    end_time = (end_time or datetime.now() + timedelta(hours=1))
    menu_desc = get_sample_str(15)
    payload = dict(end_time=end_time,
                   menu_desc=menu_desc,
                   menu_status=u"有效",
                   create_time=datetime.now(),
                   creator='test',
                   value=element,
                   event=event_code,
                   menu_kind=menu_kind,
                   menu_type=menu_type)
    db = get_mongo_client()
    insert_result = db['menus'].insert_one(payload)

    redis_client = get_redis_client()
    redis_key = build_redis_key(event_code, menu_type, menu_kind)
    if redis_key:
        redis_client.sadd(redis_key, element)

    return str(insert_result.inserted_id)
Ejemplo n.º 2
0
    def post(self, request, *args, **kwargs):
        db = get_mongo_client()
        ids = request.POST.get('ids')
        try:
            assert ids
            obj_ids = [ObjectId(id_) for id_ in ids.split(',')]
        except Exception:
            return self.render_json_response(
                dict(state=False, error=_("ID is illegal")))

        redis_values_should_remove = defaultdict(list)

        menus_records = list(db['menus'].find(
            {
                '_id': {
                    "$in": obj_ids
                },
                'menu_status': 'valid'
            }, {
                'event_code': True,
                '_id': False,
                'dimension': True,
                'menu_type': True,
                'value': True,
            }))

        if not menus_records:
            return self.render_json_response(
                dict(state=False, error=_("Records don't exist")))

        for d in menus_records:
            redis_key = build_redis_key(d['event_code'], d['dimension'],
                                        d['menu_type'])
            if redis_key:
                redis_values_should_remove[redis_key].append(d['value'])

        update_payload = {
            'menu_status': 'invalid',
            'creator': request.user.username,
            'create_time': datetime.now(),
        }
        try:
            db.menus.update_many({'_id': {
                "$in": obj_ids
            }}, {"$set": update_payload})

            #  Simultaneous delete redis data
            redis_client = get_redis_client()
            pipeline = redis_client.pipeline(transaction=False)
            for key, values in redis_values_should_remove.items():
                pipeline.srem(key, *values)
            pipeline.execute()
        except Exception:
            return self.render_json_response(
                dict(state=False,
                     error=_("Operation failed, please try again later")))
        return self.render_json_response(dict(state=True, msg=_("ok")))
Ejemplo n.º 3
0
    def post(self, request, *args, **kwargs):
        db = get_mongo_client()
        ids = request.POST.get('ids')
        try:
            assert ids
            obj_ids = [ObjectId(id_) for id_ in ids.split(',')]
        except Exception:
            return self.render_json_response(dict(
                state=False,
                error=u"id不合法"
            ))

        redis_values_should_remove = defaultdict(list)

        menus_records = list(
            db['menus'].find({'_id': {"$in": obj_ids}, 'menu_status': u'有效'},
                             {'event_code': True, '_id': False,
                              'dimension': True,
                              'menu_type': True, 'value': True,
                              }))

        if not menus_records:
            return self.render_json_response(dict(
                state=False,
                error=u"记录均不存在"
            ))

        for d in menus_records:
            redis_key = build_redis_key(d['event_code'], d['dimension'],
                                        d['menu_type'])
            if redis_key:
                redis_values_should_remove[redis_key].append(d['value'])

        update_payload = {
            'menu_status': u'无效',
            'creator': request.user.username,
            'create_time': datetime.now(),
        }
        try:
            db.menus.update_many({'_id': {"$in": obj_ids}},
                                 {"$set": update_payload})

            #  同时删除redis中数据
            redis_client = get_redis_client()
            pipeline = redis_client.pipeline(transaction=False)
            for key, values in redis_values_should_remove.items():
                pipeline.srem(key, *values)
            pipeline.execute()
        except Exception:
            return self.render_json_response(dict(
                state=False,
                error=u"操作失败,请稍后重试"
            ))
        return self.render_json_response(dict(
            state=True,
            msg="ok"
        ))
Ejemplo n.º 4
0
    def save(self, *args, **kwargs):
        """新增时,若存在维度值+项目+名单类型相同情况,则update为新增值"""
        cd = self.cleaned_data
        value_list = cd['value']
        chinese_name = self.request.user.username
        error_datas = []
        end_time = cd['end_time'].replace(tzinfo=None)

        db = get_mongo_client()
        redis_client = get_redis_client()
        for value in value_list:
            payload = dict(
                end_time=end_time,
                menu_desc=cd['menu_desc'],
                menu_status=u"有效",
                create_time=datetime.datetime.now(),
                creator=chinese_name
            )

            value = value.strip()
            dimension = cd['dimension']
            menu_type = cd['menu_type']
            event_code = cd.get('event_code')

            condition = dict(value=value,
                             event_code=event_code,
                             menu_type=menu_type,
                             dimension=dimension
                             )
            res = db.menus.find_one(condition)

            try:
                if not res:
                    payload.update(condition)
                    db.menus.insert_one(payload)
                else:
                    db.menus.update_one({"_id": res.get("_id", '')},
                                        {"$set": payload})

                #  同时写redis
                redis_key = build_redis_key(event_code, dimension,
                                            menu_type)
                if redis_key:
                    redis_client.sadd(redis_key, value)

            except Exception:
                error_datas.append(value)

        return error_datas
Ejemplo n.º 5
0
def add_element_to_menu(event_code,
                        menu_type,
                        dimension,
                        element,
                        end_time=None,
                        menu_desc=None):
    """
        Add elements to the list
    :param str|unicode event_code: List item code
    :param str|unicode menu_type: ListType  black white gray
    :param str|unicode dimension: List dimensions user_id / ip / ...
    :param str|unicode element: Elements placed on the list
    :param datetime end_time: Failure time
    :param str|unicode menu_desc: Note
    :return:
    """
    end_time = (end_time or datetime.now() + timedelta(hours=1))
    menu_desc = menu_desc or get_sample_str(15)
    payload = dict(end_time=end_time,
                   menu_desc=menu_desc,
                   menu_status='valid',
                   create_time=datetime.now(),
                   creator='test',
                   value=element,
                   event_code=event_code,
                   dimension=dimension,
                   menu_type=menu_type)
    db = get_mongo_client()
    insert_result = db['menus'].insert_one(payload)

    redis_client = get_redis_client()
    redis_key = build_redis_key(event_code,
                                dimension=dimension,
                                menu_type=menu_type)
    if redis_key:
        redis_client.sadd(redis_key, element)

    return str(insert_result.inserted_id)