Python django.core.cache.cache.keys() Examples

The following are 16 code examples of django.core.cache.cache.keys(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.cache.cache , or try the search function .
Example #1
Source File: notify.py    From sensu_drive with MIT License 6 votes vote down vote up
def onduty_members(self):
        
        OnDuty = []
        if 'OnDuty' in cache.keys('OnDuty'):
            OnDuty = cache.get('OnDuty')      
        else:
            try:
                event_start, event_end, instance = ScheduledOccurrence.objects.filter(event__in=ScheduledEvent.objects.filter(event=0)).next_occurrence()    
                NOW = datetime.datetime.now(datetime.timezone.utc).timestamp()
                if NOW >= event_start.timestamp() and NOW <= event_end.timestamp():
                    for user in instance.event.members_list():
                        OnDuty.append(user.pk)
                    logger.debug('onduty_members found: %s' % OnDuty)
                    #cache.set('OnDuty', OnDuty, timeout=event_end.timestamp())
                    cache.set('OnDuty', OnDuty, timeout=settings.ON_DUTY_CACHE_MEMBERS)
                else:
                    logger.debug('onduty_members can not find onduty_members')
            except:
                logger.error('onduty_members failed finding onduty_members')
                pass
            
        return OnDuty 
Example #2
Source File: notify.py    From sensu_drive with MIT License 6 votes vote down vote up
def user_dnd(self, user_pk):
        
        if 'DnD_' + str(user_pk) in cache.keys("DnD_*"):
            #DnD = cache.get('DnD_' + str(user_pk))
            DnD = True        
        else:
            DnD = False
            try:
                event_start, event_end, instance = ScheduledOccurrence.objects.filter(event__in=ScheduledEvent.objects.filter(event=1, members__in=[user_pk])).next_occurrence()    
                NOW = datetime.datetime.now(datetime.timezone.utc).timestamp()
                if NOW >= event_start.timestamp() and NOW <= event_end.timestamp():
                    DnD = True
                    cache.set('DnD_' + str(user_pk), DnD, timeout=event_end.timestamp())
            except:
                pass
            
        return DnD 
Example #3
Source File: views.py    From sensu_drive with MIT License 6 votes vote down vote up
def clients(request):        

    data = {}
    
    for word in cache.keys("client_*"):
        client = re.sub(r'^client_', '', word)
        try:
            
            client_data = cache.get(word)
            data[client] = client_data 
            
        except:
            raise
    
    profile_form = ContactForm(instance=Contact.objects.get(user=request.user.id))
    
    return render(request, 'isubscribe/clients.html', {'DATA':data, 'profile_form': profile_form}) 
Example #4
Source File: views.py    From sensu_drive with MIT License 6 votes vote down vote up
def subscriptions(request):        

    data = {}
    
    for word in r.keys("subscription_*"):
        subscription = re.sub(r'^subscription_', '', str(word.decode('utf-8')))
        try:
            
            subscription_data = r.lrange(word, 0, -1)
            data[subscription] = subscription_data 
            
        except:
            raise
    
    profile_form = ContactForm(instance=Contact.objects.get(user=request.user.id))   
    
    return render(request, 'isubscribe/subscriptions.html', {'DATA':data, 'profile_form': profile_form})




#@login_required(login_url=reverse_lazy('login')) 
Example #5
Source File: stats.py    From c3nav with Apache License 2.0 6 votes vote down vote up
def stats_snapshot(reset=True):
    last_now = cache.get('apistats_last_reset', '', None)
    now = timezone.now()
    results = {}
    for key in cache.keys('apistats__*'):
        results[key] = cache.get(key)
        if reset:
            cache.delete(key)
    if reset:
        cache.set('apistats_last_reset', now, None)
    results = dict(sorted(results.items()))
    return {
        'start_date': str(last_now),
        'end_date': str(now),
        'data': results
    } 
Example #6
Source File: views.py    From eoj3 with MIT License 6 votes vote down vote up
def get_context_data(self, **kwargs):
    data = super().get_context_data(**kwargs)
    data['code'] = None

    chasing = self.request.GET.get('id', '')

    history_keys = cache.keys("PASTEBIN*")

    data['history'] = []
    for key in history_keys:
      code = cache.get(key)
      if code:
        id = key.lstrip("PASTEBIN")
        data['history'].append({
          'code': code,
          'length': len(code),
          'id': id,
          'ttl': cache.ttl(key)
        })
        if id == chasing:
          data['code'] = code
    data['history'].sort(key=lambda x: x['ttl'])
    if data['history'] and not data['code']:
      data['code'] = data['history'][0]['code']
    return data 
Example #7
Source File: schedule.py    From Joy_QA_Platform with Apache License 2.0 5 votes vote down vote up
def getJobs(self):
        jobs = []
        for key in cache.keys("qa_paltform_loop_jobs_*"):
            jobs.append(pickle.loads(cache.get(key)))
        return jobs 
Example #8
Source File: schedule.py    From Joy_QA_Platform with Apache License 2.0 5 votes vote down vote up
def cancelJob(self,task_id):
        # print("尝试停止任务")
        with cache.lock("qa_test_platform_cancel"):
            for key in cache.keys("qa_paltform_loop_jobs_*"):
                job = pickle.loads(cache.get(key))
                # print(job.task_id)
                if job.task_id == task_id:
                    # print("删除id,",job.task_id)
                    cache.delete_pattern(key) 
Example #9
Source File: schedule.py    From Joy_QA_Platform with Apache License 2.0 5 votes vote down vote up
def _run_job(self, job):
        ret = job.run()
        # 缓存job最新的执行时间
        for key in cache.keys("qa_paltform_loop_jobs_*"):
            old_job = pickle.loads(cache.get(key))
            if job.task_id == old_job.task_id:
                cache.delete_pattern(key)
                cache.set(key,pickle.dumps(job),timeout=None) 
Example #10
Source File: clearobservers.py    From django-rest-framework-reactive with Apache License 2.0 5 votes vote down vote up
def handle(self, *args, **options):
        """Command handle."""
        models.Observer.objects.all().delete()
        models.Subscriber.objects.all().delete()

        for cache_key in cache.keys(search='{}*'.format(THROTTLE_CACHE_PREFIX)):
            cache.delete(cache_key) 
Example #11
Source File: notify.py    From sensu_drive with MIT License 5 votes vote down vote up
def get_contact(self, user_pk):
        
        if 'contact_' + str(user_pk) in cache.keys("contact_*"):
            contact = cache.get('contact_' + str(user_pk))
        else:
            try:
                user = User.objects.get(id=user_pk, is_active = True)
            except:
                logger.error('notify get_contact failed finding user id: %s' % (user_pk))
                pass                                        
            if not hasattr(user, 'contact') or user.contact.slack_uid in [None, '']:
                logger.error('notify get_contact no contact found for user id: %s' % (user_pk))
                return {}
            else:
                
                if user.contact.slack_uid not in [None, '']:
                    slack_uid = user.contact.slack_uid
                else:                    
                    slack_uid = None
                    
                if user.contact.phone_number not in [None, '']:
                    phone_number = user.contact.phone_number
                else:
                    phone_number = None
                    
                contact = { 'slack_uid': slack_uid, 'phone_number': phone_number, 'username': user.username }
                cache.set('contact_' + str(user_pk), contact, timeout=(float(1) * 3600))
                
        return contact 
Example #12
Source File: escalator.py    From sensu_drive with MIT License 5 votes vote down vote up
def check(self):
        
        logger.debug("escalator check entity: %s" % self.entity)
        
        if 'ack_' + self.entity in cache.keys("ack_*") or self.status == 0:
            return False
        
        if self.occurrences > 20 and self.occurrences > len(self.history) and self.status == 2:
            return True
        
        if len(self.history) > 1: 
                # remove current status from history
                self.history.pop()
                
                if len(self.history) < 2:
                    return False
                
                problem_history = []  
                              
                for i in range(len(self.history), 0, -1):                    
                    last_status = int(self.history[i-1])
                    if int(last_status) == 0:
                        break                    
                    problem_history.append(last_status)
                                
                if self.status == 2 and len(problem_history) >= 2 and len(set(problem_history)) == 1 :
                    return True
                
                if int(self.status) == 2 and len(problem_history) > 10 :
                    return True

        
        return False 
Example #13
Source File: views.py    From sensu_drive with MIT License 5 votes vote down vote up
def mySubscribe(request):
    
    def user_id_subsribtions(user_id):
        subscriptions = []
        for word in cache.keys("rule_*"):
            entity = re.sub(r'^rule_', '', word)               
            status_1 = False       
            status_2 = False 
            try:
                rule = cache.get('rule_' + entity)            
                if '1' in rule and user_id in rule['1']:
                    status_1 = True            
                if '2' in rule and user_id in rule['2']:
                    status_2 = True            
            except:
                pass
            
            if 'silent_' + entity in cache.keys("silent_*"):                
                silent = True
            else:
                silent = False                    
            
            if status_1 == True or status_2 == True:
                subscriptions.append({ 'entity': entity, 'status_1': status_1, 'status_2': status_2, 'silent': silent })
                
        return subscriptions
        


    mimetype = 'application/json'
    data = user_id_subsribtions(request.user.id)
    
    
    return HttpResponse(json.dumps(data), mimetype) 
Example #14
Source File: tasks.py    From sensu_drive with MIT License 5 votes vote down vote up
def sensu_client_list():
    
    API_URL = settings.SENSU_API_URL + '/clients'
    userAndPass = base64.b64encode(str.encode("%s:%s" % (settings.SENSU_API_USER, settings.SENSU_API_PASSWORD))).decode("ascii")
    headers = { 'X_REQUESTED_WITH' :'XMLHttpRequest',
               'Accept': 'application/json, text/javascript, */*; q=0.01',
               'Authorization' : 'Basic %s' %  userAndPass }
            
    try:
        
        request = http.request('GET', API_URL, None, headers, preload_content=False)        
        response = request.status
                
        if response == 200:
            reader = codecs.getreader('utf-8')
            data = json.load(reader(request))
            request.release_conn()
        else:
            logger.error('response: %s' % str(response))
            
    except:
        logger.error("sensu_client_list failed")
        raise
    
    subscriptions = []
    
    [ r.delete(subscription) for subscription in r.keys("subscription_*") ]
    #[ cache.delete(client) for client in cache.keys("client_*") ]
    
    for object in data:
        
        cache.set('client_' + object['name'], object, timeout=settings.CACHE_CLIENT_TTL + 300)
        
        if 'subscriptions' in object:            
            subscriptions.extend(object['subscriptions'])
            
            for subscription in object['subscriptions']:                
                logger.debug("sensu_client_list update subscription_%s adding %s" % (subscription, object['name']))
                r.rpush('subscription_' + subscription, object['name'])
            
    cache.set('subscriptions', list(set(subscriptions)), timeout=settings.CACHE_CLIENT_TTL + 300) 
Example #15
Source File: notify.py    From sensu_drive with MIT License 4 votes vote down vote up
def notify_onduty(self, twilio_retry=False, retry_count=0, member_id=None, ack=False):
        
        if 'onduty_disable_alerts' in cache.keys("onduty_disable_*"):
            if cache.get('onduty_disable_alerts'):
                logger.warning('notify_onduty - onduty alerts are disabled')
                return
        
        if twilio_retry:
            logger.debug('notify_onduty - this is a twilio_retry for member_id: %s' % member_id)
            if int(retry_count) > 0:
                self.twilio_params['retry_count'] = int(retry_count)
            else:
                self.twilio_params['retry_count'] = 0
            self.twilio_params['retry_count'] += 1
            members = self.onduty_members()           
            self.twilio_params['members'] = members
            self.twilio_params['member_id'] = int(member_id)
            if self.twilio_params['retry_count'] > settings.ON_DUTY_TWILIO_RETRY:
                self.twilio_params['retry_count'] = 0
                index = 0
                for member in members:
                    logger.debug('notify_onduty - twilio_retry members: %s index: %s members_length: %s' % (members, index, len(members)))
                    if int(member) == int(member_id):
                        if index < (len(members) - 1):
                            next_member = members[index + 1]
                        else:
                            next_member = members[0]
                        break
                    elif index == (len(members) - 1):
                        next_member = members[0]
                        break
                    index += 1                                                    
                self.twilio_params['member_id'] = next_member
                logger.debug('######### notify_onduty retry notify_twilio_call for next member id: %s' % self.twilio_params['member_id'])
            else:
                logger.debug('######### notify_onduty retry notify_twilio_call for member id: %s retry: %s' % (self.twilio_params['member_id'], self.twilio_params['retry_count']))
                
            self.notify_twilio_call(self.twilio_params['member_id'], dnd_ignore=True, on_duty=True, onduty_retry=True)
        else:            
            members = self.onduty_members()
            logger.debug('notify_onduty - this is a normal call for notify_twilio_call members: %s' % members)
            self.twilio_params['members'] = members
            if len(members) > 0 and self.status >= settings.ON_DUTY_STATUS_LEVEL and ack == False:
                self.twilio_params['member_id'] = members[0]
                logger.debug('######### notify_onduty do notify_twilio_call for user id: %s' % members[0])
                self.notify_twilio_call(members[0], dnd_ignore=True, on_duty=True)
        
            for user_pk in members:
                logger.debug('********* notify_onduty do notify_slack for user id: %s' % user_pk)
                self.notify_slack(user_pk, dnd_ignore=True) 
Example #16
Source File: views.py    From sensu_drive with MIT License 4 votes vote down vote up
def whois(request):

    mimetype = 'application/json'

    # Get channel_layer function
    from channels.asgi import get_channel_layer
    from channels.sessions import session_for_reply_channel
            
    # passing group_channel takes channel name
    #channel_layer = get_channel_layer()
    #data = channel_layer.group_channels('notifications')
    #data = channel_layer.global_statistics()
    #data = channel_layer.channel_statistics('notifications')
    #data = get_channel_layer().group_channels('notifications')    
    #data = Group("notifications").extensions
    #data = get_channel_layer().receive_twisted()
    
    #from channels import channel_layers
    #layer = channel_layers["default"]
    #print(layer.router.channels)    
    
    data = []
    
    
    from django.contrib.sessions.backends import cache as engine
    data = get_channel_layer().group_channels('notifications')
    
    active_users = []
    for C in data:        
        #Channel(C).send({"text": json.dumps({'clean_signal':True})})
        c_session = session_for_reply_channel(C)        
        session = engine.SessionStore(c_session._session_key)        
        
        #print(c_session._session['_auth_user_id'])
        #print(session.keys())
        #print(session.get('username', None), session.get_expiry_date())
        
        username = session.get('username', None)
        # this is the same
        # username = c_session.get('username', None)
        if username not in active_users and username != None:
            active_users.append(username)
    data = active_users
            
    
    return HttpResponse(json.dumps(data), mimetype)