Ejemplo n.º 1
0
    def get(self, request):
        path_info = request.path_info.split('/')
        service_name = path_info[2]
        path_info = '/%s' % '/'.join(path_info[3:])

        cache_key = 'tilescache-%s' % service_name
        #theService = cache.get(cache_key)
        theService = SERVICE_CACHE.get(cache_key, None)

        if not theService:
            print 'rebuild service %s' % service_name
            service = get_object_or_404(Service, name=service_name)
            cfg = DjangoConfig()
            cfg.read_config(service)
            configs = [cfg]
            layers = TCService.LayerConfig()
            for conf in configs:
                layers.update(conf)
    
            theService = TCService(configs, layers)
            from TileCache.Caches.Disk import Disk
            theService.cache = Disk(base='/tmp/tilescache')

            #cache.set(cache_key, theService, 10)
            SERVICE_CACHE[cache_key] = theService

        fields = request.GET
        req_method = request.method
        host = request.META.get('HTTP_HOST', 'localhost')
        format, image = theService.dispatchRequest(fields, path_info,
                                                   req_method, host)

        response = HttpResponse(image, content_type=format)
        return response
Ejemplo n.º 2
0
Archivo: tile.py Proyecto: Xawwell/iem
def wsgiApp(environ, start_response):
    global theService

    cfgs = cfgfiles
    if not theService:
        theService = Service.load(cfgs)
    return wsgiHandler(environ, start_response, theService)
Ejemplo n.º 3
0
def main():
    usage = "usage: %prog <layer> [<zoom start> <zoom stop>]"
    
    parser = OptionParser(usage=usage, version="%prog $Id$")

    parser.add_option("-f","--force", action="store_true", dest="force", default = False,
                      help="force recreation of tiles even if they are already in cache")
    parser.add_option("-b","--bbox",action="store", type="string", dest="bbox", default = None,
                      help="restrict to specified bounding box")
    parser.add_option("-c","--config", action="store", type="string", dest="tilecacheconfig",
                      help="path to configuration file")
    parser.add_option("-p","--padding",action="store", type="int", dest="padding", default = 0,
                      help="extra margin tiles to seed around target area. Defaults to 0 "+
                      "(some edge tiles might be missing).      A value of 1 ensures all tiles "+
                      "will be created, but some tiles may be wholly outside your bbox")
    parser.add_option("-r","--reverse", action="store_true", dest="reverse", default = False,
                      help="Reverse order of seeding tiles")
    parser.add_option("-a", "--all", action="store_false", dest="skip_empty", default = True,
                      help="Generate all the tiles, the default is to skip the empty tiles if the "+
                      "layer is a vector and mapserver layer.")
    parser.add_option("", "--data-projection", action="store", type="string", dest="dataProjectionString", default=None,
                      help="Proj4 string to force the data projection.")
    parser.add_option("", "--tiles-projection", action="store", type="string", dest="tilesProjectionString", default=None,
                      help="Proj4 string to force the tiles projection.")

    (options, args) = parser.parse_args()

    if len(args) > 3:
        parser.error("Incorrect number of arguments. bbox and padding are now options (-b and -p)")

    cfgs = cfgfiles
    if options.tilecacheconfig:
        cfgs = cfgs + (options.tilecacheconfig,)
        
    svc = Service.load(*cfgs)

    if options.bbox:
        bboxlist = map(float, options.bbox.split(","))
    else:
        bboxlist = None

    if len(args) > 1:
        levels = map(int, args[1:3])
    else:
        # not level given, generate all
        levels = None            

    if len(args) == 0:
        parser.print_help()
        sys.exit(-1)

    for key in fnmatch.filter(svc.layers.keys(), args[0]):
        seed(svc, svc.layers[key], levels=levels, bbox=bboxlist,
             skip_empty=options.skip_empty, padding=options.padding,
             force = options.force, reverse = options.reverse,
             dataProjectionString = options.dataProjectionString,
             tilesProjectionString = options.tilesProjectionString)
        
    svc.teardown()
Ejemplo n.º 4
0
    def __init__(self):
        TC_CONFIG = TC_CONFIG_IN[:-len(".in")]
        new_content = open(TC_CONFIG_IN).read().replace("@@DATA_PATH@@", DATA_PATH)
        f = open(TC_CONFIG, "w")
        f.write(new_content)
        f.close()

        self.tc_service = Service.load(TC_CONFIG)
