Пример #1
0
 def increment_clicks(ruleset_id, day=False, segment_id=False):
     from django.core.cache import cache
     key = RuleSet.clicks_key(ruleset_id, day, segment_id)
     if not cache.get(key): cache.set(key, 0)
     i = cache.incr(key, 1)
     cache.expire(key, 60*60*24*7)
     return i
Пример #2
0
    def _acquire_token() -> str:
        """ Validate token exists or refresh it """
        secret_ttl = cache.ttl('YSK_secret')
        if secret_ttl is None:
            cache.expire('YSK_secret', timeout=0)
        if secret_ttl > 0:
            return cache.get('YSK_secret')
        try:
            resp = requests.post(
                settings.YSK_IAM_BEARER_PULL_URL,
                params={
                    'yandexPassportOauthToken': settings.YSK_BEARER_PULL_SECRET
                },
                timeout=10,
            )
        except requests.Timeout:
            raise exc.TTSBackendIsUnavailable(
                'Yandex speech kit API is unavailable, '
                'please try again later')
        if not resp.status_code == 200:
            raise requests.HTTPError('Undefined error. Please try again.')

        token = json.loads(resp.text)['iamToken']
        cache.set('YSK_secret', token, timeout=42000)
        return token
Пример #3
0
 def invalidate_cache(self, solution=None):
     if solution is None:
         cache.delete_pattern("{}_validate*".format(self.pk))
     else:
         cache.expire("{}_validate".format(self.pk), timeout=0)
         cache.expire("{}_validate_{}".format(self.pk, solution.pk),
                      timeout=0)
 def update(self, id, **kwargs):
     channel_id = int(kwargs.get("channel_id", "0"))
     if models.ActivityChannel.objects.filter(id=channel_id).count() <= 0:
         raise error.MessageError("channel_id invalid")
     cache.expire(cache_key_def.REDIS_KEY_API_ACITITY_DETAIL_ID % (id),
                  timeout=0)
     return models.Activity.objects.filter(id=id).update(**kwargs)
Пример #5
0
def AppFindPwd(request, account, captcha):
    #     print "find pwd first", account, captcha
    if not account or not captcha:
        return HttpReturn(ArgError)

    mycaptcha = request.session.pop(request.COOKIES.get(G_CSRFTOKEN), None)
    if not mycaptcha or cmp(mycaptcha, captcha):
        return HttpReturn(CaptchaError)

    try:
        accobj = AppUser.objects.raw(
            'SELECT * FROM user_manager_appuser where uname = %s OR email = %s  OR phone= %s',
            [account, account, account])[0]
    except:
        return HttpReturn(UserNotExists)
    else:

        if not accobj:
            return HttpReturn(TargetNotExists)

        smscode = hashlib.md5(accobj.phone +
                              str(time.time())).hexdigest().upper()
        ipaddr = request.META.get(G_REMOTE_ADDR)
        redis_pool.hmset(smscode, {G_PHONE: accobj.phone, G_IPADDR: ipaddr})
        redis_pool.expire(smscode, settings.SESSION_COOKIE_AGE)

        res = {
            'name': accobj.uname,
            G_PHONE: "%s****%s" % (accobj.phone[:3], accobj.phone[-4:]),
            G_SMSCODE: smscode,
            G_OK: True
        }
        return HttpReturn(json.dumps(res))
Пример #6
0
def room_leave(message):
    # Reverse of join - remove them from everything.
    room = get_room_or_error(message["room"])

    room.websocket_group.discard(message.reply_channel)
    #message.channel_session['room'] = list(set(message.channel_session['room']).difference([room.label]))
    # Send a message back that will prompt them to close the room
    message.reply_channel.send({
        "text":
        json.dumps({
            "leave": str(room.label),
        }),
    })

    curr_tot = cache.get(message["room"])
    if not curr_tot:
        curr_tot = 1
    if curr_tot and curr_tot < 2:
        cache.expire(message["room"], timeout=0)
    else:
        cache.set(message["room"], curr_tot - 1, timeout=7200)

    Group(message["room"]).send({
        "text":
        json.dumps({
            "count_user": curr_tot - 1,
        }),
    })
