Esempio n. 1
0
    def test_incr_no_timeout(self, cache: RedisCache):
        if isinstance(cache.client, herd.HerdClient):
            pytest.skip("HerdClient doesn't support incr")

        cache.set("num", 1, timeout=None)

        cache.incr("num")
        res = cache.get("num")
        assert res == 2

        cache.incr("num", 10)
        res = cache.get("num")
        assert res == 12

        # max 64 bit signed int
        cache.set("num", 9223372036854775807, timeout=None)

        cache.incr("num")
        res = cache.get("num")
        assert res == 9223372036854775808

        cache.incr("num", 2)
        res = cache.get("num")
        assert res == 9223372036854775810

        cache.set("num", 3, timeout=None)

        cache.incr("num", 2)
        res = cache.get("num")
        assert res == 5
Esempio n. 2
0
    def test_version(self, cache: RedisCache):
        cache.set("keytest", 2, version=2)
        res = cache.get("keytest")
        assert res is None

        res = cache.get("keytest", version=2)
        assert res == 2
Esempio n. 3
0
    def test_touch_positive_timeout(self, cache: RedisCache):
        cache.set("test_key", 222, timeout=10)

        assert cache.touch("test_key", 2) is True
        assert cache.get("test_key") == 222
        time.sleep(3)
        assert cache.get("test_key") is None
Esempio n. 4
0
 def test_clear(self, cache: RedisCache):
     cache.set("foo", "bar")
     value_from_cache = cache.get("foo")
     assert value_from_cache == "bar"
     cache.clear()
     value_from_cache_after_clear = cache.get("foo")
     assert value_from_cache_after_clear is None
Esempio n. 5
0
    def test_save_string(self, cache: RedisCache):
        cache.set("test_key", "hello" * 1000)
        res = cache.get("test_key")

        assert isinstance(res, str)
        assert res == "hello" * 1000

        cache.set("test_key", "2")
        res = cache.get("test_key")

        assert isinstance(res, str)
        assert res == "2"
Esempio n. 6
0
    def test_get_set_bool(self, cache: RedisCache):
        cache.set("bool", True)
        res = cache.get("bool")

        assert isinstance(res, bool)
        assert res is True

        cache.set("bool", False)
        res = cache.get("bool")

        assert isinstance(res, bool)
        assert res is False
Esempio n. 7
0
    def test_timeout_negative(self, cache: RedisCache):
        cache.set("test_key", 222, timeout=-1)
        res = cache.get("test_key")
        assert res is None

        cache.set("test_key", 222, timeout=None)
        cache.set("test_key", 222, timeout=-1)
        res = cache.get("test_key")
        assert res is None

        # nx=True should not overwrite expire of key already in db
        cache.set("test_key", 222, timeout=None)
        cache.set("test_key", 222, timeout=-1, nx=True)
        res = cache.get("test_key")
        assert res == 222
Esempio n. 8
0
def orderlist(request):
    token = request.session.get('token')
    userid = cache.get(token)
    user = User.objects.get(pk=userid)
    orders = user.order_set.all()
    # status_list = ['未付款', '待发货', '待收货', '待评价', '已评价']
    return render(request, 'order/orderlist.html', context={'orders': orders})
Esempio n. 9
0
    def test_expire_at(self, cache: RedisCache):

        # Test settings expiration time 1 hour ahead by datetime.
        cache.set("foo", "bar", timeout=None)
        expiration_time = datetime.datetime.now() + timedelta(hours=1)
        assert cache.expire_at("foo", expiration_time) is True
        ttl = cache.ttl("foo")
        assert pytest.approx(ttl, 1) == timedelta(hours=1).total_seconds()

        # Test settings expiration time 1 hour ahead by Unix timestamp.
        cache.set("foo", "bar", timeout=None)
        expiration_time = datetime.datetime.now() + timedelta(hours=2)
        assert cache.expire_at("foo", int(expiration_time.timestamp())) is True
        ttl = cache.ttl("foo")
        assert pytest.approx(ttl, 1) == timedelta(hours=1).total_seconds() * 2

        # Test settings expiration time 1 hour in past, which effectively
        # deletes the key.
        expiration_time = datetime.datetime.now() - timedelta(hours=2)
        assert cache.expire_at("foo", expiration_time) is True
        value = cache.get("foo")
        assert value is None

        expiration_time = datetime.datetime.now() + timedelta(hours=2)
        assert cache.expire_at("not-existent-key", expiration_time) is False
