Пример #1
0
def simple_client(hello_fake):
    @path('/test/', MethodType.GET)
    def operation() -> StrResponse:
        return StrResponse(body=hello_fake)

    app = appdaora([operation])
    return TestClient(app)
Пример #2
0
def start(spec: Specification, host: str, port: int,
          html_params: Dict[str, str]) -> None:
    controllers = build_yaml_spec_controllers(spec) + [
        build_json_spec_controller(spec)
    ]
    controllers.extend(build_spec_docs_controllers(spec, html_params))
    app = appdaora(controllers)
    uvicorn.run(app, host=host, port=port)
Пример #3
0
async def test_should_get_response_with_one_scalar_path_parameter():
    @path('/test/{param}', MethodType.GET)
    def operation(param: int) -> StrResponse:
        return StrResponse(body=f'{param}: {type(param).__name__}')

    client = TestClient(appdaora([operation]))

    response = await client.get('/test/01')

    assert response.status_code == HTTPStatus.OK.value
    assert response.content == b'1: int'
Пример #4
0
async def test_should_get_response_with_one_scalar_path_parameter_and_two_query_parameter():
    @path('/test/{param}', MethodType.GET)
    def operation(param: int, param2: float, param3: str) -> StrResponse:
        return StrResponse(
            body=(
                f'{param}: {type(param).__name__}, '
                f'{param2}: {type(param2).__name__}, '
                f'{param3}: {type(param3).__name__}'
            )
        )

    client = TestClient(appdaora([operation]))

    response = await client.get('/test/01/?param2=00000.1&param3=test')

    assert response.status_code == HTTPStatus.OK.value
    assert response.content == b'1: int, 0.1: float, test: str'
Пример #5
0
async def test_should_get_response_with_scalar_parameters_with_one_path_and_one_query_and_one_header():
    @path('/test/{param}', MethodType.GET)
    def operation(
        param: int,
        param2: float,
        param3: header_param(schema=float, name='x-param3'),
    ) -> StrResponse:
        return StrResponse(
            body=(
                f'{param}: {type(param).__name__}, '
                f'{param2}: {type(param2).__name__}, '
                f'{param3}: {type(param3).__name__}'
            )
        )

    client = TestClient(appdaora([operation]))

    response = await client.get(
        '/test/01/?param2=00000.1', headers={'x-param3': '-000.1'}
    )

    assert response.status_code == HTTPStatus.OK.value
    assert response.content == b'1: int, 0.1: float, -0.1: float'
Пример #6
0
from dataclasses import dataclass

from apidaora import JSONResponse, MethodType, appdaora, path


@dataclass
class Response(JSONResponse):
    body: str


@path('/hello', MethodType.GET)
def controller(name: str) -> Response:
    message = f'Hello {name}!'
    return Response(body=message)


app = appdaora(operations=[controller])
Пример #7
0
import time

from apidaora import appdaora, route


@route.background('/hello-single', lock=True)
def hello_task(name: str) -> str:
    time.sleep(1)
    return f'Hello {name}!'


app = appdaora(hello_task)
Пример #8
0
def make_app() -> ASGIApp:
    executor = ThreadPoolExecutor(config.workers)
    chunli = Caller(data_source_target=config.redis_target)
    executor.submit(wait_for_ditributed_calls_in_background, chunli, config)

    @route.background('/run', tasks_repository_uri=config.redis_target)
    async def run(
        duration: int,
        rps_per_node: int,
        body: GzipBody,
        rampup_time: Optional[int] = None,
    ) -> Results:
        calls = (line.strip('\n') for line in body.open())
        chunli_run = Caller(data_source_target=config.redis_target)

        await chunli_run.set_calls(calls)
        await chunli_run.start_distributed_calls(
            CallerConfig(
                duration=duration,
                rps_per_node=rps_per_node,
                rampup_time=rampup_time,
            ))

        try:
            results = await chunli_run.get_results(duration)

            return results

        except Exception as error:
            logger.exception(error)
            return Results(  # type: ignore
                error=Error(name=type(error).__name__, args=error.args))

    @route.background('/script', tasks_repository_uri=config.redis_target)
    async def script(
        duration: int,
        rps_per_node: int,
        body: str,
        rampup_time: Optional[int] = None,
    ) -> Results:
        chunli_run = Caller(data_source_target=config.redis_target)

        await chunli_run.set_script(body)
        await chunli_run.start_distributed_calls(
            CallerConfig(
                duration=duration,
                rps_per_node=rps_per_node,
                rampup_time=rampup_time,
            ))

        try:
            results = await chunli_run.get_results(duration)

            return results

        except Exception as error:
            logger.exception(error)
            return Results(  # type: ignore
                error=Error(name=type(error).__name__, args=error.args))

    @route.get('/status')
    async def status() -> Status:
        return Status(chunli=random.choice(_CHUN_LI_ATTACKS))

    return appdaora([run, status, script])
Пример #9
0
)
async def pre_execution_middleware_controller(body: PreExecutionBody) -> str:
    return hello(body.name)


class PostExecutionHeader(Header, type=int, http_name='x-name-len'):
    ...


@route.get(
    '/hello-post-execution',
    middlewares=Middlewares(post_execution=[post_execution_middleware]),
)
async def post_execution_middleware_controller(name: str) -> Response:
    return text(body=hello(name))


def hello(name: str) -> str:
    return f'Hello {name}!'


app = appdaora(
    [
        post_routing_middleware_controller,
        pre_execution_middleware_controller,
        post_execution_middleware_controller,
    ],
    middlewares=Middlewares(
        post_execution=[CorsMiddleware(servers_all='my-server.domain')]),
)
Пример #10
0
class ReqBody(TypedDict):
    last_name: str


