Example #1
0
async def set_routes(router: UrlDispatcher, handler: RouteHandler) -> None:
    """
    Attach all routes (urls) to handlers.
    """
    router.add_get('/urlinfo/1/{host_and_port}/{path_and_qs}', handler.urlinfo, name='check')
    router.add_get('/{tail:.*}', handler.catchall)
    return
Example #2
0
    def hook_up(self, router: UrlDispatcher):
        """
        Dynamically hooks the right webhook paths
        """

        router.add_get(self.webhook_path, self.check_hook)
        router.add_post(self.webhook_path, self.receive_events)
Example #3
0
 def test_001_register(self, add_route):
     router = UrlDispatcher()
     router.post_init(Mock())
     self.resource_cls.register(Mock(), router)
     # GET /v1/test
     # DELETE /v1/test
     # GET /v2/test
     # DELETE /v2/test
     self.assertEqual(add_route.call_count, 4)
Example #4
0
 def register(self, router: UrlDispatcher):
     router.add_route(
         '*',
         '/{notes}'.format(notes=self.notes),
         self.collection_endpoint.dispatch
     )
     router.add_route(
         '*',
         '/{notes}/{{instance_id}}'.format(notes=self.articles),
         self.instance_endpoint.dispatch
     )
Example #5
0
 def change_routes(self, routes):
     router = UrlDispatcher()
     try:
         for route in routes:
             router.add_route(route.method,
                              route.path,
                              route.handler,
                              name=route.id)
     except Exception as exc:
         raise InvalidRouteError("Invalid route") from exc
     else:
         self._router = router
         if self._frozen:
             self._router.freeze()
def test_register_route():
    @asyncio.coroutine
    def handler(request):
        return Response()

    route = PlainRoute('GET', handler, 'test', '/handler/to/path')
    router = UrlDispatcher()
    router.register_route(route)

    req = make_mocked_request('GET', '/handler/to/path')
    info = yield from router.resolve(req)
    assert info is not None
    assert 0 == len(info)
    assert route is info.route
    assert handler is info.handler
    assert info.route.name == 'test'
def test_register_route():
    @asyncio.coroutine
    def handler(request):
        return Response()

    route = PlainRoute('GET', handler, 'test', '/handler/to/path')
    router = UrlDispatcher()
    router.register_route(route)

    req = make_mocked_request('GET', '/handler/to/path')
    info = yield from router.resolve(req)
    assert info is not None
    assert 0 == len(info)
    assert route is info.route
    assert handler is info.handler
    assert info.route.name == 'test'
Example #8
0
    def _make_dispatcher(self) -> UrlDispatcher:
        """Creates a aiohttp :see:UrlDispatcher based on
        the configured list of urls.

        Returns:
            A aiohttp :see:UrlDispatcher containing
            the configured urls.
        """

        dispatcher = UrlDispatcher()
        dispatcher.post_init(self)

        for url in self._urls:
            resource = dispatcher.add_resource(url.url, name=url.name)

            resource.add_route('GET', url.view)

        return dispatcher
Example #9
0
    def register_routes(self,
                        router: UrlDispatcher,
                        version_prefix: Optional[str] = None):
        """

        :param router:
        :param version_prefix:
        :return:
        """
        for route in self.produce_routes(version_prefix):
            try:
                router.add_route('*', route, self.dispatch)
                if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
                    logging.info('{0} is connected {1}'.format(
                        self.__class__, route))
            except RuntimeError as e:
                raise RuntimeError(
                    'Seems URL {0}, described in {1}, is already connected to another endpoint'
                    .format(route, self.__class__))
Example #10
0
 def register(self, router: UrlDispatcher):
     router.add_route('*', '/employees'.format(employees=self.employees),
                      self.employee_endpoint.dispatch)
     router.add_route('*', '/cars'.format(cars=self.cars),
                      self.car_endpoint.dispatch)
     router.add_route('*', '/parts'.format(parts=self.parts),
                      self.part_endpoint.dispatch)
