Login

Cycling MEDIA_URL context processor

Author:
girasquid
Posted:
December 4, 2008
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

This is a context processor that will allow you to cycle the values of your MEDIA_URL context variable. It will cycle through the urls defined in settings.MEDIA_URLS, so that you can distribute your media url's between multiple servers.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def media_urls(request):
    media_urls = URLCycle(url_list=settings.MEDIA_URLS)
    return {'MEDIA_URL':media_urls}
    
class URLCycle(object):
    def __init__(self,url_list):
        self.urls = url_list
        self.iter = 0
        
    def __str__(self):
        if self.iter == len(self.urls):
            self.iter = 0
        url = self.urls[self.iter]
        self.iter += 1
        return url

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 3 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

girasquid (on December 12, 2008):

Your code is much more compact - and nicer, too! Thanks for pointing it out to me - I didn't realize that there was something built-in to cycle through things for me.

#

johnboxall (on December 20, 2008):

Just an update on the above - you'd probably want to hit each subdomain at least twice so:

def ncycle(iterable n):
    while True:
        for i in range(n):
            for item in iterable:
                yield item

def cycle_media():
  if not hasattr(cycle_media, 'state'):
     cycle_media.state = ncycle(settings.MEDIA_URLS, 2)
  return cycle_media.state.next()

#

Please login first before commenting.