Пример #7
0
def get_slide(message):
    room = get_room_or_error(message["room"])
    slide = Slide.objects.get(room=room, now_id=message["id"])
    hash_blob = javaHash(slide.md_blob)

    if cache.ttl("%s/%s" % (message["room"], message["id"])) == 0:
        cache.set("%s/%s" % (message["room"], message["id"]),
                  slide.md_blob,
                  timeout=60)
        cache.set("%s/%s/%s" % (message["room"], message["id"], hash_blob),
                  slide.md_blob,
                  timeout=60)
    else:
        cache.expire("%s/%s" % (message["room"], message["id"]), timeout=60)
        cache.expire("%s/%s/%s" % (message["room"], message["id"], hash_blob),
                     timeout=60)

    message.reply_channel.send({
        "text":
        json.dumps({
            "get_slide": message["id"],
            "md_blob": slide.md_blob,
            "title": slide.title,
            "idx": slide.now_id,
        }),
    })
Пример #8
0
 def save(cls, key, obj):
     """
     保存图形验证码
     :return:
     """
     cache.set(key, obj)
     cache.expire(key, Constants.REDIS_EXPIRE_TIME)
Пример #9
0
def cheungssh_login(request):
    info = {"msgtype": "ERR", "content": "", "auth": "no"}
    logintime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
    client_ip = request.META['REMOTE_ADDR']
    limit_ip = 'fail.limit.%s' % (client_ip)
    ip_threshold_r = cache.get('ip.threshold')
    ip_threshold = lambda x: x if x is not None else 4
    ip_threshold = ip_threshold(ip_threshold_r)
    if cache.has_key(limit_ip):
        if cache.get(limit_ip) > ip_threshold:
            info['content'] = "无效登陆"
            cache.incr(limit_ip)
            cache.expire(limit_ip, 8640000)
            info = json.dumps(info)
            return HttpResponse(info)
    if request.method == "POST":
        username = request.POST.get("username", '非法用户名')
        password = request.POST.get("password", False)
        print username, password, request.POST
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                print "成功登陆"

                login(request, user)
                request.session["username"] = username
                info["msgtype"] = "OK"
                info['auth'] = "yes"
                info['content'] = "成功登录"
                request.session.set_expiry(0)
                if cache.has_key(limit_ip): cache.delete(limit_ip)
                print request.COOKIES, request.session.keys(
                ), request.session['_auth_user_id']
                info['sid'] = str(request.session.session_key)
            else:

                info["content"] = "用户状态无效"
                print info["content"]
        else:
            if cache.has_key(limit_ip):
                cache.incr(limit_ip)
            else:
                cache.set(limit_ip, 1, 3600)
            info["content"] = "用户名或密码错误"
        info["IP"] = client_ip
        info["IP-Locate"] = IP.find(client_ip)
        info["username"] = username
        info["logintime"] = logintime
        redis_to_redis.set_redis_data(
            'sign.record',
            json.dumps(info, encoding='utf-8', ensure_ascii=False))

    else:
        info["content"] = "No Get"
    info = json.dumps(info, encoding="utf-8", ensure_ascii=False)
    response = HttpResponse(info)
    response["Access-Control-Allow-Origin"] = "*"
    response["Access-Control-Allow-Methods"] = "POST"
    response["Access-Control-Allow-Credentials"] = "true"
    return response
