Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_rgb_handler(use_testdb, raster_file, raster_file_xyz):
import terracotta
from terracotta.handlers import rgb
raw_img = rgb.rgb(['val21', 'x'], ['val22', 'val23', 'val24'], raster_file_xyz)
img_data = np.asarray(Image.open(raw_img))
assert img_data.shape == (*terracotta.get_settings().DEFAULT_TILE_SIZE, 3)
def test_update_config():
from terracotta import get_settings, update_settings
update_settings(DRIVER_PATH='test')
new_settings = get_settings()
assert new_settings.DRIVER_PATH == 'test'
update_settings(DEFAULT_TILE_SIZE=[50, 50])
new_settings = get_settings()
assert new_settings.DRIVER_PATH == 'test' and new_settings.DEFAULT_TILE_SIZE == (50, 50)
def test_get_rgb_stretch(client, use_testdb, raster_file_xyz):
import terracotta
settings = terracotta.get_settings()
x, y, z = raster_file_xyz
for stretch_range in ('[0,10000]', '[0,null]', '[null, 10000]', '[null,null]', 'null'):
rv = client.get(f'/rgb/val21/x/{z}/{x}/{y}.png?r=val22&g=val23&b=val24&'
f'r_range={stretch_range}&b_range={stretch_range}&g_range={stretch_range}')
assert rv.status_code == 200, rv.data
img = Image.open(BytesIO(rv.data))
assert np.asarray(img).shape == (*settings.DEFAULT_TILE_SIZE, 3)
def test_get_singleband_greyscale(client, use_testdb, raster_file_xyz):
import terracotta
settings = terracotta.get_settings()
x, y, z = raster_file_xyz
rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png')
assert rv.status_code == 200
img = Image.open(BytesIO(rv.data))
assert np.asarray(img).shape == settings.DEFAULT_TILE_SIZE
def metadata(keys: Union[Sequence[str], Mapping[str, str]]) -> Dict[str, Any]:
"""Returns all metadata for a single dataset"""
settings = get_settings()
driver = get_driver(settings.DRIVER_PATH, provider=settings.DRIVER_PROVIDER)
metadata = driver.get_metadata(keys)
metadata['keys'] = OrderedDict(zip(driver.key_names, keys))
return metadata
def inner(*args: Any, **kwargs: Any) -> Any:
try:
return fun(*args, **kwargs)
except exceptions.TileOutOfBoundsError:
# send empty image
from terracotta import get_settings, image
settings = get_settings()
return send_file(image.empty_image(settings.DEFAULT_TILE_SIZE), mimetype='image/png')
except exceptions.DatasetNotFoundError as exc:
# wrong path -> 404
if current_app.debug:
raise
return abort(404, str(exc))
except (exceptions.InvalidArgumentsError, exceptions.InvalidKeyError,
marshmallow.ValidationError) as exc:
# wrong query arguments -> 400
if current_app.debug:
raise
return abort(400, str(exc))
def colorbar(keys: Union[Sequence[str], Mapping[str, str]], *,
colormap: str = None, stretch_method: str = 'stretch',
stretch_options: Mapping[str, Any] = None, num_values: int = 100
) -> Mapping[Union[int, float], List[float]]:
"""Returns a mapping pixel value -> rgba for given image"""
stretch_options = stretch_options or {}
settings = get_settings()
driver = get_driver(settings.DRIVER_PATH, provider=settings.DRIVER_PROVIDER)
with driver.connect():
metadata = driver.get_metadata(keys)
stretch_range = image.get_stretch_range(stretch_method, metadata, **stretch_options)
pixel_values = np.linspace(stretch_range[0], stretch_range[1], num_values)
colors = image.apply_cmap(pixel_values, stretch_range, cmap=colormap)
return dict(zip(pixel_values.tolist(), colors.tolist()))
All flags must be passed before specifying a subcommand.
Example:
$ terracotta -c config.toml connect localhost:5000
"""
if ctx.invoked_subcommand is None:
click.echo(ctx.get_help())
# update settings from config file
if config is not None:
update_settings(**config)
# setup logging
settings = get_settings()
if loglevel is None:
loglevel = settings.LOGLEVEL
logs.set_logger(loglevel, catch_warnings=True)
def __init__(self, mysql_path: str) -> None:
"""Initialize the MySQLDriver.
This should not be called directly, use :func:`~terracotta.get_driver` instead.
Arguments:
mysql_path: URL to running MySQL server, in the form
``mysql://username:password@hostname/database``
"""
settings = get_settings()
self.DB_CONNECTION_TIMEOUT: int = settings.DB_CONNECTION_TIMEOUT
con_params = urlparse.urlparse(mysql_path)
if not con_params.hostname:
con_params = urlparse.urlparse(f'mysql://{mysql_path}')
assert con_params.hostname is not None
if con_params.scheme != 'mysql':
raise ValueError(f'unsupported URL scheme "{con_params.scheme}"')
self._db_args = MySQLCredentials(
host=con_params.hostname,
user=con_params.username,
def __init__(self, path: Union[str, Path]) -> None:
"""Initialize the SQLiteDriver.
This should not be called directly, use :func:`~terracotta.get_driver` instead.
Arguments:
path: File path to target SQLite database (may or may not exist yet)
"""
path = str(path)
settings = get_settings()
self.DB_CONNECTION_TIMEOUT: int = settings.DB_CONNECTION_TIMEOUT
self.LAZY_LOADING_MAX_SHAPE: Tuple[int, int] = settings.LAZY_LOADING_MAX_SHAPE
self._connection: Connection
self._connected = False
super().__init__(os.path.realpath(path))