@jsondaora
class HelloOutput(TypedDict):
    hello_message: str
    about_you: You


@route.put('/hello/{name}')
async def hello_controller(
    name: str, location: String, age: Age, body: ReqBody
) -> HelloOutput:
    you = You(
        name=name,
        location=location.value,
        age=age.value.value,
        last_name=body['last_name'],
    )
    return HelloOutput(
        hello_message=await hello_message(name, location.value), about_you=you
    )


async def hello_message(name: str, location: str) -> str:
    return f'Hello {name}! Welcome to {location}!'


app = appdaora(hello_controller)
Пример #11
0
from typing import TypedDict

from apidaora import appdaora, route
from jsondaora import jsondaora


@route.get('/hello')
def hello() -> str:
    return 'Hello World!'


@jsondaora
class Body(TypedDict):
    name: str


@route.post('/hello-body')
def hello_body(body: Body) -> str:
    return f"Hello {body['name']}!"


app = appdaora([hello, hello_body])
Пример #12
0
from apidaora import appdaora, route


@route.get('/app-options')
async def app_options() -> str:
    return 'Options'


@route.get('/route-options', options=True)
async def route_options() -> str:
    return 'Options'


app = appdaora([app_options, route_options], options=True)
Пример #13
0
@route.get('/updates')
async def database_updates(queries: Optional[str] = None):
    worlds = []
    updates = set()

    async with connection_pool.acquire() as connection:
        statement = await connection.prepare(READ_ROW_SQL_TO_UPDATE)

        for _ in range(get_num_queries(queries)):
            record = await statement.fetchrow(randint(1, 10000))
            world = DatabaseObject(id=record['id'],
                                   randomNumber=record['randomnumber'])
            world['randomNumber'] = randint(1, 10000)
            worlds.append(world)
            updates.add((world['id'], world['randomNumber']))

        await connection.executemany(WRITE_ROW_SQL, updates)

    return worlds


@route.get('/plaintext')
async def plaintext():
    return text('Hello, world!')


app = appdaora([
    json_serialization, single_database_query, multiple_database_queries,
    fortunes, database_updates, plaintext
])
Пример #14
0
class YouWereNotFoundError(DBError):
    name = 'you-were-not-found'


# Application layer, here are the http related definitions

# See: https://dutrdda.github.io/apidaora/tutorial/headers/
class ReqID(Header, type=str, http_name='http_req_id'):
    ...


@route.post('/you/')
async def add_you_controller(req_id: ReqID, body: You) -> Response:
    try:
        add_you(body)
    except YouAlreadyBeenAddedError as error:
        raise BadRequestError(name=error.name, info=error.info) from error

    return json(body, HTTPStatus.CREATED, headers=(req_id,))


@route.get('/you/{name}')
async def get_you_controller(name: str, req_id: ReqID) -> Response:
    try:
        return json(get_you(name), headers=(req_id,))
    except YouWereNotFoundError as error:
        raise BadRequestError(name=error.name, info=error.info) from error


app = appdaora([add_you_controller, get_you_controller])
Пример #15
0
from typing import List

from apidaora import LockRequestMiddleware, Middlewares, appdaora, route

prevent_request_middleware = LockRequestMiddleware()


@route.post(
    '/lock-request',
    middlewares=Middlewares(
        post_routing=[prevent_request_middleware.lock],
        pre_execution=[prevent_request_middleware.unlock_pre_execution],
    ),
)
async def lock_controller(body: List[int]) -> int:
    return len(body)


@route.post(
    '/lock-request-post',
    middlewares=Middlewares(
        post_routing=[prevent_request_middleware.lock],
        post_execution=[prevent_request_middleware.unlock_post_execution],
    ),
)
async def lock_post_controller(body: List[int]) -> int:
    return len(body)


app = appdaora([lock_controller, lock_post_controller])
from apidaora import (
    BackgroundTaskMiddleware,
    Middlewares,
    Response,
    appdaora,
    route,
    text,
)


class HelloCounter:
    counter = 1

    @classmethod
    async def count(cls) -> None:
        cls.counter += 1


@route.get('/background-tasks')
async def background_tasks_controller(name: str) -> Response:
    return text(
        f'Hello {name}!\n{name} are the #{HelloCounter.counter}!',
        background_tasks=HelloCounter.count,
    )


app = appdaora(
    background_tasks_controller,
    middlewares=Middlewares(post_execution=BackgroundTaskMiddleware()),
)
Пример #17
0
from apidaora import Middlewares, Request, Response, appdaora, route, text


def request_extra_args(request: Request) -> None:
    request.ctx['extra'] = 'You'


def response_extra_args(request: Request, response: Response) -> None:
    if request.ctx and response.ctx:
        response.body = response.body.replace(
            'You', f"{request.ctx['extra']} and {response.ctx['name']}"
        )


@route.get(
    '/middlewares-ctx',
    middlewares=Middlewares(
        pre_execution=request_extra_args, post_execution=response_extra_args,
    ),
)
async def extra_args_controller(name: str, **kwargs: Any) -> Response:
    return text(hello(kwargs['extra']), name=name)


def hello(name: str) -> str:
    return f'Hello {name}!'


app = appdaora(extra_args_controller)
Пример #18
0
from apidaora import GZipFactory, appdaora, route


class GzipBody(GZipFactory):
    mode = 'rt'


@route.post('/hello')
def gzip_hello(body: GzipBody) -> str:
    with body.open() as file:
        return file.read()


app = appdaora(gzip_hello)