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

The following are 30 code examples of django.core.cache.cache.get(). 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: product.py    From Servo with BSD 2-Clause "Simplified" License 8 votes vote down vote up
def choose_product(request, order_id, product_id=None, target_url="orders-add_product"):
    """
    order_id can be either Service Order or Purchase Order
    """
    data = {'order': order_id}
    data['action'] = request.path
    data['target_url'] = target_url

    if request.method == "POST":
        query = request.POST.get('q')

        if len(query) > 2:
            products = Product.objects.filter(
                Q(code__icontains=query) | Q(title__icontains=query)
            )
            data['products'] = products

        return render(request, 'products/choose-list.html', data)

    return render(request, 'products/choose.html', data) 
Example #2
Source File: test_object_view.py    From DjangoRestMultipleModels with MIT License 6 votes vote down vote up
def test_no_queryset(self):
        """
        A querylist with no `queryset` key should raise a ValidationError with the
        appropriate message
        """
        view = NoQuerysetView.as_view()

        request = factory.get('/')

        with self.assertRaises(ValidationError) as error:
            view(request).render()

        self.assertEqual(error.exception.message, (
            'All items in the NoQuerysetView querylist attribute '
            'should contain a `queryset` key'
        )) 
Example #3
Source File: checkin.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_customer(request):
    """Return the selected customer data."""
    if not request.user.is_authenticated():
        raise PermissionDenied

    if not request.GET.get('c'):
        return

    customer = get_object_or_404(Customer, pk=request.GET['c'])
    request.session['checkin_customer'] = customer.pk

    fdata = {'fname': customer.firstname, 'lname': customer.lastname}
    fdata['city'] = customer.city
    fdata['email'] = customer.email
    fdata['phone'] = customer.phone
    fdata['country'] = customer.country
    fdata['postal_code'] = customer.zip_code
    fdata['address'] = customer.street_address

    return json_response(fdata) 
Example #4
Source File: device.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def model_from_slug(product_line, model=None):
    """
    Returns product description for model slug or models dict for
    the specified product line
    """
    if not cache.get("slugmap"):
        slugmap = {}  # Map model slug to corresponding product description
        product_lines = gsxws.products.models()

        for k, v in product_lines.items():
            d = {}
            for p in v['models']:
                slug = slugify(p)
                d[slug] = p

            slugmap[k] = d

        cache.set("slugmap", slugmap)

    models = cache.get("slugmap").get(product_line)

    if model is not None:
        return models.get(model)

    return models 
Example #5
Source File: product.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def sell(self, amount, location):
        """
        Deduct product from inventory with specified location
        """
        if not self.track_inventory():
            return

        try:
            inventory = Inventory.objects.get(product=self, location=location)
            
            try:
                inventory.amount_stocked  = inventory.amount_stocked - amount
                inventory.amount_reserved = inventory.amount_reserved - amount
            except Exception as e:
                # @TODO: Would be nice to trigger a warning
                pass

            inventory.save()
        except Inventory.DoesNotExist:
            raise ValueError(_(u"Product %s not found in inventory.") % self.code) 
Example #6
Source File: device.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def update_gsx_details(request, pk):
    """
    Updates devices GSX warranty details
    """
    device = get_object_or_404(Device, pk=pk)
    try:
        GsxAccount.default(request.user)
        device.update_gsx_details()
        messages.success(request, _("Warranty status updated successfully"))
    except Exception as e:
        messages.error(request, e)

    if request.session.get('return_to'):
        return redirect(request.session['return_to'])

    return redirect(device) 
Example #7
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def close(request, pk):
    """Close this Service Order."""
    order = get_object_or_404(Order, pk=pk)

    if request.method == 'POST':
        try:
            order.close(request.user)
        except Exception as e:
            messages.error(request, e)
            return redirect(order)

        if request.session.get("current_order_id"):
            del(request.session['current_order_id'])
            del(request.session['current_order_code'])
            del(request.session['current_order_customer'])

        messages.success(request, _('Order %s closed') % order.code)

        return redirect(order)

    data = {'order': order, 'action': reverse(close, args=[pk])}
    return render(request, "orders/close.html", data) 
