Python aiohttp.web.get() Examples

The following are 30 code examples of aiohttp.web.get(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module aiohttp.web , or try the search function .
Example #1
Source File: identity_endpoint.py    From py-ipv8 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def verify_pseudonym_credential(self, request):
        parameters = await request.json()
        if 'hash' not in parameters or 'value' not in parameters or 'schema' not in parameters:
            return Response({"error": "incorrect parameters"}, status=HTTP_BAD_REQUEST)

        channel = await self.communication_manager.load(request.match_info['pseudonym_name'],
                                                        request.headers.get('X-Rendezvous'))

        subject = None
        for peer in channel.peers:
            if peer.public_key.key_to_bin() == ez_b64_decode(request.match_info['subject_key']):
                subject = peer
                break
        if subject is None:
            return Response({"success": False, "error": "failed to find subject"})

        channel.verify(subject, ez_b64_decode(parameters["hash"]), [ez_b64_decode(parameters["value"])],
                       parameters["schema"])

        return Response({"success": True}) 
Example #2
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def get_registry(request: web.BaseRequest):
    """
    Request handler to get a revocation registry by identifier.

    Args:
        request: aiohttp request object

    Returns:
        The revocation registry

    """
    context = request.app["request_context"]

    registry_id = request.match_info["rev_reg_id"]

    try:
        revoc = IndyRevocation(context)
        revoc_registry = await revoc.get_issuer_rev_reg_record(registry_id)
    except StorageNotFoundError as err:
        raise web.HTTPNotFound(reason=err.roll_up) from err

    return web.json_response({"result": revoc_registry.serialize()}) 
Example #3
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def revocation_registries_created(request: web.BaseRequest):
    """
    Request handler to get revocation registries that current agent created.

    Args:
        request: aiohttp request object

    Returns:
        List of identifiers of matching revocation registries.

    """
    context = request.app["request_context"]

    search_tags = [
        tag for tag in vars(RevRegsCreatedQueryStringSchema)["_declared_fields"]
    ]
    tag_filter = {
        tag: request.query[tag] for tag in search_tags if tag in request.query
    }
    found = await IssuerRevRegRecord.query(context, tag_filter)

    return web.json_response({"rev_reg_ids": [record.revoc_reg_id for record in found]}) 
Example #4
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def register(app: web.Application):
    """Register routes."""

    app.add_routes(
        [
            web.get("/connections", connections_list, allow_head=False),
            web.get("/connections/{conn_id}", connections_retrieve, allow_head=False),
            web.post("/connections/create-static", connections_create_static),
            web.post("/connections/create-invitation", connections_create_invitation),
            web.post("/connections/receive-invitation", connections_receive_invitation),
            web.post(
                "/connections/{conn_id}/accept-invitation",
                connections_accept_invitation,
            ),
            web.post(
                "/connections/{conn_id}/accept-request", connections_accept_request
            ),
            web.post(
                "/connections/{conn_id}/establish-inbound/{ref_id}",
                connections_establish_inbound,
            ),
            web.post("/connections/{conn_id}/remove", connections_remove),
        ]
    ) 
Example #5
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def get_active_registry(request: web.BaseRequest):
    """
    Request handler to get an active revocation registry by cred def id.

    Args:
        request: aiohttp request object

    Returns:
        The revocation registry identifier

    """
    context = request.app["request_context"]

    cred_def_id = request.match_info["cred_def_id"]

    try:
        revoc = IndyRevocation(context)
        revoc_registry = await revoc.get_active_issuer_rev_reg_record(cred_def_id)
    except StorageNotFoundError as err:
        raise web.HTTPNotFound(reason=err.roll_up) from err

    return web.json_response({"result": revoc_registry.serialize()}) 
Example #6
Source File: identity_endpoint.py    From py-ipv8 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def setup_routes(self):
        self.app.add_routes([web.get('', self.list_pseudonyms),

                             web.get('/{pseudonym_name}/schemas', self.list_schemas),

                             web.get('/{pseudonym_name}/public_key', self.get_pseudonym_public_key),
                             web.get('/{pseudonym_name}/unload', self.unload_pseudonym),
                             web.get('/{pseudonym_name}/remove', self.remove_pseudonym),

                             web.get('/{pseudonym_name}/credentials', self.list_pseudonym_credentials),
                             web.get('/{pseudonym_name}/credentials/{subject_key}', self.list_subject_credentials),
                             web.get('/{pseudonym_name}/peers', self.list_pseudonym_peers),

                             web.put('/{pseudonym_name}/allow/{verifier_key}', self.allow_pseudonym_verification),
                             web.put('/{pseudonym_name}/disallow/{verifier_key}', self.disallow_pseudonym_verification),
                             web.put('/{pseudonym_name}/request/{authority_key}', self.create_pseudonym_credential),

                             web.put('/{pseudonym_name}/attest/{subject_key}', self.attest_pseudonym_credential),
                             web.put('/{pseudonym_name}/verify/{subject_key}', self.verify_pseudonym_credential),

                             web.get('/{pseudonym_name}/outstanding/attestations', self.list_pseudonym_outstanding_attestations),
                             web.get('/{pseudonym_name}/outstanding/verifications', self.list_pseudonym_outstanding_verifications),

                             web.get('/{pseudonym_name}/verifications', self.list_pseudonym_verification_output)
                             ]) 
Example #7
Source File: identity_endpoint.py    From py-ipv8 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def list_subject_credentials(self, request):
        channel = await self.communication_manager.load(request.match_info['pseudonym_name'],
                                                        request.headers.get('X-Rendezvous'))

        subject = None
        for peer in channel.peers:
            if peer.public_key.key_to_bin() == ez_b64_decode(request.match_info['subject_key']):
                subject = peer
                break
        if subject is None:
            return Response({"success": False, "error": "failed to find subject"})

        return Response({"names": [{
            "name": data[0],
            "hash": ez_b64_encode(strip_sha1_padding(attribute_hash)),
            "metadata": data[1],
            "attesters": [ez_b64_encode(attester) for attester in data[2]]
        }
            for attribute_hash, data in channel.get_attributes(subject).items()]
        }) 
Example #8
Source File: identity_endpoint.py    From py-ipv8 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def allow_pseudonym_verification(self, request):
        parameters = await request.json()
        if 'name' not in parameters:
            return Response({"error": "incorrect parameters"}, status=HTTP_BAD_REQUEST)

        channel = await self.communication_manager.load(request.match_info['pseudonym_name'],
                                                        request.headers.get('X-Rendezvous'))
        verifier = None
        for peer in channel.peers:
            if peer.public_key.key_to_bin() == ez_b64_decode(request.match_info['verifier_key']):
                verifier = peer
                break
        if verifier is None:
            return Response({"success": False, "error": "failed to find verifier"})

        channel.allow_verification(verifier, parameters['name'])

        return Response({"success": True}) 
Example #9
Source File: identity_endpoint.py    From py-ipv8 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def disallow_pseudonym_verification(self, request):
        parameters = await request.json()
        if 'name' not in parameters:
            return Response({"error": "incorrect parameters"}, status=HTTP_BAD_REQUEST)

        channel = await self.communication_manager.load(request.match_info['pseudonym_name'],
                                                        request.headers.get('X-Rendezvous'))
        verifier = None
        for peer in channel.peers:
            if peer.public_key.key_to_bin() == ez_b64_decode(request.match_info['verifier_key']):
                verifier = peer
                break
        if verifier is None:
            return Response({"success": False, "error": "failed to find verifier"})

        channel.disallow_verification(verifier, parameters['name'])

        return Response({"success": True}) 
Example #10
Source File: identity_endpoint.py    From py-ipv8 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def create_pseudonym_credential(self, request):
        parameters = await request.json()
        if 'name' not in parameters or 'schema' not in parameters:
            return Response({"error": "incorrect parameters"}, status=HTTP_BAD_REQUEST)

        channel = await self.communication_manager.load(request.match_info['pseudonym_name'],
                                                        request.headers.get('X-Rendezvous'))
        authority = None
        for peer in channel.peers:
            if peer.public_key.key_to_bin() == ez_b64_decode(request.match_info['authority_key']):
                authority = peer
                break
        if authority is None:
            return Response({"success": False, "error": "failed to find authority"})

        metadata = parameters['metadata'] if 'metadata' in parameters else {}
        channel.request_attestation(authority, parameters['name'], parameters['schema'], metadata)

        return Response({"success": True}) 
Example #11
Source File: identity_endpoint.py    From py-ipv8 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def attest_pseudonym_credential(self, request):
        parameters = await request.json()
        if 'name' not in parameters or 'value' not in parameters:
            return Response({"error": "incorrect parameters"}, status=HTTP_BAD_REQUEST)

        channel = await self.communication_manager.load(request.match_info['pseudonym_name'],
                                                        request.headers.get('X-Rendezvous'))

        subject = None
        for peer in channel.peers:
            if peer.public_key.key_to_bin() == ez_b64_decode(request.match_info['subject_key']):
                subject = peer
                break
        if subject is None:
            return Response({"success": False, "error": "failed to find subject"})

        channel.attest(subject, parameters["name"], ez_b64_decode(parameters["value"]))

        return Response({"success": True}) 
Example #12
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def credential_exchange_publish_revocations(request: web.BaseRequest):
    """
    Request handler for publishing pending revocations to the ledger.

    Args:
        request: aiohttp request object

    Returns:
        Credential revocation ids published as revoked by revocation registry id.

    """
    context = request.app["request_context"]
    body = await request.json()
    rrid2crid = body.get("rrid2crid")

    credential_manager = CredentialManager(context)

    try:
        results = await credential_manager.publish_pending_revocations(rrid2crid)
    except (RevocationError, StorageError, IssuerError, LedgerError) as err:
        raise web.HTTPBadRequest(reason=err.roll_up) from err
    return web.json_response({"rrid2crid": results}) 
Example #13
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def query_features(request: web.BaseRequest):
    """
    Request handler for inspecting supported protocols.

    Args:
        request: aiohttp request object

    Returns:
        The diclosed protocols response

    """
    context = request.app["request_context"]
    registry: ProtocolRegistry = await context.inject(ProtocolRegistry)
    results = registry.protocols_matching_query(request.query.get("query", "*"))

    return web.json_response({"results": {k: {} for k in results}}) 
Example #14
Source File: test_async.py    From schemathesis with MIT License 6 votes vote down vote up
def test_settings_first(testdir, plugin):
    # When `hypothesis.settings` decorator is applied to a coroutine-based test before `parametrize`
    parameters = {"parameters": [integer(name="id", required=True)]}
    testdir.make_test(
        f"""
@schema.parametrize()
{"@pytest.mark.asyncio" if plugin == "pytest_asyncio" else ""}
@settings(max_examples=5)
async def test_(request, case):
    request.config.HYPOTHESIS_CASES += 1
    assert case.full_path == "/v1/users"
    assert case.method in ("GET", "POST")
""",
        pytest_plugins=[plugin],
        paths={"/users": {"get": parameters, "post": parameters}},
    )
    result = testdir.runpytest("-v", "-s")
    result.assert_outcomes(passed=2)
    # Then it should be executed as any other test
    result.stdout.re_match_lines([r"Hypothesis calls: 10$"]) 
Example #15
Source File: http.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def invite_message_handler(self, request: web.BaseRequest):
        """
        Message handler for invites.

        Args:
            request: aiohttp request object

        Returns:
            The web response

        """
        if request.query.get("c_i"):
            return web.Response(
                text="You have received a connection invitation. To accept the "
                "invitation, paste it into your agent application."
            )
        else:
            return web.Response(status=200) 
Example #16
Source File: asyncio_endpoint.py    From py-ipv8 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_asyncio_debug(self, request):
        parameters = await request.json()
        if 'enable' not in parameters and 'slow_callback_duration' not in parameters:
            return Response({"success": False, "error": "incorrect parameters"}, status=HTTP_BAD_REQUEST)

        loop = get_event_loop()
        loop.slow_callback_duration = parameters.get('slow_callback_duration', loop.slow_callback_duration)

        if 'enable' in parameters:
            enable = bool(parameters['enable'])
            loop.set_debug(enable)

            # Add/remove asyncio log handler
            if enable and not self.asyncio_log_handler:
                self.asyncio_log_handler = DequeLogHandler()
                logging.getLogger('asyncio').addHandler(self.asyncio_log_handler)
            if not enable and self.asyncio_log_handler:
                logging.getLogger('asyncio').removeHandler(self.asyncio_log_handler)
                self.asyncio_log_handler = None

        return Response({"success": True}) 
Example #17
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def register(app: web.Application):
    """Register routes."""

    app.add_routes(
        [
            web.get("/wallet/did", wallet_did_list, allow_head=False),
            web.post("/wallet/did/create", wallet_create_did),
            web.get("/wallet/did/public", wallet_get_public_did, allow_head=False),
            web.post("/wallet/did/public", wallet_set_public_did),
            web.post("/wallet/set-did-endpoint", wallet_set_did_endpoint),
            web.get(
                "/wallet/get-did-endpoint", wallet_get_did_endpoint, allow_head=False
            ),
            web.patch("/wallet/did/local/rotate-keypair", wallet_rotate_did_keypair),
        ]
    ) 
Example #18
Source File: asyncio_endpoint.py    From py-ipv8 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def setup_routes(self):
        self.app.add_routes([web.get('/drift', self.retrieve_drift),
                             web.put('/drift', self.enable_measurements),
                             web.get('/tasks', self.get_asyncio_tasks),
                             web.put('/debug', self.set_asyncio_debug),
                             web.get('/debug', self.get_asyncio_debug)]) 
Example #19
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def format_did_info(info: DIDInfo):
    """Serialize a DIDInfo object."""
    if info:
        return {
            "did": info.did,
            "verkey": info.verkey,
            "public": json.dumps(bool(info.metadata.get("public"))),
        } 
Example #20
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def wallet_get_did_endpoint(request: web.BaseRequest):
    """
    Request handler for getting the current DID endpoint from the wallet.

    Args:
        request: aiohttp request object

    Returns:
        The updated DID info

    """
    context = request.app["request_context"]
    wallet: BaseWallet = await context.inject(BaseWallet, required=False)
    if not wallet:
        raise web.HTTPForbidden(reason="No wallet available")
    did = request.query.get("did")
    if not did:
        raise web.HTTPBadRequest(reason="Request query must include DID")
    try:
        did_info = await wallet.get_local_did(did)
        endpoint = did_info.metadata.get("endpoint")
    except WalletNotFoundError as err:
        raise web.HTTPNotFound(reason=err.roll_up) from err
    except WalletError as err:
        raise web.HTTPBadRequest(reason=err.roll_up) from err

    return web.json_response({"did": did, "endpoint": endpoint}) 
Example #21
Source File: tunnel_endpoint.py    From py-ipv8 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_swarm_size(self, request):
        infohash = unhexlify(request.match_info['infohash'])
        swarm_size = await self.tunnels.estimate_swarm_size(infohash, hops=request.query.get('hops', 1))
        return Response({"swarm_size": swarm_size}) 
Example #22
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def credentials_list(request: web.BaseRequest):
    """
    Request handler for searching credential records.

    Args:
        request: aiohttp request object

    Returns:
        The credential list response

    """
    context = request.app["request_context"]

    start = request.query.get("start")
    count = request.query.get("count")

    # url encoded json wql
    encoded_wql = request.query.get("wql") or "{}"
    wql = json.loads(encoded_wql)

    # defaults
    start = int(start) if isinstance(start, str) else 0
    count = int(count) if isinstance(count, str) else 10

    holder: BaseHolder = await context.inject(BaseHolder)
    try:
        credentials = await holder.get_credentials(start, count, wql)
    except HolderError as err:
        raise web.HTTPBadRequest(reason=err.roll_up) from err

    return web.json_response({"results": credentials}) 
Example #23
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def register(app: web.Application):
    """Register routes."""
    app.add_routes(
        [
            web.post("/schemas", schemas_send_schema),
            web.get("/schemas/created", schemas_created, allow_head=False),
            web.get("/schemas/{schema_id}", schemas_get_schema, allow_head=False),
        ]
    ) 
Example #24
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def schemas_send_schema(request: web.BaseRequest):
    """
    Request handler for sending a credential offer.

    Args:
        request: aiohttp request object

    Returns:
        The schema id sent

    """
    context = request.app["request_context"]

    body = await request.json()

    schema_name = body.get("schema_name")
    schema_version = body.get("schema_version")
    attributes = body.get("attributes")

    ledger: BaseLedger = await context.inject(BaseLedger, required=False)
    if not ledger:
        reason = "No ledger available"
        if not context.settings.get_value("wallet.type"):
            reason += ": missing wallet-type?"
        raise web.HTTPForbidden(reason=reason)

    issuer: BaseIssuer = await context.inject(BaseIssuer)
    async with ledger:
        try:
            schema_id, schema_def = await shield(
                ledger.create_and_send_schema(
                    issuer, schema_name, schema_version, attributes
                )
            )
        except (IssuerError, LedgerError) as err:
            raise web.HTTPBadRequest(reason=err.roll_up) from err

    return web.json_response({"schema_id": schema_id, "schema": schema_def}) 
Example #25
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def credential_definitions_send_credential_definition(request: web.BaseRequest):
    """
    Request handler for sending a credential definition to the ledger.

    Args:
        request: aiohttp request object

    Returns:
        The credential definition identifier

    """
    context = request.app["request_context"]

    body = await request.json()

    schema_id = body.get("schema_id")
    support_revocation = bool(body.get("support_revocation"))
    tag = body.get("tag")

    ledger: BaseLedger = await context.inject(BaseLedger, required=False)
    if not ledger:
        reason = "No ledger available"
        if not context.settings.get_value("wallet.type"):
            reason += ": missing wallet-type?"
        raise web.HTTPForbidden(reason=reason)

    issuer: BaseIssuer = await context.inject(BaseIssuer)
    async with ledger:
        credential_definition_id, credential_definition = await shield(
            ledger.create_and_send_credential_definition(
                issuer,
                schema_id,
                signature_type=None,
                tag=tag,
                support_revocation=support_revocation,
            )
        )

    return web.json_response({"credential_definition_id": credential_definition_id}) 
Example #26
Source File: test_ws_transport.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def get_application(self):
        """
        Override the get_app method to return your application.
        """
        app = web.Application()
        app.add_routes([web.get("/", self.receive_message)])
        return app 
Example #27
Source File: http.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def make_application(self) -> web.Application:
        """Construct the aiohttp application."""
        app_args = {}
        if self.max_message_size:
            app_args["client_max_size"] = self.max_message_size
        app = web.Application(**app_args)
        app.add_routes([web.get("/", self.invite_message_handler)])
        app.add_routes([web.post("/", self.inbound_message_handler)])
        return app 
Example #28
Source File: test_http.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def get_application(self):
        app = web.Application()
        app.add_routes(
            [web.get("/fail", self.fail_route), web.get("/succeed", self.succeed_route)]
        )
        return app 
Example #29
Source File: routes.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def register(app: web.Application):
    """Register routes."""

    app.add_routes(
        [
            web.get("/credential/{credential_id}", credentials_get, allow_head=False),
            web.get(
                "/credential/mime-types/{credential_id}",
                credentials_attr_mime_types_get,
                allow_head=False,
            ),
            web.post("/credential/{credential_id}/remove", credentials_remove),
            web.get("/credentials", credentials_list, allow_head=False),
        ]
    ) 
Example #30
Source File: wuy.py    From wuy with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, url, size=None, chromeArgs=[]):
        self.__instance = None

        if sys.platform[:3] == "win":
            exe = find_chrome_win()
        elif sys.platform == "darwin":
            exe = find_chrome_mac()
        else:
            for i in ["chromium-browser", "chromium", "google-chrome", "chrome"]:
                try:
                    exe = webbrowser.get(i).name
                    break
                except webbrowser.Error:
                    exe = None

        if exe:
            args = [exe, "--app=" + url] + chromeArgs
            if size == FULLSCREEN:
                args.append("--start-fullscreen")
            if tempfile.gettempdir():
                args.append(
                    "--user-data-dir=%s"
                    % os.path.join(tempfile.gettempdir(), ".wuyapp")
                )
            # self.__instance = subprocess.Popen( args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) # make troubles on windows (freezd with noconsole don't start)
            self.__instance = subprocess.Popen(args)
        else:
            raise Exception("no browser")