예제 #1
0
class Analytics(Cog):
    def __init__(self, bot: Bot):
        self.bot = bot
        self.metrics = {}
        self.app = Application()
        self.routes = RouteTableDef()

        self.metrics["queue_size"] = {
            "help": "Simp for maize",
            "type": "gauge",
            "value": 1.0
        }

        self.routes.get("/metrics")(self.get_metrics)

        self.app.add_routes(self.routes)
        self.bot.loop.create_task(self.start())

    async def start(self):
        await _run_app(self.app, port=8080)

    def format_response(self):
        response = ""
        for metric_name, metric_data in self.metrics.items():
            response += f"# HELP {metric_name} {metric_data['help']}\n"
            response += f"# TYPE {metric_name} {metric_data['type']}\n"
            response += f"{metric_name} {metric_data['value']}\n"
        return response

    async def get_metrics(self, request: Request):
        return Response(body=self.format_response())

    def update_metric(self, name, value, description):
        if self.metrics.get(name, None) is None:
            self.metrics[name] = {
                "type": "gauge",
                "description": description,
                "value": 0
            }
        self.metrics[name]["value"] = value
예제 #2
0
def routes(route: web.RouteTableDef):
    return [
        route.get('/', get_users),
        route.get('/{id}', get_one_user),
        route.post('/', create_user)
    ]
예제 #3
0
class IntegrationWebhookContext(IntegrationWebhookRoutes):
    def __init__(self, queue: 'IntegrationDeferralQueue',
                 client: 'AIOPartyClient'):
        self.route_table = RouteTableDef()
        self.client = client

        self.routes = []  # type: List[WebhookRouteStatus]

    def _with_resp_handling(self, status: 'InvocationStatus', fn):
        @wraps(fn)
        async def wrapped(request):
            return get_http_response(await fn(request))

        return wrapped

    def _notice_hook_route(self, url_path: str, method: str,
                           label: 'Optional[str]') -> 'WebhookRouteStatus':

        LOG.info('Registered hook (label: %s): %s %r', label, method, url_path)

        route_status = \
            WebhookRouteStatus(
                index=len(self.routes),
                url_path=url_path,
                method=method,
                label=label,
                command_count=0,
                use_count=0,
                error_count=0,
                error_message=None,
                error_time=None)

        self.routes.append(route_status)

        return route_status

    def _url_path(self, url_suffix: 'Optional[str]'):
        return '/integration/{integration_id}' + (url_suffix or '')

    def post(self,
             url_suffix: 'Optional[str]' = None,
             label: 'Optional[str]' = None,
             auth: 'Optional[AuthorizationLevel]' = AuthorizationLevel.PUBLIC):
        path = self._url_path(url_suffix)
        hook_status = self._notice_hook_route(path, 'post', label)

        def wrap_method(func):
            return set_handler_auth(
                self.route_table.post(path=path)(self._with_resp_handling(
                    hook_status,
                    as_handler_invocation(self.client, hook_status, func))),
                auth)

        return wrap_method

    def get(self,
            url_suffix: 'Optional[str]' = None,
            label: 'Optional[str]' = None,
            auth: 'Optional[AuthorizationLevel]' = AuthorizationLevel.PUBLIC):
        path = self._url_path(url_suffix)
        hook_status = self._notice_hook_route(path, 'get', label)

        def wrap_method(func):
            return set_handler_auth(
                self.route_table.get(path=path)(self._with_resp_handling(
                    hook_status,
                    as_handler_invocation(self.client, hook_status, func))),
                auth)

        return wrap_method

    def get_status(self) -> 'Sequence[WebhookRouteStatus]':
        return self.routes
예제 #4
0
from uuid import uuid4

from aiohttp.web import (RouteTableDef, Application, Response, json_response,
                         HTTPBadRequest, HTTPUnauthorized)

routes = RouteTableDef()


# first add ten more routes to load routing system
# ------------------------------------------------
async def req_ok(request):
    return Response(text='ok')


for n in range(5):
    routes.get(f"/route-{n}")(req_ok)
    routes.get(f"/route-dyn-{n}/{{part}}")(req_ok)


# then prepare endpoints for the benchmark
# ----------------------------------------
@routes.get('/html')
async def html(request):
    """Return HTML content and a custom header."""
    content = "<b>HTML OK</b>"
    headers = {'x-time': f"{time.time()}"}
    return Response(text=content, content_type="text/html", headers=headers)


@routes.post('/upload')
async def upload(request):