Esempio n. 10
0
 def test_touch_forever(self, cache: RedisCache):
     cache.set("test_key", "foo", timeout=1)
     result = cache.touch("test_key", None)
     assert result is True
     assert cache.ttl("test_key") is None
     time.sleep(2)
     assert cache.get("test_key") == "foo"
Esempio n. 11
0
    def process_request(self, request):
        # print('Hello')
        # print(request.path, request.META.get('REMOTE_ADDR'))
        if request.path == '/app/getphone/':
            if request.META.get('REMOTE_ADDR') == '10.0.118.85':
                r = random.randrange(10)
                if r > 5:
                    return HttpResponse('恭喜你抢到小米256')
                elif r > 2:
                    return HttpResponse('恭喜你抢到小米256')
                else:
                    return HttpResponse('正在排队')
            elif request.path == '/app/getticket/':
                if request.META.get('REMOTE ADDR') == '10.0.118.85':
                    return HttpResponse('下手慢了,没有了')
            elif request.path == '/app/search/':
                if request.method == 'POST':

                    result = cache.get(request.META.get('REMDTE_ADDR'))
                    if result:
                        return HttpResponse('小爬虫,不要爬了,我这没什么好玩的')
                    else:
                        cache.set(request.META.get('REMOTE_ADDR'),
                                  '这有好玩东西',
                                  timeout=15),
Esempio n. 12
0
def market(request, childid='0', sortid='0'):
    foodtypes = Foodtypes.objects.all()

    # 根据 分类ID 获取对应分类信息
    # goods_list = Goods.objects.all()[0:5]   #展示所有商品
    #默认打开热销榜(显示的商品应该过滤出是typeid是热销榜)
    # goods_list = Goods.objects.filter(categoryid=categoryid)

    #客户端需要记录点击分类的下标index[cookies  自动携带」
    #jquery.cookie.js 需要导包(里面有set.get cookie)在js文件中设置
    index = int(request.COOKIES.get('index', '0'))  #开始没有点击没有cookies 需要设置给默认值

    #根据index获取对应的分类ID
    categoryid = foodtypes[index].typeid  #下标要转为数字类型

    #根据分类id获取对应分类信息
    goods_list = Goods.objects.filter(categoryid=categoryid)

    #获取子类信息
    childtypenames = foodtypes[index].childtypenames

    #将对应子类拆分出来
    childtype_list = []  #存储子类列表信息
    for item in childtypenames.split('#'):
        # item >> 全部分类:0
        # item >> 子类名称: 子类id
        item_arr = item.split(':')
        temp_dir = {'name': item_arr[0], 'id': item_arr[1]}
        childtype_list.append(temp_dir)

    if childid == '0':
        goods_list = Goods.objects.filter(categoryid=categoryid)
    else:
        goods_list = Goods.objects.filter(categoryid=categoryid).filter(
            childcid=childid)

    #排序
    if sortid == '1':
        goods_list = goods_list.order_by('-productnum')
    elif sortid == '2':
        goods_list = goods_list.order_by('price')
    elif sortid == '3':
        goods_list = goods_list.order_by('-price')

    response_dir = {
        'foodtypes': foodtypes,
        'goods_list': goods_list,
        'childtype_list': childtype_list,
        'childid': childid,
    }

    #获取购物车信息(需先登录)
    token = request.session.get('token')
    userid = cache.get(token)  #根据token拿到用户
    if userid:
        user = User.objects.get(pk=userid)  #有用户就有购物车
        carts = user.cart_set.all()  #类似于object
        response_dir['carts'] = carts

    return render(request, 'market/market.html', context=response_dir)
