def test_API_functionError(): """Add and parse route.""" app = API(app_name="test") funct = Mock(__name__="Mock", side_effect=Exception("hey something went wrong")) app._add_route("/test/<user>", funct, methods=["GET"], cors=True) event = { "path": "/test/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } resp = { "body": '{"errorMessage": "hey something went wrong"}', "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "application/json", }, "statusCode": 500, } res = app(event, {}) assert res == resp # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h)
def test_headersNull(): """Add and parse route.""" app = API(app_name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<user>", funct, methods=["GET"], cors=True) event = { "path": "/test/remotepixel", "httpMethod": "GET", "headers": None, "queryStringParameters": {}, } resp = { "body": "heyyyy", "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain", }, "statusCode": 200, } res = app(event, {}) assert res == resp funct.assert_called_with(user="******")
def test_API_Post(): """SHould work as expected on POST request.""" app = API(app_name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<user>", funct, methods=["GET", "POST"], cors=True) event = { "path": "/test/remotepixel", "httpMethod": "POST", "headers": {}, "queryStringParameters": {}, "body": b"0001", } resp = { "body": "heyyyy", "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET,POST", "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain", }, "statusCode": 200, } res = app(event, {}) assert res == resp funct.assert_called_with(user="******", body=b"0001") event = { "path": "/test/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } resp = { "body": "heyyyy", "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET,POST", "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain", }, "statusCode": 200, } res = app(event, {}) assert res == resp funct.assert_called_with(user="******") # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h)
def test_API_logDebug(): """Should work as expected.""" app = API(app_name="test", debug=True) assert app.log.getEffectiveLevel() == 10 # DEBUG # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h)
def test_API_multipleRoute(): """Should work as expected.""" app = API(app_name="test") @app.route("/<user>", methods=["GET"], cors=True) @app.route("/<user>@<int:num>", methods=["GET"], cors=True) def print_id(user, num=None, params=None): return ( "OK", "application/json", json.dumps({ "user": user, "num": num, "params": params }), ) event = { "path": "/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } headers = { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "application/json", } res = app(event, {}) body = json.loads(res["body"]) assert res["statusCode"] == 200 assert res["headers"] == headers assert body["user"] == "remotepixel" assert not body.get("num") assert not body.get("params") event = { "path": "/remotepixel@1", "httpMethod": "GET", "headers": {}, "queryStringParameters": { "params": "1" }, } res = app(event, {}) body = json.loads(res["body"]) assert res["statusCode"] == 200 assert res["headers"] == headers assert body["user"] == "remotepixel" assert body["num"] == 1 assert body["params"] == "1" # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h)
def test_API_init(): """Should work as expected.""" app = API(app_name="test") assert app.app_name == "test" assert not app.routes assert not app.debug assert app.log.getEffectiveLevel() == 40 # ERROR # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h)
def test_API_noLog(): """Should work as expected.""" app = API(app_name="test", configure_logs=False) assert app.app_name == "test" assert not app.routes assert not app.debug assert app.log # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h)
def test_API_encoding(): """Test b64 encoding.""" app = API(app_name="test") body = b"thisisafakeencodedjpeg" b64body = base64.b64encode(body).decode() funct = Mock(__name__="Mock", return_value=("OK", "image/jpeg", body)) app._add_route("/test/<user>.jpg", funct, methods=["GET"], cors=True) event = { "path": "/test/remotepixel.jpg", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } resp = { "body": body, "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "image/jpeg", }, "statusCode": 200, } res = app(event, {}) assert res == resp app._add_route( "/test_encode/<user>.jpg", funct, methods=["GET"], cors=True, binary_b64encode=True, ) event = { "path": "/test_encode/remotepixel.jpg", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } resp = { "body": b64body, "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "image/jpeg", }, "isBase64Encoded": True, "statusCode": 200, } res = app(event, {}) assert res == resp
def test_API_ctx(): """Should work as expected and pass ctx and evt to the function.""" app = API(app_name="test") @app.route("/<id>", methods=["GET"], cors=True) @app.pass_event @app.pass_context def print_id(ctx, evt, id, params=None): return ( "OK", "application/json", { "ctx": ctx, "evt": evt, "id": id, "params": params }, ) event = { "path": "/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": { "params": "1" }, } headers = { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "application/json", } res = app(event, {"ctx": "jqtrde"}) body = res["body"] assert res["headers"] == headers assert res["statusCode"] == 200 assert body["id"] == "remotepixel" assert body["params"] == "1" assert body["evt"] == event assert body["ctx"] == {"ctx": "jqtrde"} # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h)
def test_API_addRoute(): """Add and parse route.""" app = API(app_name="test") assert not app.routes app._add_route("/endpoint/test/<id>", funct, methods=["GET"], cors=True, token="yo") assert app.routes with pytest.raises(ValueError): app._add_route("/endpoint/test/<id>", funct, methods=["GET"], cors=True) with pytest.raises(TypeError): app._add_route("/endpoint/test/<id>", funct, methods=["GET"], c=True) # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h)
def test_API_compression(): """Test compression and base64.""" body = b"thisisafakeencodedjpeg" gzip_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16) gzbody = gzip_compress.compress(body) + gzip_compress.flush() b64gzipbody = base64.b64encode(gzbody).decode() app = API(app_name="test") funct = Mock(__name__="Mock", return_value=("OK", "image/jpeg", body)) app._add_route( "/test_compress/<user>.jpg", funct, methods=["GET"], cors=True, payload_compression_method="gzip", ) # Should compress because "Accept-Encoding" is in header event = { "path": "/test_compress/remotepixel.jpg", "httpMethod": "GET", "headers": { "Accept-Encoding": "gzip, deflate" }, "queryStringParameters": {}, } resp = { "body": gzbody, "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Encoding": "gzip", "Content-Type": "image/jpeg", }, "statusCode": 200, } res = app(event, {}) assert res == resp # Should not compress because "Accept-Encoding" is missing in header event = { "path": "/test_compress/remotepixel.jpg", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } resp = { "body": body, "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "image/jpeg", }, "statusCode": 200, } res = app(event, {}) assert res == resp # Should compress and encode to base64 app._add_route( "/test_compress_b64/<user>.jpg", funct, methods=["GET"], cors=True, payload_compression_method="gzip", binary_b64encode=True, ) event = { "path": "/test_compress_b64/remotepixel.jpg", "httpMethod": "GET", "headers": { "Accept-Encoding": "gzip, deflate" }, "queryStringParameters": {}, } resp = { "body": b64gzipbody, "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Encoding": "gzip", "Content-Type": "image/jpeg", }, "isBase64Encoded": True, "statusCode": 200, } res = app(event, {}) assert res == resp funct = Mock( __name__="Mock", return_value=("OK", "application/json", json.dumps({"test": 0})), ) # Should compress and encode to base64 app._add_route( "/test_compress_b64/<user>.json", funct, methods=["GET"], cors=True, payload_compression_method="gzip", binary_b64encode=True, ) event = { "path": "/test_compress_b64/remotepixel.json", "httpMethod": "GET", "headers": { "Accept-Encoding": "gzip, deflate" }, "queryStringParameters": {}, } body = bytes(json.dumps({"test": 0}), "utf-8") gzip_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16) gzbody = gzip_compress.compress(body) + gzip_compress.flush() b64gzipbody = base64.b64encode(gzbody).decode() resp = { "body": b64gzipbody, "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Encoding": "gzip", "Content-Type": "application/json", }, "isBase64Encoded": True, "statusCode": 200, } res = app(event, {}) assert res == resp event = { "path": "/test_compress_b64/remotepixel.json", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } resp = { "body": json.dumps({"test": 0}), "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "application/json", }, "statusCode": 200, } res = app(event, {}) assert res == resp
import urllib import numpy from rio_tiler import main import rasterio from rasterio import warp from rio_tiler.profiles import img_profiles from rio_tiler.mercator import get_zooms from rio_tiler.utils import array_to_image, get_colormap, expression from remotepixel_tiler.utils import _postprocess from lambda_proxy.proxy import API APP = API(name="cogeo-tiler") class TilerError(Exception): """Base exception class.""" @APP.route( "/tilejson.json", methods=["GET"], cors=True, payload_compression_method="gzip", binary_b64encode=True, ttl=3600, tag=["metadata"], )
from rasterio.warp import transform_bounds from rio_tiler import cbers, utils from rio_tiler.profiles import img_profiles from rio_tiler.utils import array_to_image, get_colormap, expression, linear_rescale, _chunks from rio_tiler.errors import TileOutsideBounds, InvalidBandName, InvalidCBERSSceneId from aws_sat_api.search import cbers as cbers_search from rio_color.operations import parse_operations from rio_color.utils import scale_dtype, to_math_type from remotepixel_tiler.utils import _postprocess, rescale_intensity from lambda_proxy.proxy import API APP = API(name="cbers-tiler") # CBERS CBERS_BUCKET = "s3://cbers-pds" MAX_THREADS = int( os.environ.get("MAX_THREADS", multiprocessing.cpu_count() * 5)) def cbers_tile(sceneid, tile_x, tile_y, tile_z, bands, tilesize=256, percents='',
"""app.landsat: handle request for Landsat-tiler""" import re import json import numpy as np from rio_tiler import landsat8 from rio_tiler.utils import array_to_img, linear_rescale, get_colormap, expression from aws_sat_api.search import landsat as landsat_search from lambda_proxy.proxy import API APP = API(app_name="landsat-tiler") class LandsatTilerError(Exception): """Base exception class""" @APP.route('/search', methods=['GET'], cors=True) def search(): """Handle search requests """ query_args = APP.current_request.query_params query_args = query_args if isinstance(query_args, dict) else {} path = query_args['path'] row = query_args['row'] full = query_args.get('full', True)
"""app.landsat: handle request for Landsat-tiler""" import re import json from functools import reduce import numpy as np import numexpr as ne from rio_tiler import landsat8 from rio_tiler.utils import array_to_img, linear_rescale, get_colormap from lambda_proxy.proxy import API LANDSAT_APP = API(app_name="landsat-tiler") RATIOS = { 'ndvi': { 'eq': '(b5 - b4) / (b5 + b4)', 'rg': [-1, 1] }, 'ndsi': { 'eq': '(b2 - b5) / (b2 + b5)', 'rg': [-1, 1] }, 'ndwi': { 'eq': '(b5 - b6) / (b5 + b6)', 'rg': [-1, 1] }, 'ac-index': { 'eq': '(b1 - b2) / (b1 + b2)',
def test_API_routeToken(monkeypatch): """Validate tokens.""" monkeypatch.setenv("TOKEN", "yo") app = API(app_name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<user>", funct, methods=["GET"], cors=True, token=True) event = { "path": "/test/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": { "access_token": "yo" }, } resp = { "body": "heyyyy", "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain", }, "statusCode": 200, } res = app(event, {}) assert res == resp funct.assert_called_with(user="******") event = { "path": "/test/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": { "inp": 1, "access_token": "yo" }, } resp = { "body": "heyyyy", "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain", }, "statusCode": 200, } res = app(event, {}) assert res == resp funct.assert_called_with(user="******", inp=1) event = { "path": "/test/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": { "access_token": "yep" }, } resp = { "body": '{"message": "Invalid access token"}', "headers": { "Content-Type": "application/json" }, "statusCode": 500, } res = app(event, {}) assert res == resp event = { "path": "/test/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": { "token": "yo" }, } resp = { "body": '{"message": "Invalid access token"}', "headers": { "Content-Type": "application/json" }, "statusCode": 500, } res = app(event, {}) assert res == resp monkeypatch.delenv("TOKEN", raising=False) event = { "path": "/test/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": { "access_token": "yo" }, } resp = { "body": '{"message": "Invalid access token"}', "headers": { "Content-Type": "application/json" }, "statusCode": 500, } res = app(event, {}) assert res == resp # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h)
import urllib import mercantile import rasterio from rasterio import warp from rio_tiler import sentinel2, utils from rio_tiler.mercator import get_zooms from rio_tiler.profiles import img_profiles from rio_tiler.utils import array_to_image, get_colormap, expression from rio_tiler.errors import TileOutsideBounds, InvalidBandName, InvalidSentinelSceneId from remotepixel_tiler.utils import _postprocess, rescale_intensity from lambda_proxy.proxy import API APP = API(name="sentinel-tiler") SENTINEL_BUCKET = "s3://sentinel-s2-l1c" SENTINEL_BANDS = [ "01", "02", "03", "04", "05", "06", "07", "08", "8A", "09", "10", "11", "12" ] MAX_THREADS = int( os.environ.get("MAX_THREADS", multiprocessing.cpu_count() * 5)) def sentinel2_tile(sceneid, tile_x, tile_y, tile_z, bands=("04", "03", "02"),
cmap.register("custom_above", custom_cmaps.above_cmap) session = boto3_session() s3_client = session.client("s3") aws_session = AWSSession(session=session) PIXSEL_METHODS = { "first": defaults.FirstMethod, "highest": defaults.HighestMethod, "lowest": defaults.LowestMethod, "mean": defaults.MeanMethod, "median": defaults.MedianMethod, "stdev": defaults.StdevMethod, "bdix_stdev": custom_methods.bidx_stddev, } app = API(name="cogeo-mosaic-tiler") params = dict(payload_compression_method="gzip", binary_b64encode=True) if os.environ.get("CORS"): params["cors"] = True # We are storing new mosaicjson on AWS S3, if a user wants to change the storage # You could just change this function # e.g # def _create_mosaic_path(mosaicid: str,) -> str: # """Translate mosaicid to dynamoDB path.""" # return f"dynamodb:///{mosaicid}" def _create_mosaic_path( mosaicid: str,
"""app.sentinel: handle request for Sentinel-tiler""" import re import json import numpy as np from rio_tiler import sentinel2 from rio_tiler.utils import array_to_img, linear_rescale, get_colormap, expression, b64_encode_img from aws_sat_api.search import sentinel2 as sentinel_search from lambda_proxy.proxy import API APP = API(app_name="sentinel-tiler") class SentinelTilerError(Exception): """Base exception class""" @APP.route('/sentinel/search', methods=['GET'], cors=True) def search(): """Handle search requests """ query_args = APP.current_request.query_params query_args = query_args if isinstance(query_args, dict) else {} utm = query_args['utm'] lat = query_args['lat']
import re import json import numpy from rio_tiler import main from rio_tiler.profiles import img_profiles from rio_tiler.utils import array_to_image, get_colormap, expression, linear_rescale from rio_color.operations import parse_operations from rio_color.utils import scale_dtype, to_math_type from lambda_proxy.proxy import API APP = API(app_name="cogeo-tiler") def _postprocess( tile: numpy.ndarray, mask: numpy.ndarray, tilesize: int, rescale: str = None, color_formula: str = None, ) -> Tuple[numpy.ndarray, numpy.ndarray]: if tile is None: # Return empty tile tile = numpy.zeros((1, tilesize, tilesize), dtype=numpy.uint8) mask = numpy.zeros((tilesize, tilesize), dtype=numpy.uint8) else:
mapzen_elevation_rgb, ) from rio_tiler.profiles import img_profiles from rio_tiler.mercator import get_zooms from rio_tiler_mosaic.mosaic import mosaic_tiler from rio_tiler_mvt.mvt import encoder as mvtEncoder from rio_rgbify import encoders from rio_color.operations import parse_operations from rio_color.utils import scale_dtype, to_math_type from .utils import get_area_stats from lambda_proxy.proxy import API APP = API(name="tiler") class TilerError(Exception): """Base exception class.""" @APP.route( "/metadata", methods=["GET"], cors=True, payload_compression_method="gzip", binary_b64encode=True, ) def meta( url,
from rio_tiler import main from rio_rgbify import encoders from rio_tiler.profiles import img_profiles from rio_tiler.utils import ( array_to_image, get_colormap, expression, mapzen_elevation_rgb, ) from .utils import _postprocess from lambda_proxy.proxy import API APP = API(app_name="lambda-tiler") class TilerError(Exception): """Base exception class.""" @APP.route( "/bounds", methods=["GET"], cors=True, payload_compression_method="gzip", binary_b64encode=True, ) def bounds(url=None): """Handle bounds requests."""
"""app.cbers: handle request for CBERS-tiler""" import re import json import numpy as np from rio_tiler import cbers from rio_tiler.utils import array_to_img, linear_rescale, get_colormap, expression from aws_sat_api.search import cbers as cbers_search from lambda_proxy.proxy import API APP = API(app_name="cbers-tiler") class CbersTilerError(Exception): """Base exception class""" @APP.route('/search', methods=['GET'], cors=True) def search(): """Handle search requests """ query_args = APP.current_request.query_params query_args = query_args if isinstance(query_args, dict) else {} path = query_args['path'] row = query_args['row']
import mercantile from rasterio.transform import from_bounds from rio_tiler.utils import expression as expressionTiler, array_to_image, get_colormap from rio_tiler.profiles import img_profiles from rio_tiler.landsat8 import tile as landsatTiler from rio_tiler_mosaic.mosaic import mosaic_tiler from awspds_mosaic.utils import get_mosaic_content, get_assets, post_process_tile from awspds_mosaic.pixel_methods import pixSel from PIL import Image from lambda_proxy.proxy import API app = API(name="awspds-mosaic-landsat-tiles", debug=False) @app.route( "/<regex([0-9A-Fa-f]{56}):mosaicid>/tilejson.json", methods=["GET"], cors=True, payload_compression_method="gzip", binary_b64encode=True, tag=["metadata"], ) def tilejson(mosaicid: str, tile_format="png", tile_scale: int = 1, **kwargs: Any) -> Tuple[str, str, str]: """
from rio_tiler.utils import ( array_to_image, get_colormap, expression, linear_rescale, _chunks, ) from rio_color.operations import parse_operations from rio_color.utils import scale_dtype, to_math_type from cogeo_tiler.ogc import wmts_template from lambda_proxy.proxy import API app = API(name="cogeo-tiler") aws_session = AWSSession(session=boto3_session()) def _postprocess( tile: numpy.ndarray, mask: numpy.ndarray, rescale: str = None, color_formula: str = None, ) -> numpy.ndarray: """Post-process tile data.""" if rescale: rescale_arr = list(map(float, rescale.split(","))) rescale_arr = list(_chunks(rescale_arr, 2)) if len(rescale_arr) != tile.shape[0]: rescale_arr = ((rescale_arr[0]), ) * tile.shape[0]
def test_API_otherCompression(): """Test other compression.""" body = b"thisisafakeencodedjpeg" zlib_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS) deflate_compress = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS) zlibbody = zlib_compress.compress(body) + zlib_compress.flush() deflbody = deflate_compress.compress(body) + deflate_compress.flush() app = API(app_name="test") funct = Mock(__name__="Mock", return_value=("OK", "image/jpeg", body)) app._add_route( "/test_deflate/<user>.jpg", funct, methods=["GET"], cors=True, payload_compression_method="deflate", ) app._add_route( "/test_zlib/<user>.jpg", funct, methods=["GET"], cors=True, payload_compression_method="zlib", ) # Zlib event = { "path": "/test_zlib/remotepixel.jpg", "httpMethod": "GET", "headers": { "Accept-Encoding": "zlib, gzip, deflate" }, "queryStringParameters": {}, } resp = { "body": zlibbody, "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Encoding": "zlib", "Content-Type": "image/jpeg", }, "statusCode": 200, } res = app(event, {}) assert res == resp # Deflate event = { "path": "/test_deflate/remotepixel.jpg", "httpMethod": "GET", "headers": { "Accept-Encoding": "zlib, gzip, deflate" }, "queryStringParameters": {}, } resp = { "body": deflbody, "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Encoding": "deflate", "Content-Type": "image/jpeg", }, "statusCode": 200, } res = app(event, {}) assert res == resp
"""app: handle requests.""" from typing import Dict, Tuple, io import json from lambda_proxy.proxy import API APP = API(name="app") @APP.route("/", methods=["GET"], cors=True) def main() -> Tuple[str, str, str]: """Return JSON Object.""" return ("OK", "text/plain", "Yo") @APP.route("/<regex([0-9]{2}-[a-zA-Z]{5}):regex1>", methods=["GET"], cors=True) def _re_one(regex1: str) -> Tuple[str, str, str]: """Return JSON Object.""" return ("OK", "text/plain", input) @APP.route("/<regex([0-9]{1}-[a-zA-Z]{5}):regex2>", methods=["GET"], cors=True) def _re_two(regex2: str) -> Tuple[str, str, str]: """Return JSON Object.""" return ("OK", "text/plain", input) @APP.route("/add", methods=["GET", "POST"], cors=True) def post(body) -> Tuple[str, str, str]:
def test_API_routeURL(): """Should catch invalid route and parse valid args.""" app = API(app_name="test") funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route("/test/<user>", funct, methods=["GET"], cors=True) event = { "route": "/users/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } resp = { "body": '{"errorMessage": "Missing route parameter"}', "headers": { "Content-Type": "application/json" }, "statusCode": 400, } res = app(event, {}) assert res == resp event = { "path": "/users/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } resp = { "body": '{"errorMessage": "No view function for: /users/remotepixel"}', "headers": { "Content-Type": "application/json" }, "statusCode": 400, } res = app(event, {}) assert res == resp event = { "path": "/test/remotepixel", "httpMethod": "POST", "headers": {}, "queryStringParameters": {}, } resp = { "body": '{"errorMessage": "Unsupported method: POST"}', "headers": { "Content-Type": "application/json" }, "statusCode": 400, } res = app(event, {}) assert res == resp event = { "path": "/users/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } resp = { "body": '{"errorMessage": "No view function for: /users/remotepixel"}', "headers": { "Content-Type": "application/json" }, "statusCode": 400, } res = app(event, {}) assert res == resp event = { "path": "/test/users/remotepixel", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } resp = { "body": '{"errorMessage": "No view function for: /test/users/remotepixel"}', "headers": { "Content-Type": "application/json" }, "statusCode": 400, } res = app(event, {}) assert res == resp funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy")) app._add_route( "/test/<string:v>/<uuid:uuid>/<int:z>/<float:x>.<ext>", funct, methods=["GET"], cors=True, ) event = { "path": "/test/remotepixel/6b0d1f74-8f81-11e8-83fd-6a0003389b00/1/-1.0.jpeg", "httpMethod": "GET", "headers": {}, "queryStringParameters": {}, } resp = { "body": "heyyyy", "headers": { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET", "Access-Control-Allow-Origin": "*", "Content-Type": "text/plain", }, "statusCode": 200, } res = app(event, {}) assert res == resp funct.assert_called_with( v="remotepixel", uuid="6b0d1f74-8f81-11e8-83fd-6a0003389b00", z=1, x=-1.0, ext="jpeg", ) # Clear logger handlers for h in app.log.handlers: app.log.removeHandler(h)
from rio_tiler.utils import ( array_to_image, get_colormap, expression, linear_rescale, _chunks, ) from rio_color.operations import parse_operations from rio_color.utils import scale_dtype, to_math_type from lambda_proxy.proxy import API from lambda_tiler.viewer import viewer_template APP = API(name="lambda-tiler") def _postprocess( tile: numpy.ndarray, mask: numpy.ndarray, rescale: str = None, color_formula: str = None, ) -> Tuple[numpy.ndarray, numpy.ndarray]: """Post-process tile data.""" if rescale: rescale_arr = list(map(float, rescale.split(","))) rescale_arr = list(_chunks(rescale_arr, 2)) if len(rescale_arr) != tile.shape[0]: rescale_arr = ((rescale_arr[0]),) * tile.shape[0]
import json import os import urllib.request import numpy as np from rasterio import features from rio_tiler import main from rio_tiler.utils import (array_to_img, linear_rescale, get_colormap, expression, b64_encode_img) import stac_tools import s3_tools from lambda_proxy.proxy import API from distutils import util APP = API(app_name="ml-lambda-api") bucket_name = os.environ['stac_bucket_name'] default_algorithm = os.environ['default_algorithm'] @APP.route('/ml_start/', methods=['GET'], cors=True) def ml_start(): """Handle ml_start requests.""" query_args = APP.current_request.query_params query_args = query_args if isinstance(query_args, dict) else {} geometry = query_args['geometry'] task_id = query_args.get('task_id') algorithm = query_args.get('algorithm', 'default')