Example #8
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def accessories(request, pk, device_id):
    from django.utils import safestring

    if request.POST.get('name'):
        a = Accessory(name=request.POST['name'])
        a.order_id = pk
        a.device_id = device_id
        a.save()

    choice_list = []
    choices = Accessory.objects.distinct('name')

    for c in choices:
        choice_list.append(c.name)

    action = reverse('orders-accessories', args=[pk, device_id])
    selected = Accessory.objects.filter(order_id=pk, device_id=device_id)
    choices_json = safestring.mark_safe(json.dumps(choice_list))

    return render(request, 'devices/accessories_edit.html', locals()) 
Example #9
Source File: order.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def choose_customer(request, pk):
    """
    Lets the user search for a customer for this order
    """
    if request.method == "POST":
        customers = Customer.objects.none()
        kind = request.POST.get('kind')
        query = request.POST.get('name')

        if len(query) > 2:
            customers = Customer.objects.filter(
                Q(fullname__icontains=query) | Q(email__icontains=query) | Q(phone__contains=query)
            )

        if kind == 'companies':
            customers = customers.filter(is_company=True)

        if kind == 'contacts':
            customers = customers.filter(is_company=False)

        data = {'customers': customers, 'order_id': pk}
        return render(request, "customers/choose-list.html", data)

    data = {'action': request.path}
    return render(request, 'customers/choose.html', data) 
Example #10
Source File: product.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def calculate_price(self, price, shipping=0.0):
        """
        Calculates price and returns it w/ and w/o tax
        """
        conf = Configuration.conf()
        shipping = shipping or 0.0

        if not isinstance(shipping, Decimal):
            shipping = Decimal(shipping)

        margin = get_margin(price)
        vat = Decimal(conf.get("pct_vat", 0.0))

        # TWOPLACES = Decimal(10) ** -2  # same as Decimal('0.01')
        # @TODO: make rounding configurable!
        wo_tax = ((price*100)/(100-margin)+shipping).to_integral_exact(rounding=ROUND_CEILING)
        with_tax = (wo_tax*(vat+100)/100).to_integral_exact(rounding=ROUND_CEILING)

        return wo_tax, with_tax 
Example #11
Source File: mock.py    From controller with MIT License 6 votes vote down vote up
def add_cleanup_pod(url):
    """populate the cleanup pod list"""
    # variance allows a pod to stay alive past grace period
    variance = random.uniform(0.1, 1.5)
    grace = round(settings.KUBERNETES_POD_TERMINATION_GRACE_PERIOD_SECONDS * variance)

    # save
    pods = cache.get('cleanup_pods', {})
    pods[url] = (datetime.utcnow() + timedelta(seconds=grace))
    cache.set('cleanup_pods', pods)

    # add grace period timestamp
    pod = cache.get(url)
    grace = settings.KUBERNETES_POD_TERMINATION_GRACE_PERIOD_SECONDS
    pd = datetime.utcnow() + timedelta(seconds=grace)
    timestamp = str(pd.strftime(MockSchedulerClient.DATETIME_FORMAT))
    pod['metadata']['deletionTimestamp'] = timestamp
    cache.set(url, pod) 
Example #12
Source File: mock.py    From controller with MIT License 6 votes vote down vote up
def remove_cache_item(url, resource_type):
    # remove data object from individual cache
    cache.delete(url)
    # get rid of log element as well for pods
    if resource_type == 'pod':
        cache.delete(url + '_log')

    # remove from the resource type global scope
    items = cache.get(resource_type, [])
    if url in items:
        items.remove(url)
        cache.set(resource_type, items, None)

    # remove from namespace specific scope
    # sneaky way of getting data up to the resource type without too much magic
    cache_url = ''.join(url.partition(resource_type)[0:2])
    items = cache.get(cache_url, [])
    if url in items:
        items.remove(url)
    cache.set(cache_url, items, None) 
