コード例 #1
0
 def get_httptrace_test_url(request: Request) -> Response:
     return Response(
         headers={"resp-data": str(request.headers.get("User-Data"))},
         content="my content")
コード例 #2
0
ファイル: views.py プロジェクト: aodarc/hack9
async def listing(calling: str, request: Request):
    """Listing of calls made by the given telephone number.
    :param calling: *required. Calling number. Example 38121123456
    :param request:
        from: *required. Start of the listing period. Example: 2019-04-03T12:34:56.00Z
        to: *required. End of the listing period. Example: 2019-04-03T12:34:56.00Z
    :return:
        - 200  Listing generated, even if empty.
            - Headers
                - Content-type: application/json
            - Body
                {
                    "calling": "381211234567",
                    "calls": [
                    {
                        "calling": "381211234567",
                        "called": "38164111222333",
                        "start": "2019-05-23T21:03:33.30Z",
                        "duration": "350",
                        "rounded": "355",
                        "price": "0.4",
                        "cost": "2.367"
                    }
                  ]
                }
    """
    from_str = request.query_params.get('from')
    to_str = request.query_params.get('to')

    response_body = {
        'calling': calling,
        'calls': []
    }
    try:
        datetime_from = dateutil.parser.parse(from_str).replace(tzinfo=None)
        datetime_to = dateutil.parser.parse(to_str).replace(tzinfo=None)

        async with app.postgres.acquire() as con:
            records = await con.fetch(
                LISTING,
                int(calling),
                datetime_from,
                datetime_to
            )

        for record in records:
            record = dict(record)
            record['start'] = record['start'].isoformat() + 'Z'
            response_body['calls'].append(record)

        json_body = json.dumps(response_body)
        response = Response(
            content=json_body,
            status_code=200,
            headers={
                "Content-type": "application/json"
            }
        )
    except Exception:
        json_body = json.dumps(response_body)
        response = Response(
            content=json_body,
            status_code=200,
            headers={
                "Content-type": "application/json"
            }
        )
    return response
コード例 #3
0
 async def asgi(receive, send):
     response = Response("hello, world", media_type="text/plain")
     await response(receive, send)
コード例 #4
0
 async def app(scope, receive, send):
     if scope["path"] == "/":
         response = Response("hello, world", media_type="text/plain")
     else:
         response = RedirectResponse("/")
     await response(scope, receive, send)
コード例 #5
0
ファイル: views.py プロジェクト: aodarc/hack9
from decimal import Decimal

import dateutil
import pandas as pd
from pydantic.error_wrappers import ValidationError as pydanticValidationError
from starlette.requests import Request
from starlette.responses import Response

from api.models import CallData, CallDataInResponse, InvoiceData
from api.queries import ADD_CALLS_RECORD, GET_INVOICE_RECORD_BY_ID, LISTING, GET_FINANCIAL_REPORTS_SUM, \
    GET_FINANCIAL_REPORTS_REMAINING
from api.utils import invoice_generation
from api.utils.cost_calculation_py import calculate_cost
from . import app

ERROR_400 = Response(content='{"message": "Incorrect input"}', status_code=400,
                     headers={"Content-type": "application/json"})
ERROR_404 = Response(content='{"message": "No in DB"}', status_code=404,
                     headers={"Content-type": "application/json"})
MAX_PREFIX_SIZE = 9


def get_call_stats_from_csv(dataframe, time, calling):
    rows = pd.DataFrame()
    calling = str(calling)
    for i in range(MAX_PREFIX_SIZE, 0, -1):
        rows = dataframe.loc[dataframe.prefix == int(calling[:i])]
        if not rows.empty:
            rows = rows.loc[(rows.startDate <= time)].sort_values('startDate').tail(1)
            break

    if rows.empty:
コード例 #6
0
ファイル: file.py プロジェクト: aarnphm/BentoML
 async def to_http_response(self, obj: t.Union[FileLike,
                                               bytes]) -> Response:
     if isinstance(obj, bytes):
         obj = FileLike(bytes_=obj)
     return Response(t.cast(BytesIO, obj.stream).getvalue(),
                     media_type=self._mime_type)
コード例 #7
0
def test_head_method():
    app = Response("hello, world", media_type="text/plain")
    client = TestClient(app)
    response = client.head("/")
    assert response.text == ""
コード例 #8
0
def expose_metrics():
    return Response(generate_latest(), headers=_HEADERS)