Ejemplo n.º 5
0
def render_location_tile(location, layer='osm', version='1.0.0', zoom=17, 
extension='png', host='http://localhost'):
    latitude = location.geom.centroid.y
    longitude = location.geom.centroid.x
    service = Service.load(settings.TILECACHE_CONFIG)
    (xtile,ytile) = deg2num(latitude, longitude, zoom) #settings.TILE_ZOOM)
    path_info = '/%s/%s/%d/%d/%d.%s' % (version, layer, zoom, xtile, ytile, extension)
    tile = TMS(service).parse({}, path_info, host)
    return service.renderTile(tile)
Ejemplo n.º 6
0
def load_tilecache_config(settings):
    """ Load the TileCache config.

    This function calls ``TileCache.Service.Service.load`` and
    stores the return value in a private global variable.

    Arguments:

    * ``settings``: a dict with a ``tilecache.cfg`` key whose
      value provides the path to TileCache configuratio file.
    """
    global _service
    _service = Service.load(settings.get('tilecache.cfg'))
Ejemplo n.º 7
0
def load_tilecache_config(settings):
    """ Load the TileCache config.

    This function calls ``TileCache.Service.Service.load`` and
    stores the return value in a private global variable.

    Arguments:

    * ``settings``: a dict with a ``tilecache.cfg`` key whose
      value provides the path to TileCache configuratio file.
    """
    global _service
    _service = Service.load(settings.get('tilecache.cfg'))
Ejemplo n.º 8
0
def run(config_path="config.cfg", path_info=None, **kwargs):
    global template_lookup
    c = ConfigParser.ConfigParser()
    c.read(config_path)

    tc_path = c.get("config", "tilecache_config")

    s = Service.load(tc_path)

    template_path = c.get("config", "template_path")

    tilecache_location = None
    if c.has_option('config', "tilecache_location"):
        tilecache_location = c.get("config", "tilecache_location")

    template_lookup = TemplateLookup(directories=template_path.split(","))

    additional_metadata = []

    try:
        additional_metadata = [i[0] for i in c.items("properties")]
    except ConfigParser.NoSectionError:
        pass

    if s.metadata.has_key('exception'):
        data = [
            "Current TileCache config is invalid.",
            "Exception: %s" % s.metadata['exception'],
            "Traceback: \n %s" % s.metadata['traceback']
        ]
        return ['text/plain', "\n".join(data)]

    data = ""
    stripped = path_info.strip("/")
    stripped_split = stripped.split("/")
    if dispatch_urls.has_key(stripped_split[0]):
        data = dispatch_urls[stripped_split[0]](
            s,
            parts=stripped_split[1:],
            additional_keys=additional_metadata,
            tilecache_location=tilecache_location,
            **kwargs)

    if isinstance(data, list) or isinstance(data, Response):
        return data

    return ['text/html', str(data)]
Ejemplo n.º 9
0
def run(config_path = "config.cfg", path_info = None, **kwargs):
    global template_lookup
    c = ConfigParser.ConfigParser()
    c.read(config_path)

    tc_path = c.get("config", "tilecache_config")

    s = Service.load(tc_path)
    
    template_path = c.get("config", "template_path")

    tilecache_location = None
    if c.has_option('config', "tilecache_location"):
        tilecache_location = c.get("config", "tilecache_location")

    template_lookup = TemplateLookup(directories=template_path.split(","))
    
    additional_metadata = [] 
    
    try:
        additional_metadata = [i[0] for i in c.items("properties")]
    except ConfigParser.NoSectionError:
        pass

    if s.metadata.has_key('exception'):
        data = [
          "Current TileCache config is invalid.", 
          "Exception: %s" % s.metadata['exception'],
          "Traceback: \n %s" % s.metadata['traceback']
        ]
        return ['text/plain', "\n".join(data)]
    
    data = ""
    stripped = path_info.strip("/")
    stripped_split = stripped.split("/")
    if dispatch_urls.has_key(stripped_split[0]):
        data = dispatch_urls[stripped_split[0]](s, parts=stripped_split[1:], 
                                                additional_keys = additional_metadata, 
                                                tilecache_location = tilecache_location,
                                                **kwargs)
    
    if isinstance(data, list) or isinstance(data, Response):
        return data
    
    return ['text/html', str(data)]