Example #13
Source File: annotations.py    From yang-explorer with Apache License 2.0 6 votes vote down vote up
def get_annotation_tree():
    ann_path = ServerSettings.annotation_path(None)
    filename = os.path.join(ann_path, 'covered.json')
    if not os.path.exists(filename):
        return None

    tree = cache.get('ui_ann', None)
    if tree is None:
        tree = XPathTree('/', None)
        with open(filename, 'r') as f:
            profile = json.load(f)
            for line in profile.get('data', []):
                tree.insert(line, profile.get('annotate', None))
            cache.set('ui_ann', tree)
    else:
        print 'From cache..'
    return tree 
Example #14
Source File: annotations.py    From yang-explorer with Apache License 2.0 6 votes vote down vote up
def annotate(nodes, tree=None):
    """
    Args:
        nodes: list lxml element tree nodes with lazy tree instance
    Returns:
        Annotated nodes with attribute and value specified in annotation file
    """
    if not tree:
        tree = get_annotation_tree()

    if tree and nodes:
        for node in nodes:
            xpath = node.get('path', '')
            instance = tree.search(xpath)
            if not instance:
                continue
            for attr, value in instance.attrib.items():
                node.set(attr, value)
            annotate(list(node), tree)
    return nodes 
Example #15
Source File: test_object_view.py    From DjangoRestMultipleModels with MIT License 6 votes vote down vote up
def test_no_querylist(self):
        """
        A view with no querylist and no `get_querylist` overwrite should raise
        an assertion error with the appropriate message
        """
        view = NoQuerylistView.as_view()

        request = factory.get('/')

        with self.assertRaises(AssertionError) as error:
            view(request).render()

        self.assertEqual(str(error.exception), (
            'NoQuerylistView should either include a `querylist` attribute, '
            'or override the `get_querylist()` method.'
        )) 
Example #16
Source File: mock.py    From controller with MIT License 5 votes vote down vote up
def cleanup_pods():
    """Can be called during any sort of access, it will cleanup pods as needed"""
    pods = cache.get('cleanup_pods', {})
    for pod, timestamp in pods.copy().items():
        if timestamp > datetime.utcnow():
            continue

        del pods[pod]
        remove_cache_item(pod, 'pods')
    cache.set('cleanup_pods', pods) 
Example #17
Source File: mock.py    From controller with MIT License 5 votes vote down vote up
def get_namespace(url, resource_type):
    """Inspects the URL and gets namespace from it if there is any"""
    # correct back to proper namespace API
    url = url.replace('apis_autoscaling_v1', 'api_v1')
    url = url.replace('apis_extensions_v1beta1', 'api_v1')
    # check if this is a subresource
    subresource, resource_type, url = is_subresource(resource_type, url)
    # get namespace name
    name = url.split('api_v1_namespaces_').pop(1).split("_{}_".format(resource_type), 1).pop(0)
    return 'api_v1_namespaces_' + name 
Example #18
Source File: tasks.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def check_mail():
    """Checks IMAP box for incoming mail"""
    uid = Configuration.conf('imap_act')

    if empty(uid):
        raise ConfigurationError('Incoming message user not configured')

    counter = 0
    user = User.objects.get(pk=uid)
    server = Configuration.get_imap_server()
    typ, data = server.search(None, "UnSeen")

    for num in data[0].split():
        #logging.debug("** Processing message %s" % num)
        typ, data = server.fetch(num, "(RFC822)")
        # parsestr() seems to return an email.message?
        msg = Parser().parsestr(data[0][1])
        Note.from_email(msg, user)
        #server.copy(num, 'servo')
        server.store(num, '+FLAGS', '\\Seen')
        counter += 1

    server.close()
    server.logout()

    return '%d messages processed' % counter 
