加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

抢购业务模块(redis+mysql)

发布时间:2020-12-17 17:27:52 所属栏目:Python 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 class CatchCouponService(object): """ 抢券活动操作 """ def __init__(self): self.redis_clt = Context.inst().coupon_redis def new(self,coupon_

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

class CatchCouponService(object):
    """
    抢券活动操作
    """
    def __init__(self):
        self.redis_clt = Context.inst().coupon_redis

    def new(self,coupon_id,total,expire=None):
        """
        新建抢券活动

        :param coupon_id: 优惠券id
        :param total: 总数
        :param expire: 超时 sec or timedelta
        :return: code
        """
        key = self.key(coupon_id)
        self.redis_clt.set(key,ex=expire)
        logging.warning("create new coupon activity: key(%s) count(%s) expire(%s)",key,expire)
        return E_SUCC

    @classmethod
    def key(cls,coupon_id):
        """
        获取key

        :param coupon_id: 优惠券id
        :return: key
        """
        return "coupon:%s" % coupon_id

    def is_success(self,coupon_id):
        """
        判断是否抢购成功

        :param coupon_id:
        :return: boolean,剩余数量
        """
        key = self.key(coupon_id)
        count = self.redis_clt.decr(key)
        if count >= 0:
            return E_SUCC,count
        else:
            self.redis_clt.delete(key)
            logging.warning("delete coupon activity: cid(%s)",key)
            return E_COUPON_ACTIVITY_DONE,0

    def update(self,params):
        """
        更新抢券活动

        :param coupon_id: 优惠券id
        :param params: 更新内容
        :return: code
        """
        key = self.key(coupon_id)
        if "total" in params:
            self.redis_clt.set(key,params["total"])
            logging.warning("update coupon activity: total(%s)",params["total"])
        if "expire" in params:
            self.redis_clt.expire(key,params["expire"])
            logging.warning("update coupon activity: expire(%s)",params["expire"])
        return E_SUCC,None

    def delete(self,coupon_id):
        """
        删除

        :param coupon_id: 优惠券id
        :return: boolean
        """
        logging.warning("delete coupon activity: key(%s)",self.key(coupon_id))
        self.redis_clt.delete(self.key(coupon_id))
        return E_SUCC,None

    def query(self,coupon_list):
        """
        查询余数

        :param coupon_list: 优惠券id列表
        :return: {优惠券id: 优惠券余数}
        """
        # return self.redis_clt.get(self.key(coupon_id)) or 0
        result = {}
        key = [self.key(i) for i in coupon_list]

        values = self.redis_clt.mget(key)
        for i in range(len(key)):
            result[coupon_list[i]] = values[i] or 0
        return result

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读