Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"scope": scope,
"receive": receive,
"send": send,
"exc": None,
"app": app,
"path_params": route_scope["path_params"],
"route": route,
"request": http.Request(scope, receive),
}
injected_func = await app.injector.inject(endpoint, state)
if asyncio.iscoroutinefunction(endpoint):
response = await injected_func()
else:
response = await run_in_threadpool(injected_func)
# Wrap response data with a proper response class
if isinstance(response, (dict, list)):
response = APIResponse(content=response, schema=get_output_schema(endpoint))
elif isinstance(response, str):
response = APIResponse(content=response)
elif response is None:
response = APIResponse(content="")
await response(scope, receive, send)
) from e
solved_result = await solve_dependencies(
request=request,
dependant=dependant,
body=body,
dependency_overrides_provider=dependency_overrides_provider,
)
values, errors, background_tasks, sub_response, _ = solved_result
if errors:
raise RequestValidationError(errors)
else:
assert dependant.call is not None, "dependant.call must be a function"
if is_coroutine:
raw_response = await dependant.call(**values)
else:
raw_response = await run_in_threadpool(dependant.call, **values)
if isinstance(raw_response, Response):
if raw_response.background is None:
raw_response.background = background_tasks
return raw_response
response_data = serialize_response(
field=response_field,
response=raw_response,
include=response_model_include,
exclude=response_model_exclude,
by_alias=response_model_by_alias,
exclude_unset=response_model_exclude_unset,
)
response = response_class(
content=response_data,
status_code=status_code,
background=background_tasks,
async def read_tile_mvt(
self,
z: int,
x: int,
y: int,
tilesize: int = 128,
resampling_method: str = "bilinear",
feature_type: str = "point",
) -> BinaryIO:
"""Read raster tile data and encode to MVT."""
from rio_tiler_mvt import mvt
mvt_encoder = partial(run_in_threadpool, mvt.encoder)
tile, mask = await self.read_tile(
z, x, y, tilesize=tilesize, resampling_method=resampling_method
)
return await mvt_encoder(
tile, mask, self.band_descriptions, feature_type=feature_type
)
async def work(req, res, exp):
await run_in_threadpool(sort_random_numbers, 10 ** int(exp))
res.text = "Done"
async def read(self, size: int = None) -> typing.Union[bytes, str]:
return await run_in_threadpool(self.file.read, size)
async def write(self, data: typing.Union[bytes, str]) -> None:
await run_in_threadpool(self.file.write, data)
async def __call__(self, receive: Receive, send: Send) -> None:
body = b""
more_body = True
while more_body:
message = await receive()
body += message.get("body", b"")
more_body = message.get("more_body", False)
environ = build_environ(self.scope, body)
sender = None
try:
sender = self.loop.create_task(self.sender(send))
await run_in_threadpool(self.wsgi, environ, self.start_response)
self.send_queue.append(None)
self.send_event.set()
await asyncio.wait_for(sender, None) # type: ignore
if self.exc_info is not None:
raise self.exc_info[0].with_traceback(
self.exc_info[1], self.exc_info[2]
)
finally:
if sender and not sender.done():
sender.cancel() # pragma: no cover
async def make(self, secret: str) -> str:
return await run_in_threadpool(self.make_sync, secret)
import rasterio
from rasterio.warp import transform_bounds
from rio_tiler import reader
from rio_tiler import constants
from rio_tiler.mercator import get_zooms
from rio_tiler.utils import linear_rescale, _chunks
from rio_color.operations import parse_operations
from rio_color.utils import scale_dtype, to_math_type
from starlette.concurrency import run_in_threadpool
multi_meta = partial(run_in_threadpool, reader.multi_metadata)
multi_tile = partial(run_in_threadpool, reader.multi_tile)
def _get_info(src_path: str) -> Any:
with rasterio.open(src_path) as src_dst:
bounds = transform_bounds(
src_dst.crs, constants.WGS84_CRS, *src_dst.bounds, densify_pts=21
)
minzoom, maxzoom = get_zooms(src_dst)
center = ((bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2, minzoom)
def _get_name(ix):
name = src_dst.descriptions[ix - 1]
if not name:
name = f"band{ix}"
return name
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.gzip import GZipMiddleware
from fastapi import Depends, FastAPI, Query
import uvicorn
try:
import rio_tiler_mvt # noqa
has_mvt = True
except ModuleNotFoundError:
has_mvt = False
_postprocess_tile = partial(run_in_threadpool, postprocess_tile)
_render = partial(run_in_threadpool, render)
class viz(object):
"""Creates a very minimal slippy map tile server using fastAPI + Uvicorn."""
def __init__(
self,
raster,
token: str = None,
port: int = 8080,
host: str = "127.0.0.1",
style: str = "satellite",
):
"""Initialize app."""
self.app = FastAPI(
title="titiler",