Example #19
Source File: note.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def send_sms_smtp(self, config, recipient):
        """
        Sends SMS through SMTP gateway
        """
        recipient = recipient.replace(' ', '')
        settings.EMAIL_HOST = config.get('smtp_host')
        settings.EMAIL_USE_TLS = config.get('smtp_ssl')
        settings.EMAIL_HOST_USER = config.get('smtp_user')
        settings.EMAIL_HOST_PASSWORD = config.get('smtp_password')

        send_mail(recipient, self.body, self.sender, [config['sms_smtp_address']]) 
Example #20
Source File: note.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_excluded_emails(self):
        """
        Returns a list of email addresses that should not be contacted
        """
        if not cache.get('nomail'):
            User.refresh_nomail()

        return cache.get('nomail') 
Example #21
Source File: authentication.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def fetch_oidc_user_profile(self, access_token):
        token_hash = sha256(access_token.encode()).hexdigest()
        cache_key = f"oidc-profile-{token_hash}"
        cached_response = cache.get(cache_key)

        if cached_response:
            return cached_response

        url = settings.OIDC_USER_ENDPOINT
        response = requests.get(url, headers={"Authorization": f"Bearer {access_token}"})

        if response.status_code == 200:
            now = int(time.mktime(datetime.utcnow().timetuple()))
            resets_in = int(response.headers.get("X-RateLimit-Reset", 0)) - now
            cache_seconds = DEFAULT_PROFILE_CACHE_SECONDS if resets_in < 1 else resets_in
            profile = response.json()
            cache.set(cache_key, profile, cache_seconds)
            return profile
        elif response.status_code == 401:
            # The OIDC provider did not like the access token.
            raise exceptions.AuthenticationFailed("Unauthorized access token")
        elif response.status_code >= 500:
            raise requests.exceptions.RequestException(f"{response.status_code} on {url}")

        # This could happen if, for some reason, we're not configured to be
        # allowed to talk to the OIDC endpoint.
        raise OIDCEndpointRequestError(response.status_code) 
Example #22
Source File: device.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def from_dict(cls, d):
        if d.get('_pk'):
            return cls.objects.get(pk=d['_pk'])

        device = Device()

        for k, v in d:
            if k.startswith('_'):
                continue
            setattr(device, k, v)

        return device 
Example #23
Source File: common.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_content_type(cls, model):
        return ContentType.objects.get(app_label='servo', model=model) 
Example #24
Source File: common.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def conf(cls, key=None):
        """
        Returns the admin-configurable config of the site
        """
        config = cache.get('config')
        if config is None:
            config = dict()
            for r in Configuration.objects.all():
                config[r.key] = r.value

            cache.set('config', config)

        return config.get(key) if key else config 
Example #25
Source File: common.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_imap_server(cls):
        import imaplib
        conf = cls.conf()

        if not conf.get('imap_host'):
            raise ValueError("No IMAP server defined - check your configuration")

        if conf.get('imap_ssl'):
            server = imaplib.IMAP4_SSL(conf['imap_host'])
        else:
            server = imaplib.IMAP4(conf['imap_host'])

        server.login(conf['imap_user'], conf['imap_password'])
        server.select()
        return server 
Example #26
Source File: common.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_account(cls, location, queue=None):
        """
        Returns the correct GSX account for the specified user/queue
        """
        try:
            act = location.gsx_accounts.get(sold_to=queue.gsx_soldto)
        except Exception as e:
            act = GsxAccount.get_default_account()

        return act 
Example #27
Source File: common.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_status(self):
        from servo.models import Status
        return Status.objects.get(title=self.description) 
Example #28
Source File: account.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_unread_message_count(self):
        key = '%s_unread_message_count' % self.user.email
        count = cache.get(key, 0)
        return count if count > 0 else "" 
Example #29
Source File: account.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_checkin_user(cls):
        return cls.objects.get(pk=Configuration.conf('checkin_user')) 
Example #30
Source File: product.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_info(request, location, code):
    try:
        product = Product.objects.get(code=code)
        inventory = Inventory.objects.filter(product=product)
    except Product.DoesNotExist:
        product = cache.get(code)

    return render(request, 'products/get_info.html', locals())