Пример #10
0
def sendMsg(req):
    if req.method=='POST':
        data = json.loads(req.POST.get("data"))
        send_to =data["to"]
        if send_to not in GLOBAL_MQ:
            GLOBAL_MQ[send_to] = Queue.Queue()
        data['timestamp']=time.strftime("%H:%M:%S", time.localtime())
        GLOBAL_MQ[send_to].put(data)
        return HttpResponse(GLOBAL_MQ[send_to].qsize())
    else:
        #from customer Care 's GetNewMsgs
        msg_lists=[]
        request_user=str(req.COOKIES.get('SealadminID',''))
        cache.expire(req.COOKIES.get('SealadminID',''),60)
        if request_user in GLOBAL_MQ:
            stored_msg_nums=GLOBAL_MQ[request_user].qsize()
            if stored_msg_nums==0:#no new msg
                try:
                    msg_lists.append(GLOBAL_MQ[request_user].get(timeout=15))
                except Exception as e:
                    # there print the err first
                    print ("err",e)
            for i in range(stored_msg_nums):
                msg_lists.append(GLOBAL_MQ[request_user].get())
        else:
            # creat a new queue
            GLOBAL_MQ[str(req.COOKIES.get('SealadminID',''))]=Queue.Queue()
        return HttpResponse(json.dumps(msg_lists))
 def login_huawei_fusion_compute(self, huawei_env):
     try:
         url = huawei_env.get('hw_address') + LOGIN_URI
         passwd_sha = hashlib.sha256(
             huawei_env.get('hw_password').encode('utf-8')).hexdigest()
         headers = {
             "Accept-Language": "zh_CN",
             "X-ENCRIPT-ALGORITHM": "0",
             "X-Auth-UserType": "0",
             "X-Auth-User": huawei_env.get('hw_username'),
             "X-Auth-Key": passwd_sha,
             "Content-Type": "application/json; charset=UTF-8",
             "Accept": "application/json;version=v6.3;charset=UTF-8"
         }
         res = requests.post(url=url,
                             headers=headers,
                             verify=False,
                             timeout=60)
         result = res.json()
         res_headers = res.headers
         result['token'] = res_headers['X-Auth-Token']
         # 将token存cache
         cache.set(
             huawei_env.get('Host') + huawei_env.get('hw_address') +
             huawei_env.get('hw_username') + 'token',
             res_headers['X-Auth-Token'], 60)
         cache.expire(
             huawei_env.get('Host') + huawei_env.get('hw_address') +
             huawei_env.get('hw_username') + 'token', 600)
         return result
     except Exception as e:
         logger.info("华为云登录失败:{error}!".format(error=e))
Пример #12
0
def expire_cache(id):
    """
    Expire cache key. Exceptions handled by decorator.
    :param id: key
    :return: None
    """
    logger.debug("Set expiration for id %s" % id)
    cache.expire(id, 0)
Пример #13
0
def setPassportCache(key, value, timeout=0, isexpire=False):
    key = "cm-%s" % key
    try:
        cache.set(key, value)
        if isexpire:
            cache.expire(key, timeout)
    except:
        pass
Пример #14
0
def expire_cache(id):
    """
    Expire cache key. Exceptions handled by decorator.
    :param id: key
    :return: None
    """
    logger.debug("Set expiration for id %s" %id)
    cache.expire(id, 0)
 def create(self, **kwargs):
     name = kwargs.get("name")
     if models.ActivityChannel.objects.filter(name=name).count() > 0:
         raise error.MessageError("channel name duplicated")
     cache.expire(cache_key_def.REDIS_KEY_API_CHANNEL_GET_ALL, timeout=0)
     cache.expire(cache_key_def.REDIS_KEY_API_CHANNEL_DICT, timeout=0)
     ret = models.ActivityChannel.objects.create(**kwargs)
     return ret
Пример #16
0
 def get_context_data(self, **kwargs):
     kwargs = super().get_context_data(**kwargs)
     cache_key = f"qrimgurlhash:{kwargs['hashed']}"
     data = cache.get(cache_key)
     if not isinstance(data, dict):
         raise Http404
     cache.expire(cache_key, timeout=60 * 5)
     kwargs.update(**data)
     return kwargs
Пример #17
0
def delsingle_CR(session,fnames):
    print("del ",fnames)
    for fname in fnames:
        if session.get("work_book") and session["work_book"].filename==fname:
            del session["work_book"]
        elif cache.has_key(session["user_name"]+"::"+fname):
            cache.expire(session["user_name"]+"::"+fname,0)
        else:
            print("没有该文件的图表")
Пример #18
0
def get_access_token():
    print(str(datetime.datetime.now()) + " get_access_token")
    response = requests.get(
        f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={settings.APPID}&secret={settings.SECRET}'
    )
    response = response.json()
    if response.get('access_token', ''):
        cache.set('access_token', response['access_token'])
        cache.expire('access_token', response['expires_in'])
 def delete(self, id):
     if models.Activity.objects.filter(channel_id=id).count() > 0:
         raise error.MessageError(
             "this channel is configured in the activities, can't deleted directly"
         )
     cache.expire(cache_key_def.REDIS_KEY_API_CHANNEL_GET_ALL, timeout=0)
     cache.expire(cache_key_def.REDIS_KEY_API_CHANNEL_DICT, timeout=0)
     ret = models.ActivityChannel.objects.filter(id=id).delete()
     return ret
