Cycling MEDIA_URL context processor

 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. Use MEDIA_URL in flatpages with SSL by gobble 2 years, 10 months ago
  2. Load static media from secure (SSL) static server (Context Processor) by ianreardon 3 years, 7 months ago
  3. media_url context variable by marchino 6 years, 1 month ago
  4. Use MEDIA_URL in 500 error page by bthomas 4 years, 6 months ago
  5. Use MEDIA_URL in flatpages by robhudson 5 years, 1 month ago

Comments

jdunck (on December 11, 2008):

I don't understand why you'd want to use it twice then fall back to media_url. I get the concurrent download limit-- though your number is wrong: http://stevesouders.com/ua/

But my main question is-- suppose you have 10 media requests to do-- how does limiting the first cycle to 2 requests help? You'd just pile the other 6 on one domain, right? 3-4 per domain is better than 6 to one, in terms of concurrency and likely completion, right?

If you accept my argument, this becomes simpler.

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

#

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()

#

(Forgotten your password?)