Python aiohttp.web.HTTPNotFound() Examples
The following are 30
code examples of aiohttp.web.HTTPNotFound().
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: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def credential_exchange_remove(request: web.BaseRequest): """ Request handler for removing a credential exchange record. Args: request: aiohttp request object """ context = request.app["request_context"] outbound_handler = request.app["outbound_message_router"] credential_exchange_id = request.match_info["cred_ex_id"] cred_ex_record = None try: cred_ex_record = await V10CredentialExchange.retrieve_by_id( context, credential_exchange_id ) await cred_ex_record.delete_record(context) except StorageNotFoundError as err: await internal_error(err, web.HTTPNotFound, cred_ex_record, outbound_handler) except StorageError as err: await internal_error(err, web.HTTPBadRequest, cred_ex_record, outbound_handler) return web.json_response({})
Example #2
Source File: flags3_asyncio.py From notebooks with MIT License | 6 votes |
def download_one(cc, base_url, semaphore, verbose): try: with (yield from semaphore): # <5> image = yield from get_flag(base_url, cc) with (yield from semaphore): country = yield from get_country(base_url, cc) except web.HTTPNotFound: status = HTTPStatus.not_found msg = 'not found' except Exception as exc: raise FetchError(cc) from exc else: country = country.replace(' ', '_') filename = '{}-{}.gif'.format(country, cc) loop = asyncio.get_event_loop() loop.run_in_executor(None, save_flag, image, filename) status = HTTPStatus.ok msg = 'OK' if verbose and msg: print(cc, msg) return Result(status, cc) # END FLAGS3_ASYNCIO
Example #3
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def presentation_exchange_remove(request: web.BaseRequest): """ Request handler for removing a presentation exchange record. Args: request: aiohttp request object """ context = request.app["request_context"] presentation_exchange_id = request.match_info["pres_ex_id"] try: presentation_exchange_record = await V10PresentationExchange.retrieve_by_id( context, presentation_exchange_id ) await presentation_exchange_record.delete_record(context) except StorageNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err except StorageError as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({})
Example #4
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def credentials_remove(request: web.BaseRequest): """ Request handler for searching connection records. Args: request: aiohttp request object Returns: The connection list response """ context = request.app["request_context"] credential_id = request.match_info["credential_id"] holder: BaseHolder = await context.inject(BaseHolder) try: await holder.delete_credential(credential_id) except WalletNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err return web.json_response({})
Example #5
Source File: flags3_await.py From concurrency2017 with MIT License | 6 votes |
def download_one(client, cc, base_url, semaphore, verbose): try: async with semaphore: image = await get_flag(client, base_url, cc) async with semaphore: country = await get_country(client, base_url, cc) except web.HTTPNotFound: status = HTTPStatus.not_found msg = 'not found' except Exception as exc: raise FetchError(cc) from exc else: country = country.replace(' ', '_') filename = '{}-{}.gif'.format(country, cc) client.loop.run_in_executor(None, save_flag, image, filename) status = HTTPStatus.ok msg = 'OK' if verbose and msg: print(cc, msg) return Result(status, cc)
Example #6
Source File: flags3_await.py From concurrency2017 with MIT License | 6 votes |
def http_get(client, url): async with client.get(url) as res: if res.status == 200: ctype = res.headers.get('Content-type', '').lower() if 'json' in ctype or url.endswith('json'): data = await res.json() else: data = await res.read() return data elif res.status == 404: raise web.HTTPNotFound() else: raise aiohttp.errors.HttpProcessingError( code=res.status, message=res.reason, headers=res.headers)
Example #7
Source File: views.py From trace-examples with BSD 3-Clause "New" or "Revised" License | 6 votes |
def vote(request): async with request.app['db'].acquire() as conn: question_id = int(request.match_info['question_id']) data = await request.post() try: choice_id = int(data['choice']) except (KeyError, TypeError, ValueError) as e: raise web.HTTPBadRequest( text='You have not specified choice value') from e try: await db.vote(conn, question_id, choice_id) except db.RecordNotFound as e: raise web.HTTPNotFound(text=str(e)) router = request.app.router url = router['results'].url(parts={'question_id': question_id}) return web.HTTPFound(location=url)
Example #8
Source File: rest_svc.py From caldera with Apache License 2.0 | 6 votes |
def update_operation(self, op_id, state=None, autonomous=None, obfuscator=None): async def validate(op): try: if not len(op): raise web.HTTPNotFound elif await op[0].is_finished(): raise web.HTTPBadRequest(body='This operation has already finished.') elif state not in op[0].states.values(): raise web.HTTPBadRequest(body='state must be one of {}'.format(op[0].states.values())) except Exception as e: self.log.error(repr(e)) operation = await self.get_service('data_svc').locate('operations', match=dict(id=op_id)) if state: await validate(operation) operation[0].state = state if state == operation[0].states['FINISHED']: operation[0].finish = self.get_current_timestamp() self.log.debug('Changing operation=%s state to %s' % (op_id, state)) if autonomous: operation[0].autonomous = 0 if operation[0].autonomous else 1 self.log.debug('Toggled operation=%s autonomous to %s' % (op_id, bool(operation[0].autonomous))) if obfuscator: operation[0].obfuscator = obfuscator self.log.debug('Updated operation=%s obfuscator to %s' % (op_id, operation[0].obfuscator))
Example #9
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def actionmenu_close(request: web.BaseRequest): """ Request handler for closing the menu associated with a connection. Args: request: aiohttp request object """ context = request.app["request_context"] connection_id = request.match_info["conn_id"] menu = await retrieve_connection_menu(connection_id, context) if not menu: raise web.HTTPNotFound( reason=f"No {MENU_RECORD_TYPE} record found for connection {connection_id}" ) try: await save_connection_menu(None, connection_id, context) except StorageError as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({})
Example #10
Source File: vfolder.py From backend.ai-manager with GNU Lesser General Public License v3.0 | 6 votes |
def tus_session_headers(request, params): folder_path = (request.app['VFOLDER_MOUNT'] / params['host'] / request.app['VFOLDER_FSPREFIX'] / params['folder']) upload_base = folder_path / ".upload" base_file = upload_base / params['session_id'] if not Path(base_file).exists(): raise web.HTTPNotFound() headers = {} headers["Access-Control-Allow-Origin"] = "*" headers["Access-Control-Allow-Headers"] = \ "Tus-Resumable, Upload-Length, Upload-Metadata, Upload-Offset, Content-Type" headers["Access-Control-Expose-Headers"] = \ "Tus-Resumable, Upload-Length, Upload-Metadata, Upload-Offset, Content-Type" headers["Access-Control-Allow-Methods"] = "*" headers["Cache-Control"] = "no-store" headers["Tus-Resumable"] = "1.0.0" headers['Upload-Offset'] = str(Path(base_file).stat().st_size) headers['Upload-Length'] = str(params['size']) return headers
Example #11
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def actionmenu_perform(request: web.BaseRequest): """ Request handler for performing a menu action. Args: request: aiohttp request object """ context = request.app["request_context"] connection_id = request.match_info["conn_id"] outbound_handler = request.app["outbound_message_router"] params = await request.json() try: connection = await ConnectionRecord.retrieve_by_id(context, connection_id) except StorageNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err if connection.is_ready: msg = Perform(name=params["name"], params=params.get("params")) await outbound_handler(msg, connection_id=connection_id) return web.json_response({}) raise web.HTTPForbidden(reason=f"Connection {connection_id} not ready")
Example #12
Source File: flags2_await.py From concurrency2017 with MIT License | 6 votes |
def download_one(client, cc, base_url, semaphore, verbose): try: async with semaphore: image = await get_flag(client, base_url, cc) except web.HTTPNotFound: status = HTTPStatus.not_found msg = 'not found' except Exception as exc: raise FetchError(cc) from exc else: save_flag(image, cc.lower() + '.gif') status = HTTPStatus.ok msg = 'OK' if verbose and msg: print(cc, msg) return Result(status, cc)
Example #13
Source File: flags2_asyncio_executor.py From notebooks with MIT License | 6 votes |
def download_one(cc, base_url, semaphore, verbose): try: with (yield from semaphore): image = yield from get_flag(base_url, cc) except web.HTTPNotFound: status = HTTPStatus.not_found msg = 'not found' except Exception as exc: raise FetchError(cc) from exc else: loop = asyncio.get_event_loop() # <1> loop.run_in_executor(None, # <2> save_flag, image, cc.lower() + '.gif') # <3> status = HTTPStatus.ok msg = 'OK' if verbose and msg: print(cc, msg) return Result(status, cc) # END FLAGS2_ASYNCIO_EXECUTOR
Example #14
Source File: flags2_asyncio_executor.py From notebooks with MIT License | 6 votes |
def get_flag(base_url, cc): url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower()) resp = yield from aiohttp.request('GET', url) with contextlib.closing(resp): if resp.status == 200: image = yield from resp.read() return image elif resp.status == 404: raise web.HTTPNotFound() else: raise aiohttp.HttpProcessingError( code=resp.status, message=resp.reason, headers=resp.headers) # BEGIN FLAGS2_ASYNCIO_EXECUTOR
Example #15
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def connections_remove(request: web.BaseRequest): """ Request handler for removing a connection record. Args: request: aiohttp request object """ context = request.app["request_context"] connection_id = request.match_info["conn_id"] try: connection = await ConnectionRecord.retrieve_by_id(context, connection_id) await connection.delete_record(context) except StorageNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err except StorageError as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({})
Example #16
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def presentation_exchange_retrieve(request: web.BaseRequest): """ Request handler for fetching a single presentation exchange record. Args: request: aiohttp request object Returns: The presentation exchange record response """ context = request.app["request_context"] presentation_exchange_id = request.match_info["pres_ex_id"] try: record = await V10PresentationExchange.retrieve_by_id( context, presentation_exchange_id ) result = record.serialize() except StorageNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err except (BaseModelError, StorageError) as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response(result)
Example #17
Source File: main.py From aiohttp-swagger3 with Apache License 2.0 | 6 votes |
def delete_one_pet(request: web.Request, pet_id: int) -> web.Response: """ --- summary: Deletes specific pet tags: - pets parameters: - name: pet_id in: path required: true description: The id of the pet to delete schema: type: integer format: int32 responses: '204': description: Null response """ if pet_id not in request.app["storage"]: raise web.HTTPNotFound() del request.app["storage"][pet_id] return web.json_response(status=204)
Example #18
Source File: main.py From aiohttp-swagger3 with Apache License 2.0 | 6 votes |
def get_one_pet(request: web.Request, pet_id: int) -> web.Response: """ --- summary: Info for a specific pet tags: - pets parameters: - name: pet_id in: path required: true description: The id of the pet to retrieve schema: type: integer format: int32 responses: '200': description: Expected response to a valid request content: application/json: schema: $ref: "#/components/schemas/Pet" """ if pet_id not in request.app["storage"]: raise web.HTTPNotFound() return web.json_response(request.app["storage"][pet_id])
Example #19
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
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 #20
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
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 #21
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def get_tails_file(request: web.BaseRequest) -> web.FileResponse: """ Request handler to download the tails file of the revocation registry. Args: request: aiohttp request object Returns: The tails file in FileResponse """ 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.FileResponse(path=revoc_registry.tails_local_path, status=200)
Example #22
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def connections_establish_inbound(request: web.BaseRequest): """ Request handler for setting the inbound connection on a connection record. Args: request: aiohttp request object """ context = request.app["request_context"] connection_id = request.match_info["conn_id"] outbound_handler = request.app["outbound_message_router"] inbound_connection_id = request.match_info["ref_id"] try: connection = await ConnectionRecord.retrieve_by_id(context, connection_id) connection_mgr = ConnectionManager(context) await connection_mgr.establish_inbound( connection, inbound_connection_id, outbound_handler ) except StorageNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err except (StorageError, WalletError, ConnectionManagerError) as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response({})
Example #23
Source File: test_routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def test_create_registry_no_such_cred_def(self): CRED_DEF_ID = f"{self.test_did}:3:CL:1234:default" request = async_mock.MagicMock() request.app = self.app request.json = async_mock.CoroutineMock( return_value={ "max_cred_num": "1000", "credential_definition_id": CRED_DEF_ID, } ) with async_mock.patch.object( self.storage, "search_records", autospec=True ) as mock_search, async_mock.patch.object( test_module.web, "json_response", async_mock.Mock() ) as mock_json_response: mock_search.return_value.fetch_all = async_mock.CoroutineMock( return_value=False ) with self.assertRaises(HTTPNotFound): result = await test_module.revocation_create_registry(request) mock_json_response.assert_not_called()
Example #24
Source File: test_routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def test_get_registry_not_found(self): REV_REG_ID = "{}:4:{}:3:CL:1234:default:CL_ACCUM:default".format( self.test_did, self.test_did ) request = async_mock.MagicMock() request.app = self.app request.match_info = {"rev_reg_id": REV_REG_ID} with async_mock.patch.object( test_module, "IndyRevocation", autospec=True ) as mock_indy_revoc, async_mock.patch.object( test_module.web, "json_response", async_mock.Mock() ) as mock_json_response: mock_indy_revoc.return_value = async_mock.MagicMock( get_issuer_rev_reg_record=async_mock.CoroutineMock( side_effect=test_module.StorageNotFoundError(error_code="dummy") ) ) with self.assertRaises(HTTPNotFound): result = await test_module.get_registry(request) mock_json_response.assert_not_called()
Example #25
Source File: test_routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def test_get_active_registry_not_found(self): CRED_DEF_ID = f"{self.test_did}:3:CL:1234:default" request = async_mock.MagicMock() request.app = self.app request.match_info = {"cred_def_id": CRED_DEF_ID} with async_mock.patch.object( test_module, "IndyRevocation", autospec=True ) as mock_indy_revoc, async_mock.patch.object( test_module.web, "json_response", async_mock.Mock() ) as mock_json_response: mock_indy_revoc.return_value = async_mock.MagicMock( get_active_issuer_rev_reg_record=async_mock.CoroutineMock( side_effect=test_module.StorageNotFoundError(error_code="dummy") ) ) with self.assertRaises(HTTPNotFound): result = await test_module.get_active_registry(request) mock_json_response.assert_not_called()
Example #26
Source File: test_routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def test_get_tails_file_not_found(self): REV_REG_ID = "{}:4:{}:3:CL:1234:default:CL_ACCUM:default".format( self.test_did, self.test_did ) request = async_mock.MagicMock() request.app = self.app request.match_info = {"rev_reg_id": REV_REG_ID} with async_mock.patch.object( test_module, "IndyRevocation", autospec=True ) as mock_indy_revoc, async_mock.patch.object( test_module.web, "FileResponse", async_mock.Mock() ) as mock_file_response: mock_indy_revoc.return_value = async_mock.MagicMock( get_issuer_rev_reg_record=async_mock.CoroutineMock( side_effect=test_module.StorageNotFoundError(error_code="dummy") ) ) with self.assertRaises(HTTPNotFound): result = await test_module.get_tails_file(request) mock_file_response.assert_not_called()
Example #27
Source File: routes.py From dffml with MIT License | 6 votes |
def get_source_contexts(self, request, sctx_label_list): sources_context = SourcesContext([]) for label in sctx_label_list: sctx = request.app["source_contexts"].get(label, None) if sctx is None: raise web.HTTPNotFound( text=list(SOURCE_NOT_LOADED.values())[0], content_type="application/json", ) sources_context.append(sctx) if not sources_context: raise web.HTTPBadRequest( text=list(MODEL_NO_SOURCES.values())[0], content_type="application/json", ) return sources_context
Example #28
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def connections_send_message(request: web.BaseRequest): """ Request handler for sending a basic message to a connection. Args: request: aiohttp request object """ context = request.app["request_context"] connection_id = request.match_info["conn_id"] outbound_handler = request.app["outbound_message_router"] params = await request.json() try: connection = await ConnectionRecord.retrieve_by_id(context, connection_id) except StorageNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err if connection.is_ready: msg = BasicMessage(content=params["content"]) await outbound_handler(msg, connection_id=connection_id) return web.json_response({})
Example #29
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def actionmenu_request(request: web.BaseRequest): """ Request handler for requesting a menu from the connection target. Args: request: aiohttp request object """ context = request.app["request_context"] connection_id = request.match_info["conn_id"] outbound_handler = request.app["outbound_message_router"] try: connection = await ConnectionRecord.retrieve_by_id(context, connection_id) except StorageNotFoundError as err: LOGGER.debug("Connection not found for action menu request: %s", connection_id) raise web.HTTPNotFound(reason=err.roll_up) from err if connection.is_ready: msg = MenuRequest() await outbound_handler(msg, connection_id=connection_id) return web.json_response({}) raise web.HTTPForbidden(reason=f"Connection {connection_id} not ready")
Example #30
Source File: routes.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def connections_retrieve(request: web.BaseRequest): """ Request handler for fetching a single connection record. Args: request: aiohttp request object Returns: The connection record response """ context = request.app["request_context"] connection_id = request.match_info["conn_id"] try: record = await ConnectionRecord.retrieve_by_id(context, connection_id) result = record.serialize() except StorageNotFoundError as err: raise web.HTTPNotFound(reason=err.roll_up) from err except BaseModelError as err: raise web.HTTPBadRequest(reason=err.roll_up) from err return web.json_response(result)