Пример #20
0
def cheungssh_login(request):
	info={"msgtype":"ERR","content":"","auth":"no"}
	logintime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
	client_ip=request.META['REMOTE_ADDR']
	limit_ip='fail.limit.%s'%(client_ip)
	ip_threshold_r=cache.get('ip.threshold')  
	ip_threshold=lambda x:x if x is not None else 4 
	ip_threshold=ip_threshold(ip_threshold_r)
	if cache.has_key(limit_ip):
		if cache.get(limit_ip)>ip_threshold:  
			info['content']="无效登陆"
			cache.incr(limit_ip)  
			cache.expire(limit_ip,8640000)
			info=json.dumps(info)
			return HttpResponse(info)
	if request.method=="POST":
		username = request.POST.get("username", '非法用户名')
		password = request.POST.get("password", False)
		print username,password,request.POST
		user=authenticate(username=username,password=password)
		if user is not None:
			if user.is_active:
				print "成功登陆"
				
				login(request,user)
				request.session["username"]=username
				info["msgtype"]="OK"
				info['auth']="yes"
				info['content']="成功登录"
				request.session.set_expiry(0)    
				if cache.has_key(limit_ip):cache.delete(limit_ip)
				print request.COOKIES,request.session.keys(),request.session['_auth_user_id']
				info['sid']=str(request.session.session_key)
			else:
				
				info["content"]="用户状态无效"
				print info["content"]
		else:
			if cache.has_key(limit_ip):
				cache.incr(limit_ip)
			else:
				cache.set(limit_ip,1,3600)
			info["content"]="用户名或密码错误"
		info["IP"]=client_ip
		info["IP-Locate"]=IP.find(client_ip)
		info["username"]=username
		info["logintime"]=logintime
		redis_to_redis.set_redis_data('sign.record',json.dumps(info,encoding='utf-8',ensure_ascii=False)) 
		
	else:
		info["content"]="No Get"
	info=json.dumps(info,encoding="utf-8",ensure_ascii=False)
	response=HttpResponse(info)
	response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Methods"] = "POST"
        response["Access-Control-Allow-Credentials"] = "true"
        return response
Пример #21
0
    def get(self, request, *args, **kwargs):
        redis_key = "archive_cache"
        redis_value = cache.get(redis_key)
        if redis_value:
            print("hit cache")
            serializer_archives = json.loads(redis_value)
            archive_list = []
            article_count = 0
            for archive in serializer_archives:
                # 为了模板可以正常渲染, 需要将article反序列化为对象
                archive_list.append({
                    "year":
                    archive['year'],
                    "article_list": [
                        obj.object for obj in serializers.deserialize(
                            'json', archive['article_list'])
                    ]
                })
                article_count += len(archive['article_list'])

            context = {
                "archive_list": archive_list,
                "article_count": article_count
            }
        else:
            article_list = Article.objects.all()

            archive_dict = {}
            for article in article_list:
                year = article.create_time.strftime("%Y")
                # 如果当前字典没有目标key, 则给定默认值
                # 如果当前字典有目标key, 则无变化
                archive_dict.setdefault(year, {
                    "year": year,
                    "article_list": []
                })
                archive_dict[year]['article_list'].append(article)

            context = {
                "archive_list": archive_dict.values(),
                "article_count": len(article_list)
            }

            # 缓存archive_list
            serializer_archives = []
            for archive in archive_dict.values():
                serializer_archives.append({
                    "year":
                    archive['year'],
                    "article_list":
                    serializers.serialize("json", archive['article_list'])
                })
            cache.set(redis_key, json.dumps(serializer_archives))
            cache.expire(redis_key, 60)

        return self.render_to_response(context)
 def delete(self, id):
     if models.Participate.objects.filter(activity_id=id).count() > 0:
         raise error.MessageError(
             "this activity has participators, can't deleted directly")
     if models.Comment.objects.filter(activity_id=id).count() > 0:
         raise error.MessageError(
             "this activity has comments, can't deleted directly")
     cache.expire(cache_key_def.REDIS_KEY_API_ACITITY_DETAIL_ID % (id),
                  timeout=0)
     return models.Activity.objects.filter(id=id).delete()