コード例 #9
0
def expose_metrics_multiprocess():
    registry = CollectorRegistry()
    multiprocess.MultiProcessCollector(registry)
    return Response(generate_latest(registry), headers=_HEADERS)
コード例 #10
0
ファイル: app.py プロジェクト: waseem-aidash/rio-viz
        async def tile(
            z: int,
            x: int,
            y: int,
            scale: int = Query(2, gt=0, lt=4),
            format: Optional[TileType] = None,
            layer_params=Depends(self.layer_dependency),
            image_params: ImageParams = Depends(),
            feature_type: str = Query(
                None,
                title="Feature type (Only for Vector)",
                regex="^(point)|(polygon)$",
            ),
        ):
            """Handle /tiles requests."""
            timings = []
            headers: Dict[str, str] = {}

            tilesize = scale * 256

            if format and format in [TileType.pbf, TileType.mvt]:
                tilesize = (tilesize if feature_type
                            and feature_type == "feature" else 128)

            with Timer() as t:
                async with self.reader(
                        self.src_path) as src_dst:  # type: ignore

                    # Adapt options for each reader type
                    kwargs = self._get_options(src_dst, layer_params.kwargs)
                    if self.nodata is not None:
                        kwargs["nodata"] = self.nodata

                    tile_data = await src_dst.tile(
                        x,
                        y,
                        z,
                        tilesize=tilesize,
                        resampling_method=image_params.resampling_method.name,
                        **kwargs,
                    )

                    bandnames = kwargs.get("bands", kwargs.get(
                        "assets", None)) or [
                            f"{ix + 1}" for ix in range(tile_data.count)
                        ]

                    dst_colormap = getattr(src_dst, "colormap", None)
            timings.append(("dataread", round(t.elapsed * 1000, 2)))

            if format and format in [TileType.pbf, TileType.mvt]:
                if not pixels_encoder:
                    raise HTTPException(
                        status_code=500,
                        detail=
                        "rio-tiler-mvt not found, please do pip install rio-viz['mvt']",
                    )

                if not feature_type:
                    raise HTTPException(
                        status_code=500,
                        detail="missing feature_type for vector tile.",
                    )
                _mvt_encoder = partial(run_in_threadpool, pixels_encoder)
                with Timer() as t:
                    content = await _mvt_encoder(
                        tile_data.data,
                        tile_data.mask,
                        bandnames,
                        feature_type=feature_type,
                    )  # type: ignore
                timings.append(("format", round(t.elapsed * 1000, 2)))

            else:
                if not format:
                    format = TileType.jpeg if tile_data.mask.all(
                    ) else TileType.png

                with Timer() as t:
                    image = tile_data.post_process(
                        in_range=image_params.rescale_range,
                        color_formula=image_params.color_formula,
                    )
                timings.append(("postprocess", round(t.elapsed * 1000, 2)))

                with Timer() as t:
                    content = image.render(
                        img_format=format.driver,
                        colormap=image_params.colormap or dst_colormap,
                        **format.profile,
                    )
                timings.append(("format", round(t.from_start * 1000, 2)))

            headers["Server-Timing"] = ", ".join(
                [f"{name};dur={time}" for (name, time) in timings])
            return Response(content,
                            media_type=format.mimetype,
                            headers=headers)
コード例 #11
0
def get_processtype(entity_id, request: Request):
    db = request.app.db

    return Response(content=db['processtypes'].get(entity_id))
コード例 #12
0
ファイル: test_responses.py プロジェクト: vpistis/starlette
 def app(scope):
     headers = {}
     return Response(content="hi", headers=headers, media_type="text/html")
コード例 #13
0
ファイル: test_responses.py プロジェクト: vpistis/starlette
 def app(scope):
     return Response(status_code=204)
コード例 #14
0
def get_lab(entity_id, request: Request):
    db = request.app.db

    return Response(content=db['labs'].get(entity_id))
コード例 #15
0
ファイル: roles.py プロジェクト: Clinical-Genomics/limsmock
def get_role(entity_id, request: Request):
    db = request.app.db

    return Response(content=db['roles'].get(entity_id))