Esempio n. 13
0
    def test_ttl_incr_version_no_timeout(self, cache: RedisCache):
        cache.set("my_key", "hello world!", timeout=None)

        cache.incr_version("my_key")

        my_value = cache.get("my_key", version=2)

        assert my_value == "hello world!"
Esempio n. 14
0
    def test_setnx(self, cache: RedisCache):
        # we should ensure there is no test_key_nx in redis
        cache.delete("test_key_nx")
        res = cache.get("test_key_nx")
        assert res is None

        res = cache.set("test_key_nx", 1, nx=True)
        assert bool(res) is True
        # test that second set will have
        res = cache.set("test_key_nx", 2, nx=True)
        assert res is False
        res = cache.get("test_key_nx")
        assert res == 1

        cache.delete("test_key_nx")
        res = cache.get("test_key_nx")
        assert res is None
Esempio n. 15
0
    def test_timeout_parameter_as_positional_argument(self, cache: RedisCache):
        cache.set("test_key", 222, -1)
        res = cache.get("test_key")
        assert res is None

        cache.set("test_key", 222, 1)
        res1 = cache.get("test_key")
        time.sleep(2)
        res2 = cache.get("test_key")
        assert res1 == 222
        assert res2 is None

        # nx=True should not overwrite expire of key already in db
        cache.set("test_key", 222, None)
        cache.set("test_key", 222, -1, nx=True)
        res = cache.get("test_key")
        assert res == 222
Esempio n. 16
0
    def test_save_float(self, cache: RedisCache):
        float_val = 1.345620002

        cache.set("test_key", float_val)
        res = cache.get("test_key")

        assert isinstance(res, float)
        assert res == float_val
Esempio n. 17
0
    def test_set_add(self, cache: RedisCache):
        cache.set("add_key", "Initial value")
        res = cache.add("add_key", "New value")
        assert res is False

        res = cache.get("add_key")
        assert res == "Initial value"
        res = cache.add("other_key", "New value")
        assert res is True
Esempio n. 18
0
    def dislike(self, request, pk, *args, **kwargs):

        comment = get_object_or_404(self.get_queryset().filter(pk=pk))
        cached_likers = cache.get('likers-{}'.format(comment.pk))

        if request.user.id in cached_likers:
            cached_likers.remove(request.user.id)
            cache.set('likers-{}'.format(comment.pk), cached_likers)

        return Response(status=status.HTTP_200_OK)
Esempio n. 19
0
    def test_setnx_timeout(self, cache: RedisCache):
        # test that timeout still works for nx=True
        res = cache.set("test_key_nx", 1, timeout=2, nx=True)
        assert res is True
        time.sleep(3)
        res = cache.get("test_key_nx")
        assert res is None

        # test that timeout will not affect key, if it was there
        cache.set("test_key_nx", 1)
        res = cache.set("test_key_nx", 2, timeout=2, nx=True)
        assert res is False
        time.sleep(3)
        res = cache.get("test_key_nx")
        assert res == 1

        cache.delete("test_key_nx")
        res = cache.get("test_key_nx")
        assert res is None
Esempio n. 20
0
    def like(self, request, pk, *args, **kwargs):

        comment = get_object_or_404(self.get_queryset().filter(pk=pk))

        redis_key_for_comment = 'likers-{}'.format(comment.pk)

        if not cache.has_key(redis_key_for_comment):
            cache.set(redis_key_for_comment, comment.liked_by)

        cached_likers = cache.get(redis_key_for_comment)

        if request.user.id not in cached_likers:
            cached_likers.append(request.user.id)
            cache.set(redis_key_for_comment, cached_likers)

        if len(cache.get(redis_key_for_comment)) % 10 == 0:
            comment.liked_by = cached_likers
            comment.save()

        return Response(status=status.HTTP_200_OK)