Example #11
0
def _format_status(session: 'CheckCalibrationSession',
                   router: UrlDispatcher) -> 'CalibrationSessionStatus':
    pips = session.pipettes
    # pydantic restricts dictionary keys that can be evaluated. Since
    # the session pipettes dictionary has a UUID as a key, we must first
    # convert the UUID to a hex string.
    instruments = {token.hex: data for token, data in pips.items() if token}
    current = session.state_machine.current_state.name
    next = session.state_machine.next_state
    if next:
        path = router.get(next.name, '')
        if path:
            url = path.url_for()
        else:
            url = path
        links = {'links': {next.name: url}}
    else:
        links = {'links': {}}
    status = CalibrationSessionStatus(instruments=instruments,
                                      currentStep=current,
                                      nextSteps=links)
    return status
Example #12
0
 def route(self, router: UrlDispatcher):
     router.add_route("POST", "/users:search", self.search_users)
     router.add_route("POST", "/token/email_verify",
                      self.generate_email_verifying_token)
     router.add_route("POST", "/token/password_reset",
                      self.generate_password_reset_token)
Example #13
0
 def register(self, router: UrlDispatcher):
     router.add_route('*', '/', self.collection_endpoint.dispatch)
     router.add_route('*', f'/{self.news}/{{id}}',
                      self.instance_endpoint.dispatch)
 def register(self, router: UrlDispatcher):
     router.add_route('*', '/posts', self.collection_view.dispatch)
     router.add_route('*', '/posts/{instance_id}',
                      self.instance_view.dispatch)
Example #15
0
 def route(self, router: UrlDispatcher):
     router.add_route("PUT", "", self.put)
     router.add_route("POST", "/third_party",
                      self.create_third_party_user_token)
     router.add_route("POST", "/email", self.create_email_user_token)
     router.add_route("GET", "/self", self.get)
Example #16
0
 def register(self, router: UrlDispatcher):
     router.add_route('*', '/{notes}'.format(notes=self.notes),
                      self.collection_endpoint.dispatch)
Example #17
0
 def route(self, router: UrlDispatcher):
     router.add_route("POST", "/email", self.create_email_user)
     router.add_route("POST", "/third_party", self.create_third_party_user)
     router.add_route("GET", "/-/self", self.get_myself)
     router.add_route("PUT", "/-/self", self.update_myself)
     router.add_route("GET", "/-/{user_id}", self.get_user)
     router.add_route("POST", "/-/self:verify", self.verify_myself)
     router.add_route("PUT", "/email/self/password",
                      self.update_email_user_password)
     router.add_route("POST", "/email/self/password:reset",
                      self.reset_email_user_password)
Example #18
0
def router():
    return UrlDispatcher()
Example #19
0
 def register(self, router: UrlDispatcher):
     router.add_route('*',
                      '/{users}/{{instance_id}}'.format(users=self.users),
                      self.instance_endpoint.dispatch)
import asyncio

import pytest

from aiohttp import web
from aiohttp.web_urldispatcher import UrlDispatcher


@asyncio.coroutine
def hello(request):
    return web.Response(body=b'Hello World')

router = UrlDispatcher()
router.add_route('GET', '/', hello)


class TestPrerequisities:
    @pytest.mark.asyncio
    def test_server(self, connection, mock_url):
        response = yield from connection._session.get(mock_url)
        assert response.status == 200
        assert (yield from response.read()) == b'Hello World'
Example #21
0
 def register(self, router: UrlDispatcher):
     router.add_route('*', '/{name}'.format(name=self.name), self.collection_endpoint.dispatch)
     router.add_route('*', '/{name}/{{instance_id}}'.format(name=self.name), self.instance_endpoint.dispatch)
     router.add_route('*', '/{name}/{{instance_id}}/{{property_name}}'.format(name=self.name),
                      self.property_endpoint.dispatch)
Example #22
0
def http_router(c):
    return UrlDispatcher()
Example #23
0
import asyncio

from aiohttp.web_urldispatcher import UrlDispatcher
from aiohttp import web

from ws import ChatSock

loop = asyncio.get_event_loop()
router = UrlDispatcher()
router.add_get('/ws', ChatSock)
app = web.Application(router=router, middlewares=[])
app.ws_connections = {}
web.run_app(app, host='0.0.0.0', port=8001)
    if (request.GET['from'], request.GET['secret']) not in pytest.msgapi.api_identities:
        return web.Response(status=401)

    # Get blob
    try:
        blob = _blobs[blob_id]
    except KeyError:
        return web.Response(status=404)
    else:
        return web.Response(
            body=blob,
            content_type='application/octet-stream'
        )