コード例 #16
0
async def solve_dependencies(
    *,
    request: Union[Request, WebSocket],
    dependant: Dependant,
    body: Optional[Union[Dict[str, Any], FormData]] = None,
    background_tasks: BackgroundTasks = None,
    response: Response = None,
    dependency_overrides_provider: Any = None,
    dependency_cache: Dict[Tuple[Callable, Tuple[str]], Any] = None,
) -> Tuple[Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks],
           Response, Dict[Tuple[Callable, Tuple[str]], Any], ]:
    values: Dict[str, Any] = {}
    errors: List[ErrorWrapper] = []
    response = response or Response(  # type: ignore
        content=None,
        status_code=None,
        headers=None,
        media_type=None,
        background=None)
    dependency_cache = dependency_cache or {}
    sub_dependant: Dependant
    for sub_dependant in dependant.dependencies:
        sub_dependant.call = cast(Callable, sub_dependant.call)
        sub_dependant.cache_key = cast(Tuple[Callable, Tuple[str]],
                                       sub_dependant.cache_key)
        call = sub_dependant.call
        use_sub_dependant = sub_dependant
        if (dependency_overrides_provider
                and dependency_overrides_provider.dependency_overrides):
            original_call = sub_dependant.call
            call = getattr(dependency_overrides_provider,
                           "dependency_overrides",
                           {}).get(original_call, original_call)
            use_path: str = sub_dependant.path  # type: ignore
            use_sub_dependant = get_dependant(
                path=use_path,
                call=call,
                name=sub_dependant.name,
                security_scopes=sub_dependant.security_scopes,
            )

        solved_result = await solve_dependencies(
            request=request,
            dependant=use_sub_dependant,
            body=body,
            background_tasks=background_tasks,
            response=response,
            dependency_overrides_provider=dependency_overrides_provider,
            dependency_cache=dependency_cache,
        )
        sub_values, sub_errors, background_tasks, sub_response, sub_dependency_cache = (
            solved_result)
        sub_response = cast(Response, sub_response)
        response.headers.raw.extend(sub_response.headers.raw)
        if sub_response.status_code:
            response.status_code = sub_response.status_code
        dependency_cache.update(sub_dependency_cache)
        if sub_errors:
            errors.extend(sub_errors)
            continue
        if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache:
            solved = dependency_cache[sub_dependant.cache_key]
        elif is_coroutine_callable(call):
            solved = await call(**sub_values)
        else:
            solved = await run_in_threadpool(call, **sub_values)
        if sub_dependant.name is not None:
            values[sub_dependant.name] = solved
        if sub_dependant.cache_key not in dependency_cache:
            dependency_cache[sub_dependant.cache_key] = solved
    path_values, path_errors = request_params_to_args(dependant.path_params,
                                                      request.path_params)
    query_values, query_errors = request_params_to_args(
        dependant.query_params, request.query_params)
    header_values, header_errors = request_params_to_args(
        dependant.header_params, request.headers)
    cookie_values, cookie_errors = request_params_to_args(
        dependant.cookie_params, request.cookies)
    values.update(path_values)
    values.update(query_values)
    values.update(header_values)
    values.update(cookie_values)
    errors += path_errors + query_errors + header_errors + cookie_errors
    if dependant.body_params:
        body_values, body_errors = await request_body_to_args(  # type: ignore # body_params checked above
            required_params=dependant.body_params,
            received_body=body)
        values.update(body_values)
        errors.extend(body_errors)
    if dependant.request_param_name and isinstance(request, Request):
        values[dependant.request_param_name] = request
    elif dependant.websocket_param_name and isinstance(request, WebSocket):
        values[dependant.websocket_param_name] = request
    if dependant.background_tasks_param_name:
        if background_tasks is None:
            background_tasks = BackgroundTasks()
        values[dependant.background_tasks_param_name] = background_tasks
    if dependant.response_param_name:
        values[dependant.response_param_name] = response
    if dependant.security_scopes_param_name:
        values[dependant.security_scopes_param_name] = SecurityScopes(
            scopes=dependant.security_scopes)
    return values, errors, background_tasks, response, dependency_cache
コード例 #17
0
ファイル: roles.py プロジェクト: Clinical-Genomics/limsmock
async def put_role(entity_id, request: Request):
    body = await request.body()

    request.app.db['roles'][entity_id] = body
    return Response(content=body)
コード例 #18
0
def delete_item(
    item_uuid: UUID, current_user: models.User = Depends(deps.get_current_user)
) -> Response:
    services.item.delete_item(current_user, item_uuid)
    return Response(status_code=HTTP_204_NO_CONTENT)
コード例 #19
0
 async def app(scope, receive, send):
     headers = {"x-header-1": "123", "x-header-2": "456"}
     response = Response("hello, world", media_type="text/plain", headers=headers)
     response.headers["x-header-2"] = "789"
     await response(scope, receive, send)