Ejemplo n.º 10
0
def load_tilecache_config(settings):  # pragma: no cover
    """ Load the TileCache config.

    This function calls ``TileCache.Service.Service.load`` and
    stores the return value in a private global variable.

    Arguments:

    * ``settings``: a dict with a ``tilecache.cfg`` key whose
      value provides the path to TileCache configuratio file.
    """
    from TileCache.Service import Service
    global _service
    _service = Service.load(settings.get('tilecache.cfg'))
    if 'traceback' in _service.metadata:
        print 'Tilecache loading error: '
        print _service.metadata['exception']
        print _service.metadata['traceback']
Ejemplo n.º 11
0
def load_tilecache_config(settings):
    """ Load the TileCache config.

    This function calls ``TileCache.Service.Service.load`` and
    stores the return value in a private global variable.

    Arguments:

    * ``settings``: a dict with a ``tilecache.cfg`` key whose
      value provides the path to TileCache configuratio file.
    """
    from TileCache.Service import Service
    global _service
    _service = Service.load(settings.get('tilecache.cfg'))
    if 'traceback' in _service.metadata:
        print 'Tilecache loading error: '
        print _service.metadata['exception']
        print _service.metadata['traceback']
Ejemplo n.º 12
0
class TilecacheController(BaseController):

    service = Service.load(config.get('tilecache.cfg'))

    def tilecache(self, environ, start_response):
        try:
            expiration = self.service.config.getint('cache', 'expire')
        except NoOptionError:
            expiration = DEFAULT_EXPIRATION

        # custom_start_response adds cache headers to the response
        def custom_start_response(status, headers, exc_info=None):
            headers.append(
                ('Cache-Control', 'public, max-age=%s' % expiration))
            headers.append(('Expires',
                            email.Utils.formatdate(time.time() + expiration,
                                                   False, True)))
            return start_response(status, headers, exc_info)

        return wsgiHandler(environ, custom_start_response, self.service)
Ejemplo n.º 13
0
def get_eb_layer(name):
    # svc = Service.load(settings.TILECACHE_CONFIG)
    mapfile = r"/data/oceancolor/terra/L3m/2017/001/T2017001_L3m_DAY_NSST_sst_4km.map"
    svc = Service(
        Disk('/tmp/somecache'),  # See "Cache Invalidation", below
        {
            "raster":
            MS.MapServer("basic",
                         mapfile,
                         layers="raster",
                         srs='EPSG:4326',
                         debug=False),
        })
    '''
    svc = Service(
        Disk('/tmp/somecache'),  # See "Cache Invalidation", below
        { 
            "raster": WMS.WMS("basic", r"http://localhost/cgi-bin/mapserv.cgi?map=/data/oceancolor/aqua/L3m/2017/001/A2017001.L3m_DAY_SST_sst_4km.map&mode=map&layer=raster", srs='EPSG:4326', width='256', height='256'),
        }
    )
    '''
    return svc.layers[name]
Ejemplo n.º 14
0
    import mapnik

# todo - remove <layername>, and remove 'foo' from url in static/treemap.js
tile_request_pat = r'/(?P<version>\d{1,2}\.\d{1,3}\.\d{1,3})/(?P<layername>[a-z]{1,64})/(?P<z>\d{1,10})/(?P<x>\d{1,10})/(?P<y>\d{1,10})\.(?P<extension>(?:png|jpg|gif))'

# hackish way to grab style obj and avoid parsing XML each request...
m = mapnik.Map(1, 1)
mapnik.load_map(m, settings.MAPNIK_STYLESHEET)
style = m.find_style('style')
del m

srv = None

if settings.CACHE_SEARCH_METHOD == 'mem':
    srv = Service(
        Memcached(),
        {},  # layers are dynamic
    )
else:
    srv = Service(
        Disk(settings.CACHE_SEARCH_DISK_PATH),
        {},  # layers are dynamic
    )

query_hash = {}


class TileResponse(object):
    def __init__(self, tile_bytes):
        self.tile_bytes = tile_bytes

    def __call__(self, extension='png'):
Ejemplo n.º 15
0
def get_eb_layer(name):
    svc = Service.load(settings.TILECACHE_CONFIG)
    return svc.layers[name]
Ejemplo n.º 16
0
def application(environ, start_response):
    """Go service."""
    if not theService["app"]:
        theService["app"] = Service.load(cfgfiles)
    return wsgiHandler(environ, start_response, theService["app"])