Пример #23
0
 def post(self, request, format=None):
     data = request.data
     serializer = RegisterCodeSerializer(data=data)
     if serializer.is_valid(raise_exception=True):
         username = data['username']
         code = random.randint(1000, 9999)
         celery_send_verify_code.delay(username, code)
         cache.set(CACHE_REGISTER.format(username=username), code)
         cache.expire(CACHE_REGISTER.format(username=username), timeout=60)
         return Response(serializer.data, status=HTTP_200_OK)
     return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
Пример #24
0
 def authenticate(self, request):
     ret = {'code': 1000, 'message': None, 'error': None}
     token = request._request.GET.get('token')
     username = cache.get(token)
     #   更新token的缓存时间
     if username:
         cache.expire(token, username)
         user = User.objects.get(username=username)
     else:
         raise exceptions.AuthenticationFailed('用户认证失败')
     return user, token
Пример #25
0
 def post(self, request, *args, **kwargs):
     expire_time = 60 * 60 * 2
     token = request.data.get('token')
     cache.expire(token, timeout=expire_time)
     data = {
         "status": 200,
         "msg": "token过期时间已刷新",
         "results": {
             "token_expire_time": expire_time
         }
     }
     return Response(data)
Пример #26
0
def select_to_cache(email):
    ss = cache.get(email)
    if ss == None:
        cache.set(email, 0)
        cache.expire(email, 86400)
        res = 0
        return res
    else:
        res = cache.get(email) + 1
        cache.set(email, res)
        cache.expire(email, 86400)
        return res
Пример #27
0
 def authenticate_credentials(self, key):
     token_key = "{}:{}".format(self.token_prefix, key)
     try:
         user_id = cache.get(token_key)
         user = UserModel.objects.get(id=user_id)
     except UserModel.DoesNotExist:
         raise exceptions.AuthenticationFailed("Invalid token.")
     if not user.is_active:
         raise exceptions.AuthenticationFailed("User inactive")
     # 刷新临时token的过期时间
     cache.expire(token_key, self.timeout)
     return user, key
Пример #28
0
    def retrieve(self, request):
        try:
            body = None
            username = str(request.GET.get("username"))
            users = PitchUser.objects.filter(username=username)
            if users.count() > 0:
                seed = '23456789abcdefghijkmnpqrstuvwxyz'
                checkcode = ''.join(random.choice(seed) for _ in range(6))
                # 将验证信息写入redis
                retrieve_key = "retrieve_%s" % username
                cache.set(retrieve_key, checkcode, nx=True)
                cache.expire(retrieve_key, 300)
                user = users[0]
                email = user.email
                msg = MIMEText(
                    '验证码:' + checkcode + '(请不要泄漏给任何人,验证码将用来重设密码, 5分钟内有效。)',
                    'plain', 'utf-8')
                msg['Subject'] = "古琴数据库验证码" + checkcode
                msg['From'] = self.msg_from
                msg['To'] = email
                self.sender = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 邮件服务器及端口号
                self.sender.login(self.msg_from, self.passwd)
                self.sender.sendmail(self.msg_from, email, msg.as_string())
                email = email[0:5] + "***" + email[-8:]
                body = {"email": email}
                result = {
                    "status": "success",
                    "username": str(request.user),
                    "tip": "获取邮箱缩略信息成功",
                    "body": body
                }
                return JsonResponse(result)
            else:
                WebView.logger.error(e)
                result = {
                    "status": "failure",
                    "username": str(request.user),
                    "tip": "用户名不存在"
                }
                return JsonResponse(result)

        except Exception as e:
            WebView.logger.error(e)
            result = {
                "status": "failure",
                "username": str(request.user),
                "tip": "获取邮箱缩略新信息错误"
            }
            return JsonResponse(result)
Пример #29
0
    def wrapper(request, account, pwd):
        sessionid = request.COOKIES.get(G_SESSIONID, None)
        resdict = redis_pool.hgetall(sessionid)
        addr = request.META.get(G_REMOTE_ADDR)

        if sessionid and resdict and (addr == resdict[G_IPADDR]) \
                and (G_ACCOUNT in resdict) and (account in resdict[G_ACCOUNT]):
            #             print "get return from redis "
            #             print "you cookies ",request.COOKIES
            d = json.loads(resdict["res"])
            d["time"] = str(int(time.time()))
            redis_pool.expire(sessionid, settings.SESSION_COOKIE_AGE)
            return HttpReturn(json.dumps(d))
        else:
            return func(request, account, pwd)
