def test_cache_api(): key = "test_prefix:123" value = "456" cache.set(key, value) assert cache.get(key) == value cache.bump_version(key) assert cache.get(key, default="derp" ) == "derp" # version was bumped, so no way this is there cache.set(key, value) assert cache.get(key) == value
def set_cached_value(key, value, timeout=None): """ Set value to context cache :param key: Unique key formed to the context :param value: Value to cache :param timeout: Timeout as seconds :type timeout: int """ cache.set(key, value, timeout=timeout)
def _get_resource(self, request, resource_id): cache_key = "WSHOPCOM_API_%s_%s" % (request.LANGUAGE_CODE, resource_id) resource = cache.get(cache_key) if not resource: try: r = requests.get("https://www.wshop.com/%s/api/%s/" % (request.LANGUAGE_CODE, resource_id)) resource = r.json() cache.set(cache_key, resource, timeout=SECONDS_IN_DAY) except Exception: pass return resource or {}
def get_matching_context_conditions(context): namespace = CONTEXT_CONDITION_CACHE_NAMESPACE ctx_cache_elements = dict(customer=context.customer.pk or 0, shop=context.shop.pk) conditions_cache_key = "%s:%s" % ( namespace, hash(frozenset(ctx_cache_elements.items()))) matching_context_conditions = cache.get(conditions_cache_key, None) if matching_context_conditions is None: matching_context_conditions = set() for condition in ContextCondition.objects.filter(active=True): if condition.matches(context): matching_context_conditions.add(condition.pk) cache.set(conditions_cache_key, matching_context_conditions, timeout=None) return matching_context_conditions
def test_alert_limit_notification(rf, admin_user): supplier = get_simple_supplier() shop = get_default_shop() product = create_product("simple-test-product", shop, supplier) product.stock_behavior = StockBehavior.STOCKED product.save() sc = StockCount.objects.get(supplier=supplier, product=product) sc.alert_limit = 10 sc.save() # nothing in cache cache_key = AlertLimitReached.cache_key_fmt % (supplier.pk, product.pk) assert cache.get(cache_key) is None # put 11 units in stock supplier.adjust_stock(product.pk, +11) # still nothing in cache cache_key = AlertLimitReached.cache_key_fmt % (supplier.pk, product.pk) assert cache.get(cache_key) is None event = AlertLimitReached(product=product, supplier=supplier) assert event.variable_values["dispatched_last_24hs"] is False # stock should be 6, lower then the alert limit supplier.adjust_stock(product.pk, -5) last_run = cache.get(cache_key) assert last_run is not None event = AlertLimitReached(product=product, supplier=supplier) assert event.variable_values["dispatched_last_24hs"] is True # stock should be 1, lower then the alert limit supplier.adjust_stock(product.pk, -5) # last run should be updated assert cache.get(cache_key) != last_run event = AlertLimitReached(product=product, supplier=supplier) assert event.variable_values["dispatched_last_24hs"] is True # fake we have a cache with more than 24hrs cache.set(cache_key, time() - (24 * 60 * 60 * 2)) event = AlertLimitReached(product=product, supplier=supplier) assert event.variable_values["dispatched_last_24hs"] is False
def set_current_theme(identifier, shop): """ Activate a theme based on identifier. :param identifier: Theme identifier :type identifier: str :param shop: Shop to fetch the theme settings :type shop: wshop.core.models.Shop :return: Activated theme :rtype: Theme """ cache.bump_version(get_theme_cache_key(shop)) theme = get_theme_by_identifier(identifier, shop) if not theme: raise ValueError("Invalid theme identifier") theme.set_current() cache.set(get_theme_cache_key(shop), theme) set_middleware_current_theme(theme) return theme
def get_current_theme(shop): """ Get the currently active theme object. :param shop: The shop to get the active theme :type shop: wshop.core.models.Shop :return: Theme object or None :rtype: Theme """ value = cache.get(get_theme_cache_key(shop)) if value: set_middleware_current_theme(value) return value theme = _get_current_theme(shop) cache.set(get_theme_cache_key(shop), theme) # set this theme as the current for this thread set_middleware_current_theme(theme) return theme
def get_best_selling_product_info(shop_ids, cutoff_days=30): shop_ids = sorted(map(int, shop_ids)) cutoff_date = datetime.date.today() - datetime.timedelta(days=cutoff_days) cache_key = "best_sellers:%r_%s" % (shop_ids, cutoff_date) sales_data = cache.get(cache_key) if sales_data is None: sales_data = ( OrderLine.objects .filter( order__shop_id__in=shop_ids, order__order_date__gte=cutoff_date, type=OrderLineType.PRODUCT ) .values("product") .annotate(n=Sum("quantity")) .order_by("-n")[:100] .values_list("product", "product__variation_parent_id", "n") ) cache.set(cache_key, sales_data, 3 * 60 * 60) # three hours return sales_data
def get_currency_precision(currency): """ Get precision by currency code. Precision values will be populated from the ``decimal_places`` fields of the `Currency` objects in the database. :type currency: str :param currency: Currency code as 3-letter string (ISO-4217) :rtype: decimal.Decimal|None :return: Precision value for given currency code or None for unknown """ cache_key = 'currency_precision:' + currency precision = cache.get(cache_key) if precision is None: currency_obj = Currency.objects.filter(code=currency).first() precision = (decimal.Decimal('0.1')**currency_obj.decimal_places if currency_obj else None) cache.set(cache_key, precision) return precision
def override_current_theme_class(theme_class=_not_set, shop=None): """ Context manager for overriding the currently active theme class for testing. An instance of this class is then returned by `get_current_theme`. A falsy value means `None` is returned from `get_current_theme`, which is also useful for testing. :param theme_class: A theme class object :type theme_class: class[Theme] """ # Circular import avoidance: from wshop.xtheme.views.extra import clear_view_cache old_theme_class = cache.get(get_theme_cache_key(shop)) if theme_class is _not_set or not theme_class: cache.set(get_theme_cache_key(shop), None) else: from wshop.xtheme.models import ThemeSettings theme_settings = ThemeSettings.objects.get_or_create( shop=shop, theme_identifier=theme_class.identifier )[0] theme = theme_class(theme_settings) set_middleware_current_theme(theme) cache.set(get_theme_cache_key(shop), theme) clear_view_cache() yield cache.set(get_theme_cache_key(shop), old_theme_class) clear_view_cache()
def get_products_ordered_with(prod, count=20, request=None, language=None): cache_key = "ordered_with:%d" % prod.pk product_ids = cache.get(cache_key) if product_ids is None: # XXX: could this be optimized more? (and does it matter?) order_ids = ( OrderLine.objects.filter(product=prod, type=OrderLineType.PRODUCT) .values_list("order__id", flat=True) ) product_ids = ( OrderLine.objects .filter(order_id__in=order_ids) .exclude(product=prod) .distinct() .values_list("product", flat=True) ) cache.set(cache_key, set(product_ids), 4 * 60 * 60) return ( Product.objects .all_visible(request, language=language) .filter(id__in=product_ids) .order_by("?")[:count] )
def run(self, shop): cache_key = self.cache_key_fmt % (self.variable_values["supplier"].pk, self.variable_values["product"].pk) cache.set(cache_key, time(), timeout=(60 * 60 * 24)) super(AlertLimitReached, self).run(shop=shop)