#
# Hack to cache OSM tile images locally, using file based django caching
#
# Rick van der Zwet <info@rickvanderzwet.nl>
#
from django.views.decorators.cache import cache_page
from django.http import HttpResponse

import settings
import random
import urllib

import logging
logger = logging.getLogger(__name__)


# Create your views here.
@cache_page(60 * 60 * 24 * 7, cache="osm_proxy")
def osm_proxy(request,zoom,x,y):
  mirror = random.choice(['a','b','c'])
  url = 'http://%s.tile.openstreetmap.org/%s/%s/%s.png' % (mirror, zoom, x, y)
  logger.info("Fetching tile from %s" % url)
  data = urllib.urlopen(url).read()
  response = HttpResponse(mimetype="image/png")
  response.write(data)
  return response
