当前位置: 首页>>代码示例>>Python>>正文


Python TileStache类代码示例

本文整理汇总了Python中TileStache的典型用法代码示例。如果您正苦于以下问题:Python TileStache类的具体用法?Python TileStache怎么用?Python TileStache使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了TileStache类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: tiles

def tiles(request, service_slug, z, x, y, extension):
    """
    Proxy to tilestache
    {X} - coordinate column.
    {Y} - coordinate row.
    {B} - bounding box.
    {Z} - zoom level.
    {S} - host.
    """
    service = TileService.objects.get(slug=service_slug)
    config = {
        "cache": {"name": "Test"},
        "layers": {}
    }
    config["layers"][service_slug]={
        "provider": {
            'name': 'mapnik',
            "mapfile": service.mapfile
        }
    }
    config = TileStache.Config.buildConfiguration(config)
    path_info = "%s/%s/%s/%s.%s" % (service_slug, z, x, y, extension)
    coord, extension = TileStache.splitPathInfo(path_info)[1:]
    mimetype, content = TileStache.getTile(config.layers[service_slug], coord, extension)
    return HttpResponse(content, mimetype=mimetype)
开发者ID:flyingliang,项目名称:cartoview_arcgis_feature_server,代码行数:25,代码来源:views.py

示例2: seed_resource_cache

def seed_resource_cache():
    datatype_factory = DataTypeFactory()
    zooms = range(settings.CACHE_SEED_MAX_ZOOM + 1)
    extension = 'pbf'

    lat1, lon1, lat2, lon2 = GeoUtils().get_bounds_from_geojson(settings.CACHE_SEED_BOUNDS)
    south, west = min(lat1, lat2), min(lon1, lon2)
    north, east = max(lat1, lat2), max(lon1, lon2)

    northwest = Location(north, west)
    southeast = Location(south, east)

    padding = 0

    datatypes = [
        d.pk for d in models.DDataType.objects.filter(isgeometric=True)]
    nodes = models.Node.objects.filter(
        graph__isresource=True, datatype__in=datatypes)
    for node in nodes:
        datatype = datatype_factory.get_instance(node.datatype)
        count = models.TileModel.objects.filter(
            data__has_key=str(node.nodeid)).count()
        if datatype.should_cache(node) and count > 0:
            config = TileStache.parseConfig(get_tileserver_config(node.nodeid))
            layer = config.layers[str(node.nodeid)]
            ul = layer.projection.locationCoordinate(northwest)
            lr = layer.projection.locationCoordinate(southeast)
            coordinates = generateCoordinates(ul, lr, zooms, padding)
            for (offset, count, coord) in coordinates:
                path = '%s/%d/%d/%d.%s' % (layer.name(), coord.zoom,
                                           coord.column, coord.row, extension)

                progress = {"tile": path,
                            "offset": offset + 1,
                            "total": count}

                attempts = 3
                rendered = False

                while not rendered:
                    print '%(offset)d of %(total)d...' % progress,

                    try:
                        mimetype, content = TileStache.getTile(
                            layer, coord, extension, True)

                    except:
                        attempts -= 1
                        print 'Failed %s, will try %s more.' % (progress['tile'], ['no', 'once', 'twice'][attempts])

                        if attempts == 0:
                            print 'Failed %(zoom)d/%(column)d/%(row)d, trying next tile.\n' % coord.__dict__
                            break

                    else:
                        rendered = True
                        progress['size'] = '%dKB' % (len(content) / 1024)

                        print '%(tile)s (%(size)s)' % progress
开发者ID:fargeo,项目名称:arches,代码行数:59,代码来源:tileserver.py

示例3: tilestache

def tilestache(request, layer_name, z, x, y, extension):
    """
    Proxy to tilestache
    {X} - coordinate column.
    {Y} - coordinate row.
    {B} - bounding box.
    {Z} - zoom level.
    {S} - host.
    """
    config = get_config()
    path_info = "%s/%s/%s/%s.%s" % (layer_name, z, x, y, extension)
    coord, extension = TileStache.splitPathInfo(path_info)[1:]
    mimetype, content = TileStache.getTile(config.layers[layer_name], coord, extension)
    return HttpResponse(content, mimetype=mimetype)