router = UrlDispatcher()
router.add_route('GET', '/pubkeys/{key}', pubkeys)
router.add_route('GET', '/lookup/phone/{phone}', lookup_phone)
router.add_route('GET', '/lookup/phone_hash/{phone_hash}', lookup_phone_hash)
router.add_route('GET', '/lookup/email/{email}', lookup_email)
router.add_route('GET', '/lookup/email_hash/{email_hash}', lookup_email_hash)
router.add_route('GET', '/capabilities/{id}', capabilities)
router.add_route('GET', '/credits', credits)
router.add_route('POST', '/send_simple', send_simple)
router.add_route('POST', '/send_e2e', send_e2e)
router.add_route('POST', '/upload_blob', upload_blob)
router.add_route('GET', '/blobs/{blob_id}', download_blob)


class RawMessage(e2e.Message):
    def __init__(self, nonce=None, message=None, **kwargs):
Example #25
0
# coding utf8

from aiohttp import web
import asyncio
import os
from aiohttp.web_urldispatcher import UrlDispatcher
from typing import Callable
from functools import partial
from ..utils import io_echo
from functools import wraps
import sys
from .wrappers import AioIOWrapper

__all__ = ['router']

router = UrlDispatcher(app=NotImplemented)
print = partial(print, file=sys.__stdout__)


def out(s: str):
    '''
    Show info message with yellow color
    '''
    return io_echo("\033[92mOut: {}\033[00m".format(s))


def command_parser(cmd: str, fns: dict) -> Callable:
    '''
    get target function from funs dict and \
    map command like "cmd arg0 arg1 arg2 --key1=v1 --key2=v2" to \
    partial(fn, arg0, arg1, arg2, key1=v1, key2=v2)
Example #26
0
import logging

import aioredis
import peewee_async
import aiohttp_cors
from aiohttp import web
from aiohttp.web_urldispatcher import UrlDispatcher
from aiohttp_session import session_middleware
from aiohttp_session.redis_storage import RedisStorage

from db import database
from utils.middlewares import request_user_middleware
from settings import REDIS_CON, DATABASE
from views import Test, WebSocket, LogInView, UserInfoView, RoomListView

router = UrlDispatcher()

loop = asyncio.get_event_loop()
redis_pool = loop.run_until_complete(aioredis.create_pool(REDIS_CON,
                                                          loop=loop))
middlewares = [
    session_middleware(
        RedisStorage(redis_pool=redis_pool,
                     cookie_name='aiochat_session_id',
                     max_age=24 * 60 * 60,
                     domain="192.168.0.101",
                     httponly=False,
                     secure=False)), request_user_middleware
]
app = web.Application(router=router, middlewares=middlewares)
Example #27
0
 def hook_up(self, router: UrlDispatcher):
     router.add_post(self.make_hook_path(), self.receive_updates)
Example #28
0
 def register(self, router: UrlDispatcher):
     router.add_route('*', '/{collection}'.format(collection=self.collection_name), self.collection_endpoint.dispatch)
     router.add_route('*', '/{collection}/{{instance_id}}'.format(collection=self.collection_name), self.instance_endpoint.dispatch)
Example #29
0
import asyncio

import pytest

from aiohttp import web
from aiohttp.web_urldispatcher import UrlDispatcher


@asyncio.coroutine
def hello(request):
    return web.Response(body=b'Hello World')


router = UrlDispatcher()
router.add_route('GET', '/', hello)


class TestPrerequisities:
    @pytest.mark.asyncio
    def test_server(self, connection, mock_url):
        response = yield from connection._session.get(mock_url)
        assert response.status == 200
        assert (yield from response.read()) == b'Hello World'
Example #30
0
def test_add_to_non_initialized_router():
    router = UrlDispatcher()
    with pytest.raises(RuntimeError):
        router.add_get('/', make_handler())
Example #31
0
def test_add_to_non_initialized_router():
    router = UrlDispatcher()
    with pytest.raises(RuntimeError):
        router.add_get('/', make_handler())