Python http.HTTPStatus.NOT_FOUND Examples
The following are 30
code examples of http.HTTPStatus.NOT_FOUND().
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
http.HTTPStatus
, or try the search function
.
Example #1
Source File: column.py From amundsenmetadatalibrary with Apache License 2.0 | 6 votes |
def get(self, table_uri: str, column_name: str) -> Union[tuple, int, None]: """ Gets column descriptions in Neo4j """ try: description = self.client.get_column_description(table_uri=table_uri, column_name=column_name) return {'description': description}, HTTPStatus.OK except NotFoundException: msg = 'table_uri {} with column {} does not exist'.format(table_uri, column_name) return {'message': msg}, HTTPStatus.NOT_FOUND except Exception: return {'message': 'Internal server error!'}, HTTPStatus.INTERNAL_SERVER_ERROR
Example #2
Source File: test_rproxy.py From dffml with MIT License | 6 votes |
def test_not_found(self): async with rproxy( self, self.UPSTREAM_PATH, subdomain=self.PROXY_SUBDOMAIN, path=self.PROXY_PATH, ) as rctx, aiohttp.ClientSession() as session: url = "http://%s.%s:%d%s" % ( self.PROXY_SUBDOMAIN + ".not.found", self.TEST_ADDRESS, rctx.port, self.PROXY_PATH, ) LOGGER.debug("rproxy url: %s", url) async with session.get(url) as resp: self.assertEqual(resp.status, HTTPStatus.NOT_FOUND)
Example #3
Source File: routes.py From dffml with MIT License | 6 votes |
def mcctx_route(handler): """ Ensure that the labeled multicomm context requested is loaded. Return the mcctx if it is loaded and an error otherwise. """ @wraps(handler) async def get_mcctx(self, request): mcctx = request.app["multicomm_contexts"].get( request.match_info["label"], None ) if mcctx is None: return web.json_response( MULTICOMM_NOT_LOADED, status=HTTPStatus.NOT_FOUND ) return await handler(self, request, mcctx) return get_mcctx
Example #4
Source File: routes.py From dffml with MIT License | 6 votes |
def sctx_route(handler): """ Ensure that the labeled source context requested is loaded. Return the sctx if it is loaded and an error otherwise. """ @wraps(handler) async def get_sctx(self, request): sctx = request.app["source_contexts"].get( request.match_info["label"], None ) if sctx is None: return web.json_response( SOURCE_NOT_LOADED, status=HTTPStatus.NOT_FOUND ) return await handler(self, request, sctx) return get_sctx
Example #5
Source File: routes.py From dffml with MIT License | 6 votes |
def mctx_route(handler): """ Ensure that the labeled model context requested is loaded. Return the mctx if it is loaded and an error otherwise. """ @wraps(handler) async def get_mctx(self, request): mctx = request.app["model_contexts"].get( request.match_info["label"], None ) if mctx is None: return web.json_response( MODEL_NOT_LOADED, status=HTTPStatus.NOT_FOUND ) return await handler(self, request, mctx) return get_mctx
Example #6
Source File: routes.py From dffml with MIT License | 6 votes |
def context_source(self, request): label = request.match_info["label"] ctx_label = request.match_info["ctx_label"] if not label in request.app["sources"]: return web.json_response( {"error": f"{label} source not found"}, status=HTTPStatus.NOT_FOUND, ) # Enter the source context and pass the features exit_stack = request.app["exit_stack"] source = request.app["sources"][label] mctx = await exit_stack.enter_async_context(source()) request.app["source_contexts"][ctx_label] = mctx return web.json_response(OK)
Example #7
Source File: conftest.py From vulnix with BSD 3-Clause "New" or "Revised" License | 6 votes |
def do_GET(self): """Serve a GET request from the fixtures directory""" fn = p.join(p.dirname(__file__), 'fixtures', self.path[1:]) print("path=", fn) try: with open(fn, 'rb') as f: stat = os.fstat(f.fileno()) content = f.read() except OSError: self.send_error(HTTPStatus.NOT_FOUND) except IOError: self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR) self.send_response(HTTPStatus.OK) self.send_header('Content-Type', self.guess_type(fn)) self.send_header('Content-Length', stat.st_size) self.send_header('ETag', hashlib.sha1(content).hexdigest()) self.end_headers() self.wfile.write(content)
Example #8
Source File: __init__.py From thingsboard_api_tools with MIT License | 6 votes |
def delete(self, params, msg): url = self.mothership_url + params headers = {"Accept": "application/json"} self.add_auth_header(headers) if self.verbose: req = requests.Request("DELETE", url, headers=headers) prepared = req.prepare() TbApi.pretty_print_request(prepared) response = requests.delete(url, headers=headers) # Don't fail if not found if(response.status_code == HTTPStatus.NOT_FOUND): return False self.validate_response(response, msg) return True
Example #9
Source File: routes.py From dffml with MIT License | 6 votes |
def context_model(self, request): label = request.match_info["label"] ctx_label = request.match_info["ctx_label"] if not label in request.app["models"]: return web.json_response( {"error": f"{label} model not found"}, status=HTTPStatus.NOT_FOUND, ) # Enter the model context and pass the features exit_stack = request.app["exit_stack"] model = request.app["models"][label] mctx = await exit_stack.enter_async_context(model()) request.app["model_contexts"][ctx_label] = mctx return web.json_response(OK)
Example #10
Source File: jsonapi.py From safrs with GNU General Public License v3.0 | 6 votes |
def get_swagger_doc(cls, http_method): """ Create a swagger api model based on the sqlalchemy schema if an instance exists in the DB, the first entry is used as example """ body = {} responses = {} object_name = cls.__name__ object_model = {} responses = {HTTPStatus.OK.value: {"description": "{} object".format(object_name), "schema": object_model}} if http_method.upper() in ("POST", "GET"): responses = { HTTPStatus.OK.value: {"description": HTTPStatus.OK.description}, HTTPStatus.NOT_FOUND.value: {"description": HTTPStatus.NOT_FOUND.description}, } return body, responses
Example #11
Source File: __init__.py From amundsenmetadatalibrary with Apache License 2.0 | 6 votes |
def get_with_kwargs(self, *, id: Optional[str] = None, **kwargs: Optional[Any]) \ -> Iterable[Union[Mapping, int, None]]: if id is not None: get_object = getattr(self.client, f'get_{self.str_type}') try: actual_id: Union[str, int] = int(id) if id.isdigit() else id object = get_object(id=actual_id, **kwargs) if object is not None: return self.schema().dump(object).data, HTTPStatus.OK return None, HTTPStatus.NOT_FOUND except ValueError as e: return {'message': f'exception:{e}'}, HTTPStatus.BAD_REQUEST else: get_objects = getattr(self.client, f'get_{self.str_type}s') objects: List[Any] = get_objects() return self.schema(many=True).dump(objects).data, HTTPStatus.OK
Example #12
Source File: test_jobs.py From asgard-api with MIT License | 6 votes |
def test_update_job_job_does_not_exist(self, dev_job_fixture): await _load_jobs_into_chronos(dev_job_fixture) asgard_job = ChronosScheduledJobConverter.to_asgard_model( ChronosJob(**dev_job_fixture) ) asgard_job.id = "job-does-not-exist" asgard_job.remove_namespace(self.account) resp = await self.client.put( f"/jobs/{asgard_job.id}", headers={ "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}" }, json=asgard_job.dict(), ) self.assertEqual(HTTPStatus.NOT_FOUND, resp.status) self.assertEqual( ErrorResource( errors=[ErrorDetail(msg=f"Entity not found: {asgard_job.id}")] ).dict(), await resp.json(), )
Example #13
Source File: test_jobs.py From asgard-api with MIT License | 6 votes |
def test_delete_job_job_exist(self, dev_job_fixture): await _load_jobs_into_chronos(dev_job_fixture) asgard_job = ChronosScheduledJobConverter.to_asgard_model( ChronosJob(**dev_job_fixture) ).remove_namespace(self.account) resp = await self.client.delete( f"/jobs/{asgard_job.id}", headers={ "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}" }, ) self.assertEqual(HTTPStatus.OK, resp.status) resp_data = await resp.json() self.assertEqual(ScheduledJobResource(job=asgard_job).dict(), resp_data) resp = await self.client.get( f"/jobs/{asgard_job.id}", headers={ "Authorization": f"Token {USER_WITH_MULTIPLE_ACCOUNTS_AUTH_KEY}" }, ) self.assertEqual(HTTPStatus.NOT_FOUND, resp.status)
Example #14
Source File: tasks.py From asgard-api with MIT License | 6 votes |
def download_by_id(download_id): file_data = cache.get(f"downloads/{download_id}") if not file_data: return Response(status=HTTPStatus.NOT_FOUND) file_url = file_data["file_url"] task_id = file_data["task_id"] file_path = file_data["file_path"] response = requests.get(file_url, stream=True) if response.status_code == HTTPStatus.NOT_FOUND: return Response(response=json.dumps({}), status=HTTPStatus.NOT_FOUND) filename = f"{task_id}_{file_path.strip('/')}.log" return Response( response=response.iter_content(chunk_size=4096), status=200, headers={ "Content-Disposition": f"attachment; filename={filename}", "Content-Type": "application/octet-stream", }, )
Example #15
Source File: test_http_client.py From asgard-api with MIT License | 6 votes |
def test_exceptions_have_detail_info_about_the_request_that_failed( self ): """ Cada exceção lançada deve carregar algumas infos sobre o request original. A ClientResponseError da aiohttp tem tudo que queremos. A exception lançada pelo client contém: - request_info original - status (int) """ client = HttpClient() url = "https://httpbin.org/status/404" try: await client.get(url) except HTTPNotFound as e: self.assertEqual(HTTPStatus.NOT_FOUND, e.status) self.assertEqual(url, str(e.request_info.url)) self.assertEqual("GET", e.request_info.method) self.assertIsNotNone(e.request_info.headers)
Example #16
Source File: webserver.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def _check_status(self): """Check if the http status is what we expected.""" path_to_statuses = { '/favicon.ico': [HTTPStatus.OK, HTTPStatus.PARTIAL_CONTENT], '/does-not-exist': [HTTPStatus.NOT_FOUND], '/does-not-exist-2': [HTTPStatus.NOT_FOUND], '/404': [HTTPStatus.NOT_FOUND], '/redirect-later': [HTTPStatus.FOUND], '/redirect-self': [HTTPStatus.FOUND], '/redirect-to': [HTTPStatus.FOUND], '/relative-redirect': [HTTPStatus.FOUND], '/absolute-redirect': [HTTPStatus.FOUND], '/cookies/set': [HTTPStatus.FOUND], '/500-inline': [HTTPStatus.INTERNAL_SERVER_ERROR], '/500': [HTTPStatus.INTERNAL_SERVER_ERROR], } for i in range(15): path_to_statuses['/redirect/{}'.format(i)] = [HTTPStatus.FOUND] for suffix in ['', '1', '2', '3', '4', '5', '6']: key = ('/basic-auth/user{suffix}/password{suffix}' .format(suffix=suffix)) path_to_statuses[key] = [HTTPStatus.UNAUTHORIZED, HTTPStatus.OK] default_statuses = [HTTPStatus.OK, HTTPStatus.NOT_MODIFIED] sanitized = QUrl('http://localhost' + self.path).path() # Remove ?foo expected_statuses = path_to_statuses.get(sanitized, default_statuses) if self.status not in expected_statuses: raise AssertionError( "{} loaded with status {} but expected {}".format( sanitized, self.status, ' / '.join(repr(e) for e in expected_statuses)))
Example #17
Source File: test_table_badge_api.py From amundsenmetadatalibrary with Apache License 2.0 | 5 votes |
def test_badge_on_unreserved_badge_value(self) -> None: self.app.config['WHITELIST_BADGES'] = [BADGE_NAME] response = self.app.test_client().put(f'/table/{TABLE_NAME}/tag/{TAG_NAME}?tag_type=badge') self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)
Example #18
Source File: test_patched_startup.py From asgard-api with MIT License | 5 votes |
def test_patched_startup_app_without_routes(self): app = App() app._on_startup.clear() app._on_startup.append(patched_startup) client = ClientSession() await app.startup() resp = await client.get( f"http://{settings.HTTP_HOST}:{settings.HTTP_PORT}/new-path", headers={"Origin": "server.com"}, ) self.assertEqual(HTTPStatus.NOT_FOUND, resp.status) self.assertFalse("Access-Control-Allow-Origin" in resp.headers) await app.shutdown()
Example #19
Source File: test_apps.py From asgard-api with MIT License | 5 votes |
def tearDown(self): await super(AppStatsTest, self).tearDown() await self.esclient.indices.delete( index=self.INDEX_NAME, ignore=[HTTPStatus.BAD_REQUEST, HTTPStatus.NOT_FOUND], )
Example #20
Source File: accounts.py From asgard-api with MIT License | 5 votes |
def remove_user_from_account(user_id: str, account_id: str): account = await AccountsService.get_account_by_id( int(account_id), AccountsBackend() ) status_code = HTTPStatus.OK if account else HTTPStatus.NOT_FOUND user = await UsersService.get_user_by_id(int(user_id), UsersBackend()) if account and user: await AccountsService.remove_user_from_account( user, account, AccountsBackend() ) return web.json_response(AccountUsersResource().dict(), status=status_code)
Example #21
Source File: decorators.py From flask-unchained with MIT License | 5 votes |
def patch_loader(*decorator_args, serializer): """ Decorator to automatically load and (partially) update a model from json request data :param serializer: The ModelSerializer to use to load data from the request """ def wrapped(fn): @wraps(fn) def decorated(*args, **kwargs): errors = {} try: data = serializer.load(request.get_json(), instance=kwargs.pop('instance'), partial=True) except ValidationError as e: errors = e.normalized_messages() data = e.valid_data if not errors and not data.id: abort(HTTPStatus.NOT_FOUND) return fn(data, errors) return decorated if decorator_args and callable(decorator_args[0]): return wrapped(decorator_args[0]) return wrapped
Example #22
Source File: users.py From asgard-api with MIT License | 5 votes |
def delete_user(user_id: str): user = await UsersService.get_user_by_id(int(user_id), UsersBackend()) status_code = HTTPStatus.OK if user else HTTPStatus.NOT_FOUND if user: await UsersService.delete_user(user, UsersBackend()) return web.json_response( UserResource(user=user).dict(), status=status_code ) return web.json_response(UserResource().dict(), status=status_code)
Example #23
Source File: test_column_description_api.py From amundsenmetadatalibrary with Apache License 2.0 | 5 votes |
def test_should_fail_to_update_column_description_when_table_does_not_exist(self) -> None: self.mock_proxy.put_column_description.side_effect = NotFoundException(message="table does not exist") response = self.app.test_client().put(f'/table/{TABLE_NAME}/column/{COLUMN_NAME}/description', json={"description": DESCRIPTION}) self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)
Example #24
Source File: test_column_description_api.py From amundsenmetadatalibrary with Apache License 2.0 | 5 votes |
def test_should_fail_to_get_column_description_when_table_is_not_found(self) -> None: self.mock_proxy.get_column_description.side_effect = NotFoundException(message="table does not exist") response = self.app.test_client().get(f'/table/{TABLE_NAME}/column/{COLUMN_NAME}/description') self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)
Example #25
Source File: test_table_detail_api.py From amundsenmetadatalibrary with Apache License 2.0 | 5 votes |
def test_should_fail_to_get_column_details_when_table_not_foubd(self) -> None: self.mock_proxy.get_table.side_effect = NotFoundException(message='table not found') response = self.app.test_client().get(f'/table/{TABLE_URI}') self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)
Example #26
Source File: test_dashboard_tag_api.py From amundsenmetadatalibrary with Apache License 2.0 | 5 votes |
def test_should_fail_to_delete_tag_when_table_not_found(self) -> None: self.mock_proxy.delete_tag.side_effect = NotFoundException(message='foo') response = self.app.test_client().delete(f'/dashboard/{ID}/tag/{TAG}') self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)
Example #27
Source File: test_table_tag_api.py From amundsenmetadatalibrary with Apache License 2.0 | 5 votes |
def test_should_fail_to_delete_tag_when_table_not_found(self) -> None: self.mock_proxy.delete_tag.side_effect = NotFoundException(message='cannot find table') response = self.app.test_client().delete(f'/table/{TABLE_URI}/tag/{TAG}') self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)
Example #28
Source File: test_table_description_api.py From amundsenmetadatalibrary with Apache License 2.0 | 5 votes |
def test_should_fail_to_update_description_when_table_not_found(self) -> None: self.mock_proxy.put_table_description.side_effect = NotFoundException(message='cannot find table') response = self.app.test_client().put(f'/table/{TABLE_URI}/description', json={'description': DESCRIPTION}) self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)
Example #29
Source File: test_table_description_api.py From amundsenmetadatalibrary with Apache License 2.0 | 5 votes |
def test_should_fail_when_cannot_find_table(self) -> None: self.mock_proxy.get_table_description.side_effect = NotFoundException(message='cannot find table') response = self.app.test_client().get(f'/table/{TABLE_URI}/description') self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND)
Example #30
Source File: test_tag_common.py From amundsenmetadatalibrary with Apache License 2.0 | 5 votes |
def test_badge_on_unreserved_badge_value(self) -> None: self.app.config['WHITELIST_BADGES'] = [BADGE_NAME] mock_proxy = MagicMock() tag_common = TagCommon(client=mock_proxy) response = tag_common.put(id='', resource_type=ResourceType.Dashboard, tag=TAG_NAME, tag_type='badge') self.assertEqual(response[1], HTTPStatus.NOT_FOUND)