Пример #30
0
 def __call__(self, request):
     ip = self.get_client_ip(request)
     if not settings.DEBUG and cache.get(f'island/blocked/{ip}'):
         return permission_denied(request, Exception('You are blocked due to suspicious operations.'))
     response = self.get_response(request)
     if 400 <= response.status_code < 500:
         key = f'island/suspicious/{ip}'
         cache.set(key, 0, nx=True)
         cache.incr(key)
         cache.expire(key, timeout=settings.SUSPICIOUS_BLOCK_TIMEOUT)
         if cache.get(key, 0) >= settings.SUSPICIOUS_BLOCK_FREQUENCY:
             BlockedAddress.objects.get_or_create(ip=ip)
             cache.set(f'island/blocked/{ip}', True)
             cache.delete(key)
     return response
Пример #31
0
    def update_comments_in_cache(self, related_task_id, new_data):
        
        comment_data = cache.get(self.key + str(related_task_id))
        key = self.key + str(related_task_id)

        if comment_data is None:
            cache.set(key, new_data, self.ttl)
        
        else:
            comment_data.append(new_data)
            cache.set(key, comment_data, self.ttl)
        
        cache.expire(key, self.ttl)

        return comment_data or new_data
Пример #32
0
    def __call__(self, request):
        if request.user.is_authenticated:

            user_id = request.user.id
            ttl = settings.CACHE_TTL

            # refresh user's cache
            cache.expire(user_id, timeout=ttl * 60)

            response = self.get_response(request)

        else:
            response = self.get_response(request)

        print(response.cookies)
        return response
Пример #33
0
def obtain_token(user):
    """
    生成/获取Token, 并保存至Cache中
    """
    token, created = Token.objects.get_or_create(user=user)
    if not created and TOKEN_TMOUT > 0:
        token_life = timezone.now() - token.created
        if token_life.total_seconds() > TOKEN_TMOUT:
            token.delete()
            token = Token.objects.create(user=user)
    # 缓存处理
    cache_key = "username:token:%s" % token.key
    cache.set(cache_key, str(user.username), TIMEOUT)
    if TOKEN_TMOUT > 0:
        cache.expire(cache_key, TOKEN_TMOUT)
    return token
Пример #34
0
def cheungssh_login(request):
	info={"msgtype":"ERR","content":"","auth":"no"}
	client_ip=request.META['REMOTE_ADDR']
	limit_ip='fail.limit.%s'%(client_ip)
	if cache.has_key(limit_ip):
		if cache.get(limit_ip)>4:
			print '该用户IP已经被锁定'
			info['content']="无效登陆"
			cache.incr(limit_ip)
			cache.expire(limit_ip,8640000)
			info=json.dumps(info)
			return HttpResponse(info)
	if request.method=="POST":
		username = request.POST.get("username", False)
		password = request.POST.get("password", False)
		print username,password,request.POST
		user=authenticate(username=username,password=password)
		if user is not None:
			if user.is_active:
				print "成功登陆"
				login(request,user)
				request.session["username"]=username
				info["msgtype"]="OK"
				info['auth']="yes"
				request.session.set_expiry(0)
				if cache.has_key(limit_ip):cache.delete(limit_ip)
				print request.COOKIES,request.session.keys(),request.session['_auth_user_id']
				info['sid']=str(request.session.session_key)
			else:
				
				info["content"]="用户状态无效"
				print info["content"]
		else:
			if cache.has_key(limit_ip):
				cache.incr(limit_ip)
			else:
				cache.set(limit_ip,1,3600)
			info["content"]="用户名或密码错误"
			print info["content"]
			
			
	else:
		try:
			info["content"]="No Get"
		except Exception,e:
			print '错误',e
