def login(request): if request.method == 'GET': return render(request, 'mine/login.html') elif request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') back = request.COOKIES.get('back') #重定向位置 print(back) user = User.objects.filter(email=email) if user.exists(): user = user.first() if user.password == generate_password(password): token = generate_token() #更新token cache.set(token, user.id, 60 * 60 * 24 * 3) #状态保持 #传递客户端 request.session['token'] = token # return redirect('axf:mine') if back == 'mine': return redirect('axf:mine') else: return redirect('axf:marketbase') else: return render(request, 'mine/login.html', context={'ps_err': '密码错误'}) else: return render(request, 'mine/login.html', context={'user_err': '用户不存在'})
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
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
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
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"
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
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),
def test_set_call_empty_pipeline(self, cache: RedisCache, mocker: MockerFixture): if isinstance(cache.client, ShardClient): pytest.skip("ShardClient doesn't support get_client") pipeline = cache.client.get_client(write=True).pipeline() key = "key" value = "value" mocked_set = mocker.patch.object(pipeline, "set") cache.set(key, value, client=pipeline) if isinstance(cache.client, herd.HerdClient): default_timeout = cache.client._backend.default_timeout herd_timeout = (default_timeout + herd.CACHE_HERD_TIMEOUT) * 1000 herd_pack_value = cache.client._pack(value, default_timeout) mocked_set.assert_called_once_with( cache.client.make_key(key, version=None), cache.client.encode(herd_pack_value), nx=False, px=herd_timeout, xx=False, ) else: mocked_set.assert_called_once_with( cache.client.make_key(key, version=None), cache.client.encode(value), nx=False, px=cache.client._backend.default_timeout * 1000, xx=False, )
def test_persist(self, cache: RedisCache): cache.set("foo", "bar", timeout=20) assert cache.persist("foo") is True ttl = cache.ttl("foo") assert ttl is None assert cache.persist("not-existent-key") is False
def test_pexpire(self, cache: RedisCache): cache.set("foo", "bar", timeout=None) assert cache.pexpire("foo", 20500) is True ttl = cache.pttl("foo") # delta is set to 10 as precision error causes tests to fail assert pytest.approx(ttl, 10) == 20500 assert cache.pexpire("not-existent-key", 20500) is False
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!"
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
def test_delete_pattern_with_custom_count(self, client_mock, cache: RedisCache): for key in ["foo-aa", "foo-ab", "foo-bb", "foo-bc"]: cache.set(key, "foo") cache.delete_pattern("*foo-a*", itersize=2) client_mock.delete_pattern.assert_called_once_with("*foo-a*", itersize=2)
def test_delete_return_value_type_new31(self, cache: RedisCache): """delete() returns a boolean instead of int since django version 3.1""" cache.set("a", 1) res = cache.delete("a") assert isinstance(res, bool) assert res is True res = cache.delete("b") assert isinstance(res, bool) assert res is False
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
def test_delete_return_value_type_before31(self, cache: RedisCache): """delete() returns a int before django version 3.1""" cache.set("a", 1) res = cache.delete("a") assert isinstance(res, int) assert res == 1 res = cache.delete("b") assert isinstance(res, int) assert res == 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)
def test_delete_pattern_with_settings_default_scan_count( self, client_mock, cache: RedisCache): for key in ["foo-aa", "foo-ab", "foo-bb", "foo-bc"]: cache.set(key, "foo") expected_count = django_redis.cache.DJANGO_REDIS_SCAN_ITERSIZE cache.delete_pattern("*foo-a*") client_mock.delete_pattern.assert_called_once_with( "*foo-a*", itersize=expected_count)
def test_delete_pattern(self, cache: RedisCache): for key in ["foo-aa", "foo-ab", "foo-bb", "foo-bc"]: cache.set(key, "foo") res = cache.delete_pattern("*foo-a*") assert bool(res) is True keys = cache.keys("foo*") assert set(keys) == {"foo-bb", "foo-bc"} res = cache.delete_pattern("*foo-a*") assert bool(res) is False
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"
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
def test_pttl(self, cache: RedisCache): # Test pttl cache.set("foo", "bar", 10) ttl = cache.pttl("foo") # delta is set to 10 as precision error causes tests to fail if isinstance(cache.client, herd.HerdClient): assert pytest.approx(ttl, 10) == 12000 else: assert pytest.approx(ttl, 10) == 10000 # Test pttl with float value cache.set("foo", "bar", 5.5) ttl = cache.pttl("foo") if isinstance(cache.client, herd.HerdClient): assert pytest.approx(ttl, 10) == 7500 else: assert pytest.approx(ttl, 10) == 5500 # Test pttl None cache.set("foo", "foo", timeout=None) ttl = cache.pttl("foo") assert ttl is None # Test pttl with expired key cache.set("foo", "foo", timeout=-1) ttl = cache.pttl("foo") assert ttl == 0 # Test pttl with not existent key ttl = cache.pttl("not-existent-key") assert ttl == 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
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
def register(request): if request.method == 'GET': return render(request, 'mine/register.html') elif request.method == 'POST': email = request.POST.get('email') password = generate_password(request.POST.get('password')) name = request.POST.get('name') user = User() user.email = email user.password = password user.name = name user.save() token = generate_token() cache.set(token, user.id, 60 * 60 * 24 * 3) request.session['token'] = token return render(request, 'mine/mine.html')
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
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
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)
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})
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