コード例 #20
0
ファイル: exceptions.py プロジェクト: caowenbin08/starlette
 def http_exception(self, request: Request, exc: HTTPException) -> Response:
     if exc.status_code in {204, 304}:
         return Response(b"", status_code=exc.status_code)
     return PlainTextResponse(exc.detail, status_code=exc.status_code)
コード例 #21
0
 async def app(scope, receive, send):
     response = Response(b"xxxxx", media_type="image/png")
     await response(scope, receive, send)
コード例 #22
0
ファイル: router.py プロジェクト: muraig/fastapi_full_stack
async def message(body: Message):
    res = await proceed_custom(body)
    return Response(status_code=res.status_code)
コード例 #23
0
ファイル: employee.py プロジェクト: DanielSantaR/final-web
async def remove(*, id: str):
    employee_remove = await employee_service.remove_employee(employee_id=id)
    status_code = 204 if employee_remove == 1 else 404
    return Response(status_code=status_code)
コード例 #24
0
 async def preflight_handler(request: Request,
                             rest_of_path: str) -> Response:
     response = Response()
     response.headers['Access-Control-Allow-Headers'] = '*'
     response.headers['Access-Control-Max-Age'] = '600'
     return response
コード例 #25
0
ファイル: views.py プロジェクト: aodarc/hack9
async def switch_call(data: dict):
    """Register details of a call that was made and calcualte the cost of the call.
        - Request data:
            {
                "calling": "381211234567",
                "called": "38164111222333",
                "start": "2019-05-23T21:03:33.30Z",
                "duration": "450"
            }

    :param data:
    :return:
        - 200  Call accepted
            - Headers
                - Content-type: application/json
            - Body
                {
                    "calling": "381211234567",
                    "called": "38164111222333",
                    "start": "2019-05-23T21:03:33.30Z",
                    "duration": "350",
                    "rounded": "355",
                    "price": "0.4",
                    "cost": "2.367"
                }
        - 400  Incorrect input
            - Headers
                - Content-type: application/json
            - Body
                {
                    "message": "Incorrect input"
                }
        - 400  Incorrect input
            - Headers
                - Content-type: application/json
            - Body
                {
                    "message": "Error occurred"
                }
    """
    try:
        call_object = CallData(**data)

        call_stats = get_call_stats_from_csv(
            calling=call_object.called,
            time=call_object.start.isoformat() + 'Z',
            dataframe=app.df
        )
        if not call_stats:
            return ERROR_400

        cost = calculate_cost(
            initial=int(call_stats["initial"]),
            duration=int(call_object.duration),
            increment=int(call_stats["increment"]),
            rate=float(call_stats["price"])
        )
        rounded = math.ceil((int(call_stats["initial"]) + int(call_object.duration)) / \
        int(call_stats["increment"])) * int(call_stats["increment"])
        call_object.price = call_stats["price"]
        call_object.cost = cost
        call_object.rounded = rounded

        async with app.postgres.acquire() as con:
            await con.execute(
                ADD_CALLS_RECORD,
                int(call_object.calling),
                int(call_object.called),
                call_object.start.replace(tzinfo=None),
                call_object.duration,
                call_object.rounded,
                float(call_object.price),
                float(call_object.cost)
            )
            # call_object.id = str(row.inserted_id)
            # response = {key: str(v) for key, v in call_object.dict().items()}
            response = call_object.dict()
    except pydanticValidationError:
        response = Response(
            content='{"message": "Incorrect input"}',
            status_code=400,
            headers={
                "Content-type": "application/json"
            }
        )
    except Exception as e:
        raise e
        # response = Response(
        #     content='{"message": "Error occurred"}',
        #     status_code=400,
        #     headers={
        #         "Content-type": "application/json"
        #     }
        # )
    return response
コード例 #26
0
def get_segmentation_map(file: bytes = File(...)):
    '''Get segmentation maps from image file'''
    segmented_image = get_segments(model, file)
    bytes_io = io.BytesIO()
    segmented_image.save(bytes_io, format='PNG')
    return Response(bytes_io.getvalue(), media_type="image/png")
コード例 #27
0
 def app(scope):
     return Response(b"", status_code=123)
コード例 #28
0
async def home():
    return Response('/')
コード例 #29
0
 async def asgi(receive, send):
     response = Response(b"xxxxx", media_type="image/png")
     await response(receive, send)
コード例 #30
0
def metrics(request: Request) -> Response:
    return Response(generate_latest(REGISTRY), media_type=CONTENT_TYPE_LATEST)