Hopefully this question will come through clear enough as I’m not sure how to explain what I’m trying to figure out.
Currently for my stores brand list page I have a for loop that goes through every Vendor on the store and outputs the name with a link to the brand collection. This in turn creates a long loading time every time someone tries to access that page because it has to generate that list again.
I was hoping to find a way to have some sort of check where I set the initial brands list and then every time someone loads that page it just has to compare the number of current vendors to the number of vendors in the saved list. If they are the same it would just have to output the list and not go through the for loop, and if the numbers aren’t the same it would generate a new brands list and save that to be used later.
Does anyone know if it’s possible to make something like this? So far I haven’t been able to find any information on saving global variables that aren’t static and stuck as what I set them to by hand.
We have quite a few brands and they change occasionally, so if I don’t use a dynamically generated brand list it requires manually checking for changes in the Vendors list and updating the brands list by hand every time it changes.
Yes, it is possible to achieve what you’re looking for. One way to do this would be to cache the generated brand list. Instead of generating the list every time the page is loaded, you can store the generated list in a cache (e.g., in-memory cache, Redis, or a database) and retrieve it from there. If the number of vendors has changed, you can regenerate the list and update the cache.
Here’s a simple example using an in-memory cache in Python:
import cachecontrol
cache = cachecontrol.CacheControl(cache=cachecontrol.Cache(
memory=cachecontrol.MemoryCacheStore(),
allowable_methods=['GET', 'POST']
))
def generate_brand_list():
# Code to generate the brand list based on the Vendors
return brand_list
@cache.cached(key_prefix='brand_list')
def get_brand_list():
return generate_brand_list()
def update_brand_list():
brand_list = generate_brand_list()
cache.set('brand_list', brand_list)
# Get the cached brand list
brand_list = get_brand_list()
# Check if the number of vendors has changed
if len(brand_list) != current_vendor_count:
# Regenerate the brand list
update_brand_list()
This way, you can reduce the number of times the brand list is generated, improving the page loading time.