本文整理汇总了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)
示例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
示例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)
示例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
示例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
示例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)
示例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
示例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)
示例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)
示例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
示例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
示例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))
示例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)
示例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])
示例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)