开发者ID:crindt,项目名称:uf,代码行数:14,代码来源:views_painting.py

示例4: render

    def render(self, config, input_img, coord):
        
        layer_img, color_img, mask_img = None, None, None
        
        if self.layername:
            layer = config.layers[self.layername]
            mime, body = TileStache.handleRequest(layer, coord, 'png')
            layer_img = PIL.Image.open(StringIO(body))
        
        if self.maskname:
            layer = config.layers[self.maskname]
            mime, body = TileStache.handleRequest(layer, coord, 'png')
            mask_img = PIL.Image.open(StringIO(body)).convert('L')

        if self.colorname:
            color = makeColor(self.colorname)
            color_img = PIL.Image.new('RGBA', input_img.size, color)

        output_img = input_img.copy()

        if layer_img and color_img and mask_img:
            raise Exception('could be ugly')
        
        elif layer_img and color_img:
            output_img.paste(color_img, None, color_img)
            output_img.paste(layer_img, None, layer_img)

        elif layer_img and mask_img:
            # need to combine the masks here
            layermask_img = PIL.Image.new('RGBA', layer_img.size, (0, 0, 0, 0))
            layermask_img.paste(layer_img, None, mask_img)
            output_img.paste(layermask_img, None, layermask_img)

        elif color_img and mask_img:
            output_img.paste(color_img, None, mask_img)
        
        elif layer_img:
            output_img.paste(layer_img, None, layer_img)
        
        elif color_img:
            output_img.paste(color_img, None, color_img)

        elif mask_img:
            raise Exception('nothing')

        else:
            raise Exception('nothing')

        return output_img
开发者ID:gundersen,项目名称:TileStache,代码行数:49,代码来源:Composite.py

示例5: tiles

def tiles(request, layer_name, z, x, y, extension, custom_tile=None):
    """
    Fetch tiles with tilestache.
    """
    metatile = TileStache.Core.Metatile()
    
    if custom_tile:
        config = get_config(custom_tile=custom_tile)
    else:
        config = get_config()
    
    path_info = "%s/%s/%s/%s.%s" % (layer_name, z, x, y, extension)
    coord, extension = TileStache.splitPathInfo(path_info)[1:]
    try:
        tilestacheLayer = config.layers[layer_name]
    except:
        return HttpResponseNotFound()

    status_code, headers, content = tilestacheLayer.getTileResponse(coord, extension)
    mimetype = headers.get('Content-Type')
    if len(content) == 0:
        status_code = 404

    response = HttpResponse(content, content_type=mimetype, status=status_code)
    response['Access-Control-Allow-Origin'] = '*'
    return response
开发者ID:jbants,项目名称:EasyTileServer,代码行数:26,代码来源:views.py

示例6: clean_resource_cache

def clean_resource_cache(tile):
    # get the tile model's bounds
    datatype_factory = DataTypeFactory()
    nodegroup = models.NodeGroup.objects.get(pk=tile.nodegroup_id)
    for node in nodegroup.node_set.all():
        datatype = datatype_factory.get_instance(node.datatype)
        if datatype.should_cache(node) and datatype.should_manage_cache(node):
            bounds = datatype.get_bounds(tile, node)
            if bounds is not None:
                zooms = range(20)
                config = TileStache.parseConfig(
                    get_tileserver_config(node.nodeid))
                layer = config.layers[str(node.nodeid)]
                mimetype, format = layer.getTypeByExtension('pbf')

                lon1, lat1, lon2, lat2 = bounds
                south, west = min(lat1, lat2), min(lon1, lon2)
                north, east = max(lat1, lat2), max(lon1, lon2)

                northwest = Location(north, west)
                southeast = Location(south, east)

                ul = layer.projection.locationCoordinate(northwest)
                lr = layer.projection.locationCoordinate(southeast)

                padding = 0
                coordinates = generateCoordinates(ul, lr, zooms, padding)

                for (offset, count, coord) in coordinates:
                    config.cache.remove(layer, coord, format)
    for key, tile_list in tile.tiles.iteritems():
        for child_tile in tile_list:
            clean_resource_cache(child_tile)