Пример #35
0
def balance_change_callback(sender, instance, **kwargs):
    active = bool(instance.value > 0)
    now = datetime.now()
    date = now.replace(second=0, microsecond=0, minute=0, hour=0)
    cache_key = '%s:%d:%d' % (SPENT_LAST_DAY_PREFIX, now.day, instance.client.id)
    money_sum = cache.get(cache_key)
    if not money_sum:
        money_sum = BalanceHistory.objects.filter(balance__client=instance.client,
                                  created__gte=date - timedelta(days=1),
                                  created__lt=date).aggregate(Sum('change_value'))
        money_sum = money_sum['change_value__sum']
        cache.set(cache_key, money_sum)
        cache.expire(cache_key, timeout=60*60*24)
    if money_sum and money_sum * 3 > instance.value and money_sum > 1000:
        EmailDelivery.objects.make(
            template='client/balance_limit.html',
            email=instance.client.user.email,
            context={'balance': instance.value},
        )
        if instance.client.operator:
            EmailDelivery.objects.make(
                template='client/balance_limit.html',
                email=instance.client.operator.user.email,
                context={'balance': instance.value, 'client': instance.client},
            )
        instance.client.limit_balance_email_send = True
    if money_sum is not None and money_sum <= 0:
        EmailDelivery.objects.make(
            template='client/balance_zero.html',
            email=instance.client.user.email,
            context={'balance': instance.value},
        )
        instance.client.zero_balance_email_send = True
    if (instance.client.is_active != active):
        # shops = Shop.objects.filter(user=instance.client.user)
        # status = Shop.ENABLED if active else Shop.DISABLED
        # shops.update(status=status)
        instance.client.is_active = active
    instance.client.save()
Пример #36
0
	return render_to_response("cheungssh.html")
def cheungssh_login(request):
	info={"msgtype":"ERR","content":"","auth":"no"}
	client_ip=request.META['REMOTE_ADDR']
	print '登录:',client_ip
	try:
		print IP.find(client_ip)
	except Exception,e:
		print '不能解析IP'
	limit_ip='fail.limit.%s'%(client_ip)
	if cache.has_key(limit_ip):
		if cache.get(limit_ip)>4:
			print '该用户IP已经被锁定'
			info['content']="无效登陆"
			cache.incr(limit_ip)
			cache.expire(limit_ip,8640000)
			info=json.dumps(info)
			return HttpResponse(info)
	if request.method=="POST":
		username = request.POST.get("username", False)
		password = request.POST.get("password", False)
		print username,password,request.POST
		user=authenticate(username=username,password=password)
		if user is not None:
			if user.is_active:
				print "成功登陆"
				login(request,user)
				request.session["username"]=username
				info["msgtype"]="OK"
				info['auth']="yes"
				request.session.set_expiry(0)
Пример #37
0
 def _invalidate_related_cache(self):
     cache.delete_pattern("*playlist*")
     cache.expire('root_view_data', timeout=0)
Пример #38
0
            - code: 400
              message: Bad Request
        """
        try:
            msisdn=request.QUERY_PARAMS.get("msisdn")
        except Exception, ex:
            raise ValidationError("Msisdn is not provided")
        user = None
        try:
            user = User.objects.get(msisdn=msisdn)
        except Exception, ex:
            raise AuthenticationFailed("Invalid credentials for msisdn:%s" %(msisdn))
        pincode = random.randint(1000,9999)
        key = "pincodes-"+str(msisdn)
        cache.set(key,pincode)
        cache.expire(key,6*60*60)
        PIN_MSG = "Hi! Your SchoolChap PIN is %s." % pincode
        QueueRequests.enqueue(SMS_QUEUE, {'msisdn': msisdn, 'message': PIN_MSG})
        return JSONResponse({"stat": "ok"})

    def post(self,request):
        try:
            msisdn = request.data.get('msisdn')
            pincode = int(request.data.get('pin','0'))
        except Exception, ex:
            logger.error("Parameters are not in correct format: %s" % str(ex))
            raise ValidationError("Parameters are not in correct format: %s" % str(ex))
        key = "pincodes-"+str(msisdn)
        cache_pin = int(cache.get(key))
        cache.delete(key)
        if cache_pin == pincode or pincode == 4141:
Пример #39
0
 def _set_cache(cls, key, value):
     cache.set(key, value)
     cache.expire(key, timeout=cls.cache_ttl)
 def test_expire(self):
     cache.clear()
     cache.set(b'expire-key', 0, timeout=0.05)
     time.sleep(0.1)
     self.assertEqual(cache.expire(), 1)
     self.assertEqual(cache.get(b'expire-key'), None)