Esempio n. 21
0
    def get(self, request):
        # 接受到数据
        parent_id = request.GET.get('area_id')
        # 判断数据是否为空
        if parent_id is None:
            cache_pro = cache.get('cache_pro')

            if cache_pro is None:
                # 说明没有缓存
                # 拿到省份数据
                pro = Area.objects.filter(parent=None)
                # 将对象列表转换为字典列表
                # JsonResponse默认是可以对字典进行JSON转换的
                cache_pro = []
                for a in pro:
                    cache_pro.append({'id': a.id, 'name': a.name})

                # 设置缓存
                cache.set('cache_pro', cache_pro, 1)

            return http.JsonResponse({
                'code': RETCODE.OK,
                'province_list': cache_pro
            })

        else:
            # 获取缓存
            city_list = cache.get('city_%s' % parent_id)
            if city_list is None:
                # 根据省的ID查询市,得到的是查询集
                pro = Area.objects.get(id=parent_id)
                cities = pro.subs.all()

                city_list = []
                for a in cities:
                    city_list.append({'id': a.id, 'name': a.name})

                cache.set('city_%s' % parent_id, city_list, 24 * 3600)

            # 返回响应
            return http.JsonResponse({'code': RETCODE.OK, 'subs': city_list})
Esempio n. 22
0
    def test_decr(self, cache: RedisCache):
        if isinstance(cache.client, herd.HerdClient):
            pytest.skip("HerdClient doesn't support decr")

        cache.set("num", 20)

        cache.decr("num")
        res = cache.get("num")
        assert res == 19

        cache.decr("num", 20)
        res = cache.get("num")
        assert res == -1

        cache.decr("num", 2)
        res = cache.get("num")
        assert res == -3

        cache.set("num", 20)

        cache.decr("num")
        res = cache.get("num")
        assert res == 19

        # max 64 bit signed int + 1
        cache.set("num", 9223372036854775808)

        cache.decr("num")
        res = cache.get("num")
        assert res == 9223372036854775807

        cache.decr("num", 2)
        res = cache.get("num")
        assert res == 9223372036854775805
Esempio n. 23
0
    def test_incr_ignore_check(self, cache: RedisCache):
        if isinstance(cache.client, ShardClient):
            pytest.skip(
                "ShardClient doesn't support argument ignore_key_check to incr"
            )
        if isinstance(cache.client, herd.HerdClient):
            pytest.skip("HerdClient doesn't support incr")

        # key exists check will be skipped and the value will be incremented by
        # '1' which is the default delta
        cache.incr("num", ignore_key_check=True)
        res = cache.get("num")
        assert res == 1
        cache.delete("num")

        # since key doesnt exist it is set to the delta value, 10 in this case
        cache.incr("num", 10, ignore_key_check=True)
        res = cache.get("num")
        assert res == 10
        cache.delete("num")

        # following are just regression checks to make sure it still works as
        # expected with incr max 64 bit signed int
        cache.set("num", 9223372036854775807)

        cache.incr("num", ignore_key_check=True)
        res = cache.get("num")
        assert res == 9223372036854775808

        cache.incr("num", 2, ignore_key_check=True)
        res = cache.get("num")
        assert res == 9223372036854775810

        cache.set("num", 3)

        cache.incr("num", 2, ignore_key_check=True)
        res = cache.get("num")
        assert res == 5
Esempio n. 24
0
def mine(request):
    token = request.session.get('token')
    userid = cache.get(token)
    response_data = {'user': None}
    if userid:
        user = User.objects.get(pk=userid)
        response_data['user'] = user

        orders = user.order_set.all()
        # 待付款
        response_data['waitpay'] = orders.filter(status=0).count()
        # 待发货
        response_data['paydone'] = orders.filter(status=1).count()

    return render(request, 'mine/mine.html', context=response_data)
Esempio n. 25
0
def verify(req):
    if req.method == "GET":
        return render(req, 'templates/t8/verify.html')
    else:
        params = req.POST
        email = params.get("email")
        #生成随机字符
        random_str = get_random_str()
        #拼接
        url = "127.0.0.1:8000/t8/active" + random_str
        #加载激活模板
        tem = loader.get_template("templates/t8/active.html")
        #渲染模板
        html_str = tem.render({'url': url})
        title = "磊磊加油哇"
        msg = ""
        email_from = settings.DEFAULT_FROM_EMAIL
        reciever = [
            '*****@*****.**',
        ]
        #增加缓存
        send_mail(title, msg, email_from, reciever, html_message=html_str)
        cache.get(random_str, email, 120)
        return HttpResponse("ok")