开发者ID:fargeo,项目名称:arches,代码行数:33,代码来源:tileserver.py

示例7: getTile

def getTile(layer,extension,x,y,z,config):
    cfg = TileStache.Config.buildConfiguration(config)
    contenttype, content = TileStache.getTile(cfg.layers[layer], ModestMaps.Core.Coordinate(int(x), int(y), int(z)),extension,ignore_cached=True)
    handle, filename = mkstemp(prefix='tile-', suffix='.'+extension)
    os.write(handle, content)
    os.close(handle)
    return filename
开发者ID:lzxleslie,项目名称:HighGis_Django,代码行数:7,代码来源:tile.py

示例8: wms

def wms(layer,x,y,z):
    if not tileconfig.layers.has_key(layer):
        return abort(404)
    coord = ModestMaps.Core.Coordinate(y,x,z)
    type, bytes = TileStache.getTile(tileconfig.layers[layer], coord, 'png')
    buf = BytesIO(bytes)
    return send_file(buf, mimetype=type)
开发者ID:mapkiwiz,项目名称:geotags,代码行数:7,代码来源:wms.py

示例9: app

def app(environ, start_response):

    layer, coord, ext = TileStache._splitPathInfo(environ['PATH_INFO'])

    if not config.layers.get(layer, False):
        status = '404 NOT FOUND'
        data = ''

    else:

        try:
            content_type, data = TileStache.handleRequest(config.layers[layer], coord, ext)
            status = '200 OK'

        except Exception, e:
            status = '500 SERVER ERROR'
            data = str(e)
开发者ID:gundersen,项目名称:TileStache,代码行数:17,代码来源:tilestache_gunicorn.py

示例10: get_tile_config

def get_tile_config():
    import TileStache as tilestache
    pth = os.path.join(TILE_CONFIG_DIR, 'tiles.cfg')
    try:
        cfg = tilestache.parseConfigfile(pth)
    except (IOError, ValueError):
        cfg = None
    return cfg
开发者ID:afenix,项目名称:juniper-priorities,代码行数:8,代码来源:settings.py

示例11: addLayer

	def addLayer( self, layerDef, coord ):
		
		_, _, layer = TileStache.getTile(self.layer.config.layers[layerDef['src']], coord, 'JSON')[1]
#		raise KnownUnknown(layer)
		if layerDef['wrapper'] == None:
			layer = json.loads(layer)
		else:
			layer = json.loads(layer[(len(layerDef['wrapper'])+1):-1]) #Strip "Wrapper(...)"
		
		gridSize = len(layer['grid'])

		#init resultGrid based on given layers (if required)
		if len(self.resultGrid) == 0:
			for i in xrange(gridSize):
				self.resultGrid.append([])
				for j in xrange(gridSize):
					self.resultGrid[i].append(-1)
	
		keys = layer['keys']
		
		keyRemap = {}
		for k in keys:
			if k in self.gridKeys:
				for ext in xrange(ord('a'), ord('z')+1):
					if not k+chr(ext) in self.gridKeys:
						keyRemap[k] = (k+chr(ext))
						break
				if not k in keyRemap:
					raise Error("Couldn't remap")
		
		addedKeys = [] #FIXME: HashSet<string>?
		
		for y in xrange(gridSize):
			line = layer['grid'][y]
			for x in xrange(gridSize):
				idNo = self.decodeId(line[x])
				
				if keys[idNo] == "":
					continue
				
				key = keys[idNo]
				if keys[idNo] in keyRemap:
					key = keyRemap[keys[idNo]]
				
				if not key in addedKeys:
					self.gridKeys.append(key)
					addedKeys.append(key)
					if layerDef['layer_id'] != None and self.layer_id != None: #Add layer name attribute
						layer['data'][keys[idNo]][self.layer_id] = layerDef['layer_id']
					self.gridData[key] = layer['data'][keys[idNo]]
						
						
				newId = self.gridKeys.index(key)
				
				self.resultGrid[x][y] = newId
开发者ID:bhell,项目名称:TileStache,代码行数:55,代码来源:UtfGridComposite.py

