desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Get mime-type and format by file extension. This only accepts "xml".'
def getTypeByExtension(self, extension):
if (extension.lower() != 'xml'): raise KnownUnknown(('TileDataOSM only makes .xml tiles, not "%s"' % extension)) return ('text/xml', 'XML')
'Render a single tile, return a SaveableResponse instance.'
def renderTile(self, width, height, srs, coord):
db = _connect(**self.dbkwargs).cursor() prepare_database(db, coord, self.layer.projection) counts = [] db.execute('SELECT n.id, n.version, EXTRACT(epoch FROM n.tstamp),\n u.i...
''
def __init__(self, layer, filename, resample='cubic', maskband=0):
self.layer = layer fileurl = urljoin(layer.config.dirpath, filename) (scheme, h, file_path, p, q, f) = urlparse(fileurl) if (scheme not in ('', 'file')): raise Exception(('GDAL file must be on the local filesystem, not: ' + fileurl)) if (resample not in resamplings...
''
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
src_ds = gdal.Open(str(self.filename)) driver = gdal.GetDriverByName('GTiff') if src_ds.GetGCPs(): src_ds.SetProjection(src_ds.GetGCPProjection()) grayscale_src = (src_ds.RasterCount == 1) try: area_ds = driver.Create('/vsimem/output', width, height, 3) if (area_ds is None): ...
'Get mime-type and format by file extension. This only accepts "json".'
def getTypeByExtension(self, extension):
if (extension.lower() != 'json'): raise KnownUnknown(('UtfGridComposite only makes .json tiles, not "%s"' % extension)) return ('text/json', 'JSON')
'Initialize Cascadenik provider with layer and mapfile.'
def __init__(self, layer, mapfile, fonts=None, workdir=None):
self.workdir = (workdir or gettempdir()) self.mapnik = None ImageProvider.__init__(self, layer, mapfile, fonts)
'Mostly hand off functionality to Mapnik.ImageProvider.renderArea()'
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
if (self.mapnik is None): self.mapnik = mapnik.Map(0, 0) load_map(self.mapnik, str(self.mapfile), self.workdir, cache_dir=self.workdir) return ImageProvider.renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom)
''
def renderArea(self, width_, height_, srs, xmin_, ymin_, xmax_, ymax_, zoom):
merc = Proj(srs) (lon, lat) = merc(((xmin_ + xmax_) / 2), ((ymin_ + ymax_) / 2), inverse=True) zone = lon2zone(lon) hemi = lat2hemi(lat) utm = Proj(proj='utm', zone=zone, datum='WGS84') ((minlon, minlat), (maxlon, maxlat)) = (merc(xmin_, ymin_, inverse=1), merc(xmax_, ymax_, inverse=1)) ((xm...
'Initialize the Monkeycache Provider. Cache_config is a complete cache configuration dictionary that you might use in a TileStache setup (http://tilestache.org/doc/#caches). This is where Monkeycache will look for already-rendered tiles. Layer_name is the name of a layer saved in that cache. Format should match the sec...
def __init__(self, layer, cache_config, layer_name, format='PNG'):
fake_layer_dict = {'provider': {'name': 'Proxy', 'url': 'http://localhost/{Z}/{X}/{Y}.png'}} fake_config_dict = {'cache': cache_config, 'layers': {layer_name: fake_layer_dict}} fake_config = buildConfiguration(fake_config_dict, layer.config.dirpath) self.source_layer = fake_config.layers[layer_name] ...
'Pull a single tile from self.source_cache.'
def renderTile(self, width, height, srs, coord):
body = self.source_cache.read(self.source_layer, coord, self.tile_format) return ResponseWrapper(body, self.tile_format)
''
def __init__(self, config, redis_host='localhost', redis_port=6379):
TileStache.WSGITileServer.__init__(self, config) self.redis_kwargs = dict(host=redis_host, port=redis_port) self.config.cache = CacheWrap(self.config.cache, self.redis_kwargs) update_status('Created', **self.redis_kwargs)
''
def __call__(self, environ, start_response):
start = time() if (environ['PATH_INFO'] == '/status'): start_response('200 OK', [('Content-Type', 'text/plain')]) return status_response(**self.redis_kwargs) if (environ['PATH_INFO'] == '/favicon.ico'): start_response('404 Not Found', [('Content-Type', 'text/plain')]) ...
''
def __del__(self):
update_status('Destroyed', **self.redis_kwargs)
'Acquire a cache lock for this tile. Returns nothing, but blocks until the lock has been acquired.'
def lock(self, layer, coord, format):
mem = Client(self.servers) key = tile_key(layer, coord, format, self.revision, self.key_prefix) due = (_time() + layer.stale_lock_timeout) try: while (_time() < due): if mem.add((key + '-lock'), 'locked.', layer.stale_lock_timeout): return _sleep(0.2) ...
'Release a cache lock for this tile.'
def unlock(self, layer, coord, format):
mem = Client(self.servers) key = tile_key(layer, coord, format, self.revision, self.key_prefix) mem.delete((key + '-lock')) mem.disconnect_all()
'Remove a cached tile.'
def remove(self, layer, coord, format):
mem = Client(self.servers) key = tile_key(layer, coord, format, self.revision, self.key_prefix) mem.delete(key) mem.disconnect_all()
'Read a cached tile.'
def read(self, layer, coord, format):
mem = Client(self.servers) key = tile_key(layer, coord, format, self.revision, self.key_prefix) value = mem.get(key) mem.disconnect_all() if (value is None): return None return b64decode(value.encode('ascii'))
'Save a cached tile.'
def save(self, body, layer, coord, format):
mem = Client(self.servers) key = tile_key(layer, coord, format, self.revision, self.key_prefix) if (body is not None): body = b64encode(body).decode('ascii') mem.set(key, body, (layer.cache_lifespan or 0)) mem.disconnect_all()
'Two required Coordinate objects defining tile pyramid bounds. Boundaries are inclusive: upper_left_high is the left-most column, upper-most row, and highest zoom level; lower_right_low is the right-most column, furthest-dwn row, and lowest zoom level.'
def __init__(self, upper_left_high, lower_right_low):
self.upper_left_high = upper_left_high self.lower_right_low = lower_right_low
'Check a tile Coordinate against the bounds, return true/false.'
def excludes(self, tile):
if (tile.zoom > self.upper_left_high.zoom): return True if (tile.zoom < self.lower_right_low.zoom): return True _tile = tile.zoomTo(self.lower_right_low.zoom) if (_tile.column > self.lower_right_low.column): return True if (_tile.row > self.lower_right_low.row): retur...
'Single argument is a list of Bounds objects.'
def __init__(self, bounds):
self.bounds = bounds
'Check a tile Coordinate against the bounds, return false if none match.'
def excludes(self, tile):
for bound in self.bounds: if (not bound.excludes(tile)): return False return True
'Convert configured parameters to keyword args for __init__().'
@staticmethod def prepareKeywordArgs(config_dict):
return {'stack': config_dict['stack']}
'Render this image stack. Given a coordinate, return an output image with the results of all the layers in this stack pasted on in turn. Final argument is a dictionary used to temporarily cache results of layers retrieved from layer_bitmap(), to speed things up in case of repeatedly-used identical images.'
def draw_stack(self, coord, tiles):
rendered = Blit.Color(0, 0, 0, 0) for layer in self.stack: if (('zoom' in layer) and (not in_zoom(coord, layer['zoom']))): continue (source_name, mask_name, color_name) = [layer.get(k, None) for k in ('src', 'mask', 'color')] if (source_name and color_name and mask_name): ...
'Initialize a callable WSGI instance. Config parameter can be a file path string for a JSON configuration file or a configuration object with \'cache\', \'layers\', and \'dirpath\' properties. Optional autoreload boolean parameter causes config to be re-read on each request, applicable only when config is a JSON file.'...
def __init__(self, config, autoreload=False):
if (type(config) in (str, unicode, dict)): self.autoreload = autoreload self.config_path = config try: self.config = parseConfig(config) except: print('Error loading Tilestache config:') raise else: assert hasattr(config, 'cach...
''
def __call__(self, environ, start_response):
if self.autoreload: try: self.config = parseConfig(self.config_path) except Exception as e: raise Core.KnownUnknown(('Error loading Tilestache config file:\n%s' % str(e))) try: (layer, coord, ext) = splitPathInfo(environ['PATH_INFO']) except Core.K...
''
def _response(self, start_response, code, content='', headers=None):
headers = (headers or Headers([])) if content: headers.setdefault('Content-Length', str(len(content))) start_response(('%d %s' % (code, httplib.responses[code])), headers.items()) return [content]
'Convert from Coordinate object to a Point object in EPSG:900913'
def coordinateProj(self, coord):
diameter = ((2 * _pi) * 6378137) zoom = (_log(diameter) / _log(2)) coord = coord.zoomTo(zoom) point = Point(coord.column, coord.row) point.x = (point.x - (diameter / 2)) point.y = ((diameter / 2) - point.y) return point
'Convert from Point object in EPSG:900913 to a Coordinate object'
def projCoordinate(self, point):
diameter = ((2 * _pi) * 6378137) zoom = (_log(diameter) / _log(2)) coord = Coordinate(point.y, point.x, zoom) coord.column = (coord.column + (diameter / 2)) coord.row = ((diameter / 2) - coord.row) return coord
'Convert from Location object to a Point object in EPSG:900913'
def locationProj(self, location):
return self.coordinateProj(self.locationCoordinate(location))
'Convert from Point object in EPSG:900913 to a Location object'
def projLocation(self, point):
return self.coordinateLocation(self.projCoordinate(point))
'Convert from Coordinate object to a Point object in EPSG:4326'
def coordinateProj(self, coord):
return self.locationProj(self.coordinateLocation(coord))
'Convert from Point object in EPSG:4326 to a Coordinate object'
def projCoordinate(self, point):
return self.locationCoordinate(self.projLocation(point))
'Convert from Location object to a Point object in EPSG:4326'
def locationProj(self, location):
return Point(location.lon, location.lat)
'Convert from Point object in EPSG:4326 to a Location object'
def projLocation(self, point):
return Location(point.y, point.x)
''
def _description(self, layer, coord, format):
name = layer.name() tile = ('%(zoom)d/%(column)d/%(row)d' % coord.__dict__) return ' '.join((name, tile, format))
'Pretend to acquire a cache lock for this tile.'
def lock(self, layer, coord, format):
name = self._description(layer, coord, format) if self.logfunc: self.logfunc(('Test cache lock: ' + name))
'Pretend to release a cache lock for this tile.'
def unlock(self, layer, coord, format):
name = self._description(layer, coord, format) if self.logfunc: self.logfunc(('Test cache unlock: ' + name))
'Pretend to remove a cached tile.'
def remove(self, layer, coord, format):
name = self._description(layer, coord, format) if self.logfunc: self.logfunc(('Test cache remove: ' + name))
'Pretend to read a cached tile.'
def read(self, layer, coord, format):
name = self._description(layer, coord, format) if self.logfunc: self.logfunc(('Test cache read: ' + name)) return None
'Pretend to save a cached tile.'
def save(self, body, layer, coord, format):
name = self._description(layer, coord, format) if self.logfunc: self.logfunc(('Test cache save: %d bytes to %s' % (len(body), name)))
''
def _filepath(self, layer, coord, format):
l = layer.name() z = ('%d' % coord.zoom) e = format.lower() e += ((self._is_compressed(format) and '.gz') or '') if (self.dirs == 'safe'): x = ('%06d' % coord.column) y = ('%06d' % coord.row) (x1, x2) = (x[:3], x[3:]) (y1, y2) = (y[:3], y[3:]) filepath = os.se...
''
def _fullpath(self, layer, coord, format):
filepath = self._filepath(layer, coord, format) fullpath = pathjoin(self.cachepath, filepath) return fullpath
''
def _lockpath(self, layer, coord, format):
return (self._fullpath(layer, coord, format) + '.lock')
'Acquire a cache lock for this tile. Returns nothing, but blocks until the lock has been acquired. Lock is implemented as an empty directory next to the tile file.'
def lock(self, layer, coord, format):
lockpath = self._lockpath(layer, coord, format) due = (time.time() + layer.stale_lock_timeout) while True: try: umask_old = os.umask(self.umask) if (time.time() > due): try: os.rmdir(lockpath) except OSError: ...
'Release a cache lock for this tile. Lock is implemented as an empty directory next to the tile file.'
def unlock(self, layer, coord, format):
lockpath = self._lockpath(layer, coord, format) try: os.rmdir(lockpath) except OSError: pass
'Remove a cached tile.'
def remove(self, layer, coord, format):
fullpath = self._fullpath(layer, coord, format) try: os.remove(fullpath) except OSError as e: if (e.errno != 2): raise
'Read a cached tile.'
def read(self, layer, coord, format):
fullpath = self._fullpath(layer, coord, format) if (not exists(fullpath)): return None age = (time.time() - os.stat(fullpath).st_mtime) if (layer.cache_lifespan and (age > layer.cache_lifespan)): return None elif self._is_compressed(format): return gzip.open(fullpath, 'r').re...
'Save a cached tile.'
def save(self, body, layer, coord, format):
fullpath = self._fullpath(layer, coord, format) try: umask_old = os.umask(self.umask) os.makedirs(dirname(fullpath), (511 & (~ self.umask))) except OSError as e: if (e.errno != 17): raise finally: os.umask(umask_old) suffix = ('.' + format.lower()) suf...
'Acquire a cache lock for this tile in the first tier. Returns nothing, but blocks until the lock has been acquired.'
def lock(self, layer, coord, format):
return self.tiers[0].lock(layer, coord, format)
'Release a cache lock for this tile in the first tier.'
def unlock(self, layer, coord, format):
return self.tiers[0].unlock(layer, coord, format)
'Remove a cached tile from every tier.'
def remove(self, layer, coord, format):
for (index, cache) in enumerate(self.tiers): cache.remove(layer, coord, format)
'Read a cached tile. Start at the first tier and work forwards until a cached tile is found. When found, save it back to the earlier tiers for faster access on future requests.'
def read(self, layer, coord, format):
for (index, cache) in enumerate(self.tiers): body = cache.read(layer, coord, format) if body: for cache in self.tiers[:index]: cache.save(body, layer, coord, format) return body return None
'Save a cached tile. Every tier gets a saved copy.'
def save(self, body, layer, coord, format):
for (index, cache) in enumerate(self.tiers): cache.save(body, layer, coord, format)
'Acquire a cache lock for this tile. Returns nothing, but blocks until the lock has been acquired. Does nothing and returns immediately if `use_locks` is false.'
def lock(self, layer, coord, format):
if (not self.use_locks): return key_name = tile_key(layer, coord, format, self.path) due = (_time() + layer.stale_lock_timeout) while (_time() < due): if (not self.bucket.get_key((key_name + '-lock'))): break _sleep(0.2) key = self.bucket.new_key((key_name + '-loc...
'Release a cache lock for this tile.'
def unlock(self, layer, coord, format):
if (not self.use_locks): return key_name = tile_key(layer, coord, format, self.path) self.bucket.delete_key((key_name + '-lock'))
'Remove a cached tile.'
def remove(self, layer, coord, format):
key_name = tile_key(layer, coord, format, self.path) self.bucket.delete_key(key_name)
'Read a cached tile.'
def read(self, layer, coord, format):
key_name = tile_key(layer, coord, format, self.path) key = self.bucket.get_key(key_name) if (key is None): return None if layer.cache_lifespan: t = timegm(strptime(key.last_modified, '%a, %d %b %Y %H:%M:%S %Z')) if ((time() - t) > layer.cache_lifespan): ...
'Save a cached tile.'
def save(self, body, layer, coord, format):
key_name = tile_key(layer, coord, format, self.path) key = self.bucket.new_key(key_name) (content_type, encoding) = guess_type(('example.' + format)) headers = ((content_type and {'Content-Type': content_type}) or {}) key.set_contents_from_string(body, headers, policy=self.policy, reduced_redundancy...
''
def save(self, out, format):
if (format == 'WKT'): if ('wkt' in self.content['crs']): out.write(self.content['crs']['wkt']) else: out.write(_sref_4326().ExportToWkt()) return if (format in ('GeoJSON', 'GeoBSON', 'GeoAMF')): content = self.content if ('wkt' in content['crs']): ...
'Convert configured parameters to keyword args for __init__().'
@staticmethod def prepareKeywordArgs(config_dict):
kwargs = dict() kwargs['driver'] = config_dict['driver'] kwargs['parameters'] = config_dict['parameters'] kwargs['id_property'] = config_dict.get('id_property', None) kwargs['properties'] = config_dict.get('properties', None) kwargs['projected'] = bool(config_dict.get('projected', False)) kw...
'Render a single tile, return a VectorResponse instance.'
def renderTile(self, width, height, srs, coord):
(layer, ds) = _open_layer(self.driver, self.parameters, self.layer.config.dirpath) features = _get_features(coord, self.properties, self.layer.projection, layer, self.clipped, self.projected, self.spacing, self.id_property, self.skip_empty_fields) response = {'type': 'FeatureCollection', 'features': feature...
'Get mime-type and format by file extension. This only accepts "geojson" for the time being.'
def getTypeByExtension(self, extension):
if (extension.lower() == 'geojson'): return ('application/json', 'GeoJSON') elif (extension.lower() == 'arcjson'): return ('application/json', 'ArcJSON') elif (extension.lower() == 'geobson'): return ('application/x-bson', 'GeoBSON') elif (extension.lower() == 'arcbson'): ...
'Initialize Mapnik provider with layer and mapfile. XML mapfile keyword arg comes from TileStache config, and is an absolute path by the time it gets here.'
def __init__(self, layer, mapfile, fonts=None, scale_factor=None):
maphref = urljoin(layer.config.dirpath, mapfile) (scheme, h, path, q, p, f) = urlparse(maphref) if (scheme in ('file', '')): self.mapfile = path else: self.mapfile = maphref self.layer = layer self.mapnik = None engine = mapnik.FontEngine.instance() if fonts: font...
'Convert configured parameters to keyword args for __init__().'
@staticmethod def prepareKeywordArgs(config_dict):
kwargs = {'mapfile': config_dict['mapfile']} if ('fonts' in config_dict): kwargs['fonts'] = config_dict['fonts'] if ('scale factor' in config_dict): kwargs['scale_factor'] = int(config_dict['scale factor']) return kwargs
''
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
start_time = time() if global_mapnik_lock.acquire(): try: if (self.mapnik is None): self.mapnik = get_mapnikMap(self.mapfile) logging.debug('TileStache.Mapnik.ImageProvider.renderArea() %.3f to load %s', (time() - start_time), self.mapfile) ...
'Initialize Mapnik grid provider with layer and mapfile. XML mapfile keyword arg comes from TileStache config, and is an absolute path by the time it gets here.'
def __init__(self, layer, mapfile, fields=None, layers=None, layer_index=0, scale=4, layer_id_key=None):
self.mapnik = None self.layer = layer maphref = urljoin(layer.config.dirpath, mapfile) (scheme, h, path, q, p, f) = urlparse(maphref) if (scheme in ('file', '')): self.mapfile = path else: self.mapfile = maphref self.scale = scale self.layer_id_key = layer_id_key if l...
'Convert configured parameters to keyword args for __init__().'
@staticmethod def prepareKeywordArgs(config_dict):
kwargs = {'mapfile': config_dict['mapfile']} for key in ('fields', 'layers', 'layer_index', 'scale', 'layer_id_key'): if (key in config_dict): kwargs[key] = config_dict[key] return kwargs
''
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
start_time = time() if global_mapnik_lock.acquire(): try: if (self.mapnik is None): self.mapnik = get_mapnikMap(self.mapfile) logging.debug('TileStache.Mapnik.GridProvider.renderArea() %.3f to load %s', (time() - start_time), self.mapfile) ...
'Get mime-type and format by file extension. This only accepts "json".'
def getTypeByExtension(self, extension):
if (extension.lower() != 'json'): raise KnownUnknown(('MapnikGrid only makes .json tiles, not "%s"' % extension)) return ('application/json; charset=utf-8', 'JSON')
'Return a cropped grid response.'
def crop(self, bbox):
(minchar, minrow, maxchar, maxrow) = [(v / self.scale) for v in bbox] (keys, data) = (self.content['keys'], self.content.get('data', None)) grid = [row[minchar:maxchar] for row in self.content['grid'][minrow:maxrow]] cropped = dict(keys=keys, data=data, grid=grid) return SaveableResponse(cropped, se...
'Return True if this is really a metatile with a buffer or multiple tiles. A default 1x1 metatile with buffer=0 is not for real.'
def isForReal(self):
return ((self.buffer > 0) or (self.rows > 1) or (self.columns > 1))
'Return a new coordinate for the upper-left corner of a metatile. This is useful as a predictable way to refer to an entire metatile by one of its sub-tiles, currently needed to do locking correctly.'
def firstCoord(self, coord):
return self.allCoords(coord)[0]
'Return a list of coordinates for a complete metatile. Results are guaranteed to be ordered left-to-right, top-to-bottom.'
def allCoords(self, coord):
(rows, columns) = (int(self.rows), int(self.columns)) row = (rows * (int(coord.row) / rows)) column = (columns * (int(coord.column) / columns)) coords = [] for r in range(rows): for c in range(columns): coords.append(Coordinate((row + r), (column + c), coord.zoom)) return coo...
'Figure out what I\'m called, return a name if there is one. Layer names are stored in the Configuration object, so config.layers must be inspected to find a matching name.'
def name(self):
for (name, layer) in self.config.layers.items(): if (layer is self): return name return None
'Get status code, headers, and a tile binary for a given request layer tile. Arguments: - coord: one ModestMaps.Core.Coordinate corresponding to a single tile. - extension: filename extension to choose response type, e.g. "png" or "jpg". - ignore_cached: always re-render the tile, whether it\'s in the cache or not. Thi...
def getTileResponse(self, coord, extension, ignore_cached=False):
start_time = time() (mimetype, format) = self.getTypeByExtension(extension) status_code = 200 headers = Headers([('Content-Type', mimetype)]) body = None cache = self.config.cache if (not ignore_cached): try: body = cache.read(self, coord, format) except TheTileLe...
'Return True if we have a real metatile and the provider is OK with it.'
def doMetatile(self):
return (self.metatile.isForReal() and hasattr(self.provider, 'renderArea'))
'Render a tile for a coordinate, return PIL Image-like object. Perform metatile slicing here as well, if required, writing the full set of rendered tiles to cache as we go. Note that metatiling and pass-through mode of a Provider are mutually exclusive options'
def render(self, coord, format):
if (self.bounds and self.bounds.excludes(coord)): raise NoTileLeftBehind(Image.new('RGBA', (self.dim, self.dim), (0, 0, 0, 0))) srs = self.projection.srs (xmin, ymin, xmax, ymax) = self.envelope(coord) (width, height) = (self.dim, self.dim) provider = self.provider metatile = self.metati...
'Projected rendering envelope (xmin, ymin, xmax, ymax) for a Coordinate.'
def envelope(self, coord):
ul = self.projection.coordinateProj(coord) lr = self.projection.coordinateProj(coord.down().right()) return (min(ul.x, lr.x), min(ul.y, lr.y), max(ul.x, lr.x), max(ul.y, lr.y))
'Projected rendering envelope (xmin, ymin, xmax, ymax) for a metatile.'
def metaEnvelope(self, coord):
buffer = (float(self.metatile.buffer) / self.dim) coords = self.metatile.allCoords(coord) ul = coords[0].left(buffer).up(buffer) lr = coords[(-1)].right((1 + buffer)).down((1 + buffer)) ul = self.projection.coordinateProj(ul) lr = self.projection.coordinateProj(lr) return (min(ul.x, lr.x), m...
'Pixel width and height of full rendered image for a metatile.'
def metaSize(self, coord):
buffer = (float(self.metatile.buffer) / self.dim) width = int((self.dim * ((buffer * 2) + self.metatile.columns))) height = int((self.dim * ((buffer * 2) + self.metatile.rows))) return (width, height)
'List of all coords in a metatile and their x, y offsets in a parent image.'
def metaSubtiles(self, coord):
subtiles = [] coords = self.metatile.allCoords(coord) for other in coords: r = (other.row - coords[0].row) c = (other.column - coords[0].column) x = ((c * self.dim) + self.metatile.buffer) y = ((r * self.dim) + self.metatile.buffer) subtiles.append((other, x, y)) ...
'Get mime-type and PIL format by file extension.'
def getTypeByExtension(self, extension):
if hasattr(self.provider, 'getTypeByExtension'): return self.provider.getTypeByExtension(extension) elif (extension.lower() == 'png'): return ('image/png', 'PNG') elif (extension.lower() == 'jpg'): return ('image/jpeg', 'JPEG') else: raise KnownUnknown(('Unknown extens...
'Optional arguments are added to self.jpeg_options for pickup when saving. More information about options: http://effbot.org/imagingbook/format-jpeg.htm'
def setSaveOptionsJPEG(self, quality=None, optimize=None, progressive=None):
if (quality is not None): self.jpeg_options['quality'] = int(quality) if (optimize is not None): self.jpeg_options['optimize'] = bool(optimize) if (progressive is not None): self.jpeg_options['progressive'] = bool(progressive)
'Optional arguments are added to self.png_options for pickup when saving. Palette argument is a URL relative to the configuration file, and it implies bits and optional transparency options. More information about options: http://effbot.org/imagingbook/format-png.htm'
def setSaveOptionsPNG(self, optimize=None, palette=None, palette256=None):
if (optimize is not None): self.png_options['optimize'] = bool(optimize) if (palette is not None): palette = urljoin(self.config.dirpath, palette) (palette, bits, t_index) = load_palette(palette) (self.bitmap_palette, self.png_options['bits']) = (palette, bits) if (t_inde...
'Return a guaranteed instance of PIL.Image.'
def image(self):
if (self._image is None): self._image = Image.open(self.buffer) return self._image
'Initialize Proxy provider with layer and url.'
def __init__(self, layer, url=None, provider_name=None, timeout=None):
if url: self.provider = ModestMaps.Providers.TemplatedMercatorProvider(url) elif provider_name: if (provider_name in ModestMaps.builtinProviders): self.provider = ModestMaps.builtinProviders[provider_name]() else: raise Exception(('Unkown Modest Maps prov...
'Convert configured parameters to keyword args for __init__().'
@staticmethod def prepareKeywordArgs(config_dict):
kwargs = dict() if ('url' in config_dict): kwargs['url'] = config_dict['url'] if ('provider' in config_dict): kwargs['provider_name'] = config_dict['provider'] if ('timeout' in config_dict): kwargs['timeout'] = config_dict['timeout'] return kwargs
''
def renderTile(self, width, height, srs, coord):
img = None urls = self.provider.getTileUrls(coord) proxy_support = urllib2.ProxyHandler() url_opener = urllib2.build_opener(proxy_support) for url in urls: body = url_opener.open(url, timeout=self.timeout).read() tile = Verbatim(body) if (len(urls) == 1): return t...
'Initialize a UrlTemplate provider with layer and template string. http://docs.python.org/library/string.html#template-strings'
def __init__(self, layer, template, referer=None, source_projection=None, timeout=None):
self.layer = layer self.template = Template(template) self.referer = referer self.source_projection = source_projection self.timeout = timeout
'Convert configured parameters to keyword args for __init__().'
@staticmethod def prepareKeywordArgs(config_dict):
kwargs = {'template': config_dict['template']} if ('referer' in config_dict): kwargs['referer'] = config_dict['referer'] if ('source projection' in config_dict): kwargs['source_projection'] = Geography.getProjectionByName(config_dict['source projection']) if ('timeout' in config_di...
'Return an image for an area. Each argument (width, height, etc.) is substituted into the template.'
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
if (self.source_projection is not None): ne_location = self.layer.projection.projLocation(Point(xmax, ymax)) ne_point = self.source_projection.locationProj(ne_location) ymax = ne_point.y xmax = ne_point.x sw_location = self.layer.projection.projLocation(Point(xmin, ymin)) ...
'Read configuration and verify successful read'
def test_config(self):
config_content = {'layers': {'memcache_osm': {'provider': {'name': 'proxy', 'url': 'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png'}}}, 'cache': {'name': 'Memcache', 'servers': ['127.0.0.1:11211'], 'revision': 4}} config = parseConfig(config_content) self.assertEqual(config.cache.servers, ['127.0.0.1:11211']...
'Fetch tile from OSM using Proxy provider (web mercator)'
def test_proxy_mercator(self):
config_file_content = '\n {\n "layers":{\n "osm":{\n "provider":{\n ...
'Fetch two WGS84 tiles from WMS using bbox'
def test_url_template_wgs84(self):
config_file_content = '\n {\n "layers":{\n "osgeo_wms":{\n "projection":"WGS84",\n ...
'Fetch custom binary result using URL Template(result should not be modified)'
def test_url_template_custom_binary(self):
config_file_content = '\n {\n "layers":{\n "local_layer":{\n "projection":"WGS84",\n ...
'Create 3 points (2 on west, 1 on east hemisphere) and retrieve as geojson. 2 points should be returned in western hemisphere and 1 on eastern at zoom level 0 (clip on)'
def test_points_geojson(self):
self.defineGeometry('POINT') point_sf = Point((-122.4183), 37.775) point_berlin = Point(13.4127, 52.5233) point_lima = Point((-77.0283), 12.0433) self.insertTestRow(point_sf.wkt, 'San Francisco') self.insertTestRow(point_berlin.wkt, 'Berlin') self.insertTestRow(point_lima.wkt, 'Lima') ...
'Create a line that goes from west to east (clip on)'
def test_linestring_geojson(self):
self.defineGeometry('LINESTRING') geom = LineString([((-180), 32), (180, 32)]) self.insertTestRow(geom.wkt) (tile_mimetype, tile_content) = utils.request(self.config_file_content, 'vector_test', 'geojson', 0, 0, 0) self.assertTrue(tile_mimetype.endswith('/json')) geojson_result = json.loads(tile...
'Create a polygon to cover the world and make sure it is "similar" (clip on)'
def test_polygon_geojson(self):
self.defineGeometry('POLYGON') geom = Polygon([((-180), (-90)), (180, (-90)), (180, 90), ((-180), 90), ((-180), (-90))]) self.insertTestRow(geom.wkt) (tile_mimetype, tile_content) = utils.request(self.config_file_content, 'vector_test', 'geojson', 0, 0, 0) self.assertTrue(tile_mimetype.endswith('/js...
'Fetch tile and check the existence in memcached'
def test_memcache(self):
config_file_content = '\n {\n "layers":{\n "memcache_osm":{\n "provider":{\n ...