Login

Cycling MEDIA_URL context processor

Author:
girasquid
Posted:
December 4, 2008
Language:
Python
Version:
1.0
Tags:
cycle media_url
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. Load static media from secure (SSL) static server (Context Processor) by ianreardon 5 years, 7 months ago
  2. Use MEDIA_URL in 500 error page by bthomas 6 years, 6 months ago
  3. Use MEDIA_URL in flatpages with SSL by gobble 4 years, 10 months ago
  4. media_url context variable by marchino 8 years, 1 month ago
  5. Add site info to request context by bthomas 6 years, 6 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.