示例12: __call__

 def __call__(self, environ, start_response):
     """ Handle a request, using PATH_INFO and QUERY_STRING from environ.
     
         There are six required query string parameters: width, height,
         xmin, ymin, xmax and ymax. Layer name must be supplied in PATH_INFO.
     """
     if self.autoreload: # re-parse the config file on every request
         try:
             self.config = TileStache.parseConfigfile(self.config_path)
         except Exception, e:
             raise Core.KnownUnknown("Error loading Tilestache config file:\n%s" % str(e))
开发者ID:alalonde,项目名称:TileStache,代码行数:11,代码来源:WSGICustomTileServer.py

示例13: application

def application(environ, start_response):

    config = environ["TILESTACHE_CONFIG"]

    layer, coord, ext = TileStache.splitPathInfo(environ["PATH_INFO"])

    if not config.layers.get(layer, False):
        print >>environ["wsgi.errors"], "[gunistache] unknown layer: " + layer
        status = "404 NOT FOUND"
        data = ""

    else:

        try:
            content_type, data = TileStache.handleRequest(config.layers[layer], coord, ext)
            status = "200 OK"

        except Exception, e:
            print >>environ["wsgi.errors"], "[gunistache] failed to handle request:" + str(e)
            status = "500 SERVER ERROR"
            data = str(e)
开发者ID:straup,项目名称:tilestache-tools,代码行数:21,代码来源:httpony.py

示例14: addLayer

  def addLayer( self, layerDef, coord ):
    layer = TileStache.getTile(self.layer.config.layers[layerDef['src']], coord, 'JSON')[1]

    if layerDef['wrapper'] == None:
      layer = json.loads(layer)
    else:
      # Strip "Wrapper(...)"
      layer = json.loads(layer[(len(layerDef['wrapper'])+1):-1])

    grid_size = len(layer['grid'])

    # Init resultGrid based on given layers (if required)
    if len(self.resultGrid) == 0:
      for i in xrange(grid_size):
        self.resultGrid.append([])
        for j in xrange(grid_size):
          self.resultGrid[i].append(-1)

    layer_keys = layer['keys']

    for y in xrange(grid_size):
      line = layer['grid'][y]
      for x in xrange(grid_size):
        src_id = self.decodeId(line[x])
        
        if layer_keys[src_id] == "":
          continue

        src_key = layer_keys[src_id]

        # Add layer name attribute
        if layerDef['layer_id'] != None and self.layer_id != None:
          layer['data'][src_key][self.layer_id] = layerDef['layer_id']

        if self.resultGrid[x][y] == -1:
          cur_id = self.curId
          self.curId += 1
          cur_key = json.dumps(cur_id)

          # Set key for current point.
          self.resultGrid[x][y] = self.encodeId(cur_id)
          self.gridKeys.insert(cur_id + 1, cur_key)

          # Initialize data bucket.
          self.gridData[cur_key] = []

        else:
          cur_id = self.decodeId(self.resultGrid[x][y])
          cur_key = json.dumps(cur_id)

        self.gridData[cur_key].append(layer['data'][src_key])
开发者ID:Narrator,项目名称:TileStache,代码行数:51,代码来源:UtfGridCompositeOverlap.py

示例15: tilestache_tiles

def tilestache_tiles(request, layer_name, z, x, y, extension):
    """
    :param request:
    :param layer_name:
    :param z:
    :param x:
    :param y:
    :param extension:
    :return:

    Proxy to tilestache
    {X} - coordinate column.
    {Y} - coordinate row.
    {B} - bounding box.
    {Z} - zoom level.
    {S} - host.
    """

    config = TileStacheConfig.objects.filter(name='default')[0].config
    path_info = "%s/%s/%s/%s.%s" % (layer_name, z, x, y, extension)
    coord, extension = TileStache.splitPathInfo(path_info)[1:]
    mimetype, content = TileStache.getTile(config.layers[layer_name], coord, extension)
    return HttpResponse(content, mimetype=mimetype)
开发者ID:crindt,项目名称:uf,代码行数:23,代码来源:tilestache_views.py


注:本文中的TileStache类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。