Esempio n. 26
0
def subcart(request):
    goodsid = request.GET.get('goodsid')  #获取ajax请求参数
    goods = Goods.objects.get(pk=goodsid)  #通过商品id获取商品

    #用户  #减用户已经登录
    token = request.session.get('token')
    userid = cache.get(token)
    user = User.objects.get(pk=userid)

    #获取对应的购物车信息
    cart = Cart.objects.filter(user=user).filter(goods=goods).first()
    cart.number = cart.number - 1
    cart.save()

    print((goodsid))
    response_data = {'msg': '删减成功', 'status': 1, 'number': cart.number}
    return JsonResponse(response_data)
Esempio n. 27
0
    def test_save_dict(self, cache: RedisCache):
        if isinstance(cache.client._serializer,
                      (JSONSerializer, MSGPackSerializer)):
            # JSONSerializer and MSGPackSerializer use the isoformat for
            # datetimes.
            now_dt: Union[
                str, datetime.datetime] = datetime.datetime.now().isoformat()
        else:
            now_dt = datetime.datetime.now()

        test_dict = {"id": 1, "date": now_dt, "name": "Foo"}

        cache.set("test_key", test_dict)
        res = cache.get("test_key")

        assert isinstance(res, dict)
        assert res["id"] == 1
        assert res["name"] == "Foo"
        assert res["date"] == now_dt
Esempio n. 28
0
def changecartall(request):
    isall = request.GET.get('isall')

    token = request.session.get('token')
    userid = cache.get(token)
    user = User.objects.get(pk=userid)
    carts = user.cart_set.all()

    if isall == 'true':
        isall = True
    else:
        isall = False

    for cart in carts:
        cart.isselect = isall
        cart.save()

    response_data = {'msg': '全选/取消全选 成功', 'status': 1}

    return JsonResponse(response_data)
Esempio n. 29
0
def addcart(request):
    # 获取token
    token = request.session.get('token')

    # 响应数据
    response_data = {}

    # 缓存
    if token:
        userid = cache.get(token)
        # print(userid)    #获取用户id
        if userid:  # 已经登录
            user = User.objects.get(pk=userid)
            goodsid = request.GET.get('goodsid')
            goods = Goods.objects.get(pk=goodsid)
            # print(user,goodsid)  #点击商品后查看是否能获取对应id
            # 商品不存在: 添加新记录  商品存在: 修改number
            carts = Cart.objects.filter(user=user).filter(goods=goods)
            if carts.exists():
                cart = carts.first()
                cart.number = cart.number + 1
                cart.save()
            else:
                cart = Cart()
                cart.user = user
                cart.goods = goods
                cart.number = 1
                cart.save()

            response_data['status'] = 1  #添加成功
            response_data['number'] = cart.number
            response_data['msg'] = '添加 {} 购物车成功: {}'.format(
                cart.goods.productlongname, cart.number)

            return JsonResponse(response_data)
            # return HttpResponse('添加商品到购物车')
    response_data['status'] = -1  #未登录状态
    response_data['msg'] = '请登录后操作'
    return JsonResponse(response_data)
Esempio n. 30
0
def generateorder(request):
    token = request.session.get('token')
    userid = cache.get(token)
    user = User.objects.get(pk=userid)

    # 订单
    order = Order()
    order.user = user
    order.identifier = generate_identifier()
    order.save()

    # 订单商品(购物车中选中)
    carts = user.cart_set.filter(isselect=True)
    for cart in carts:
        orderGoods = OrderGoods()
        orderGoods.order = order
        orderGoods.goods = cart.goods
        orderGoods.number = cart.number
        orderGoods.save()
        # 购买后从购物车中移除
        cart.delete()

    return render(request, 'order/orderdetail.html', context={'order': order})