Beispiel #1
0
def add_activity(activity: ActivityModel,
                 merchant_id: int = Depends(get_login_merchant),
                 session: Session = Depends(create_session)):
    """
    新建营销活动\n
    :param activity: 活动信息\n
    :return:
    """
    ret_code = 0
    ret_msg = "success"
    try:
        cur_merchant = json.loads(redis_client.hget("merchants", merchant_id))
        if cur_merchant["merchant_type"] != 0:
            session.commit()
            return make_response(-1, "权限不足!")

        now = datetime.now()
        act = Activity(activity.act_name, activity.act_cover,
                       activity.begin_time, activity.end_time, now, now)
        session.add(act)

        # 活动存入redis并添加商品折扣表
        activity_key = f"activity_{act.id}"
        discount_key = f"discount_of_activity_{act.id}"
        expire_time = (activity.end_time - now).seconds
        pipe = redis_client.pipeline(transaction=True)
        pipe.set(activity_key,
                 json.dumps(act.to_dict(), cls=JsonEncoder),
                 ex=expire_time)
        # 创建一个空的商品折扣表, 插入一条空数据占位符
        pipe.hset(discount_key, "", "")
        pipe.expire(discount_key, expire_time)
        pipe.execute()
        logger.info("活动redis信息初始化成功!")

        session.commit()
        logger.info(f"新建营销活动成功,活动id: {act.id}")
    except Exception as e:
        session.rollback()
        logger.error(str(e))
        ret_code = -1
        ret_msg = str(e)
    return make_response(ret_code, ret_msg)