Python falcon.HTTPNotFound() Examples
The following are 30
code examples of falcon.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
falcon
, or try the search function
.
Example #1
Source File: alarm_definitions.py From monasca-api with Apache License 2.0 | 6 votes |
def _alarm_definition_delete(self, tenant_id, id): sub_alarm_definition_rows = ( self._alarm_definitions_repo.get_sub_alarm_definitions(id)) alarm_metric_rows = self._alarm_definitions_repo.get_alarm_metrics( tenant_id, id) sub_alarm_rows = self._alarm_definitions_repo.get_sub_alarms( tenant_id, id) if not self._alarm_definitions_repo.delete_alarm_definition( tenant_id, id): raise falcon.HTTPNotFound self._send_alarm_definition_deleted_event(id, sub_alarm_definition_rows) self._send_alarm_event(u'alarm-deleted', tenant_id, id, alarm_metric_rows, sub_alarm_rows, None, None)
Example #2
Source File: schedule.py From oncall with BSD 2-Clause "Simplified" License | 6 votes |
def on_delete(req, resp, schedule_id): """ Delete a schedule by id. Only allowed for team admins. **Example request:** .. sourcecode:: http DELETE /api/v0/schedules/1234 HTTP/1.1 :statuscode 200: Successful delete :statuscode 404: Schedule not found """ connection = db.connect() cursor = connection.cursor() verify_auth(req, schedule_id, connection, cursor) cursor.execute('DELETE FROM `schedule` WHERE `id`=%s', int(schedule_id)) deleted = cursor.rowcount connection.commit() cursor.close() connection.close() if deleted == 0: raise HTTPNotFound()
Example #3
Source File: request.py From certidude with MIT License | 6 votes |
def on_post(self, req, resp, cn): """ Sign a certificate signing request """ try: cert, buf = self.authority.sign(cn, profile=config.PROFILES[req.get_param("profile", default="rw")], overwrite=True, signer=req.context.get("user").name) # Mailing and long poll publishing implemented in the function above except EnvironmentError: # no such CSR raise falcon.HTTPNotFound() resp.body = "Certificate successfully signed" resp.status = falcon.HTTP_201 resp.location = os.path.join(req.relative_uri, "..", "..", "signed", cn) logger.info("Signing request %s signed by %s from %s", cn, req.context.get("user"), req.context.get("remote_addr"))
Example #4
Source File: public_ical.py From oncall with BSD 2-Clause "Simplified" License | 6 votes |
def on_get(req, resp, key): """Get ical file for a user or team's oncall calendar with no contact information. Key can be requested at /api/v0/ical_key. """ roles = req.get_param_as_list('roles') name_and_type = get_name_and_type_from_key(key) if name_and_type is None: raise HTTPNotFound() name, type = name_and_type start = int(time.time()) events = [] if type == 'user': events = get_user_events(name, start, roles=roles) elif type == 'team': events = get_team_events(name, start, roles=roles, include_subscribed=True) resp.body = ical.events_to_ical(events, name, contact=False) resp.set_header('Content-Type', 'text/calendar')
Example #5
Source File: ical_key_team.py From oncall with BSD 2-Clause "Simplified" License | 6 votes |
def on_get(req, resp, team): """Get the secret key that grants public access to team's oncall calendar for the logged-in user. **Example request:** .. sourcecode:: http GET /api/v0/ical_key/team/jteam HTTP/1.1 Content-Type: text/plain ef895425-5f49-11ea-8eee-10e7c6352aff """ challenger = req.context['user'] key = get_ical_key(challenger, team, 'team') if key is None: raise HTTPNotFound() resp.body = key resp.set_header('Content-Type', 'text/plain')
Example #6
Source File: service.py From oncall with BSD 2-Clause "Simplified" License | 6 votes |
def on_delete(req, resp, service): """ Delete a service. Currently unused/debug only. """ connection = db.connect() cursor = connection.cursor() # FIXME: also delete team service mappings? cursor.execute('DELETE FROM `service` WHERE `name`=%s', service) deleted = cursor.rowcount connection.commit() cursor.close() connection.close() if deleted == 0: raise HTTPNotFound()
Example #7
Source File: app.py From iris-relay with BSD 2-Clause "Simplified" License | 6 votes |
def on_get(self, req, resp): if not self.healthcheck_path: logger.error('Healthcheck path not set') raise falcon.HTTPNotFound() try: with open(self.healthcheck_path) as f: health = f.readline().strip() except IOError: raise falcon.HTTPNotFound() try: connection = db.connect() cursor = connection.cursor() cursor.execute('SELECT version()') cursor.close() connection.close() except Exception: resp.status = HTTP_503 resp.content_type = 'text/plain' resp.body = 'Could not connect to database' else: resp.status = HTTP_200 resp.content_type = 'text/plain' resp.body = health
Example #8
Source File: db.py From iris with BSD 2-Clause "Simplified" License | 6 votes |
def guarded_session(): ''' Context manager that will automatically close session on exceptions ''' try: session = Session() yield session except IrisValidationException as e: session.close() raise HTTPBadRequest('Validation error', str(e)) except (HTTPForbidden, HTTPUnauthorized, HTTPNotFound, HTTPBadRequest): session.close() raise except Exception: session.close() logger.exception('SERVER ERROR') raise
Example #9
Source File: team_subscription.py From oncall with BSD 2-Clause "Simplified" License | 6 votes |
def on_delete(req, resp, team, subscription, role): check_team_auth(team, req) connection = db.connect() cursor = connection.cursor() cursor.execute('''DELETE FROM `team_subscription` WHERE team_id = (SELECT `id` FROM `team` WHERE `name` = %s) AND `subscription_id` = (SELECT `id` FROM `team` WHERE `name` = %s)\ AND `role_id` = (SELECT `id` FROM `role` WHERE `name` = %s)''', (team, subscription, role)) deleted = cursor.rowcount connection.commit() cursor.close() connection.close() if deleted == 0: raise HTTPNotFound()
Example #10
Source File: user_pinned_team.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def on_delete(req, resp, user_name, team_name): ''' Delete a pinned team **Example request:** .. sourcecode:: http DELETE /api/v0/users/jdoe/pinned_teams/team-foo HTTP/1.1 :statuscode 200: Successful delete :statuscode 403: Delete not allowed; logged in user does not match user_name :statuscode 404: Team not found in user's pinned teams ''' check_user_auth(user_name, req) connection = db.connect() cursor = connection.cursor() cursor.execute('''DELETE FROM `pinned_team` WHERE `user_id` = (SELECT `id` FROM `user` WHERE `name` = %s) AND `team_id` = (SELECT `id` FROM `team` WHERE `name` = %s)''', (user_name, team_name)) deleted = cursor.rowcount connection.commit() cursor.close() connection.close() if deleted == 0: raise HTTPNotFound()
Example #11
Source File: firewall.py From certidude with MIT License | 5 votes |
def whitelist_subject(func): def wrapped(self, req, resp, cn, *args, **kwargs): from ipaddress import ip_address from certidude import authority from xattr import getxattr try: path, buf, cert, signed, expires = authority.get_signed(cn) except IOError: raise falcon.HTTPNotFound() else: # First attempt to authenticate client with certificate buf = req.get_header("X-SSL-CERT") if buf: header, _, der_bytes = pem.unarmor(buf.replace("\t", "").encode("ascii")) origin_cert = x509.Certificate.load(der_bytes) if origin_cert.native == cert.native: logger.debug("Subject authenticated using certificates") return func(self, req, resp, cn, *args, **kwargs) # For backwards compatibility check source IP address # TODO: make it disableable try: inner_address = getxattr(path, "user.lease.inner_address").decode("ascii") except IOError: raise falcon.HTTPForbidden("Forbidden", "Remote address %s not whitelisted" % req.context.get("remote_addr")) else: if req.context.get("remote_addr") != ip_address(inner_address): raise falcon.HTTPForbidden("Forbidden", "Remote address %s mismatch" % req.context.get("remote_addr")) else: return func(self, req, resp, cn, *args, **kwargs) return wrapped
Example #12
Source File: ical_key_user.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def on_get(req, resp, user_name): """Get the secret key that grants public access to user_name's oncall calendar for the logged-in user. Current policy only allows the logged-in user to get its own key, so user_name parameter must be the same as the logged-in user. **Example request:** .. sourcecode:: http GET /api/v0/ical_key/user/jdoe HTTP/1.1 Content-Type: text/plain ef895425-5f49-11ea-8eee-10e7c6352aff """ challenger = req.context['user'] if challenger != user_name: raise HTTPForbidden( 'Unauthorized', 'Action not allowed: "%s" is not allowed to view ical_key of "%s"' % (challenger, user_name) ) key = get_ical_key(challenger, user_name, 'user') if key is None: raise HTTPNotFound() resp.body = key resp.set_header('Content-Type', 'text/plain')
Example #13
Source File: user_teams.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def on_get(req, resp, user_name): """ Get active teams by user name. Note that this does not return any deleted teams that this user is a member of. **Example request**: .. sourcecode:: http GET /api/v0/users/jdoe/teams HTTP/1.1 Host: example.com **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json [ "team-foo", "team-bar" ] """ connection = db.connect() cursor = connection.cursor() cursor.execute('SELECT `id` FROM `user` WHERE `name` = %s', user_name) if cursor.rowcount < 1: raise HTTPNotFound() user_id = cursor.fetchone()[0] cursor.execute('''SELECT `team`.`name` FROM `team` JOIN `team_user` ON `team_user`.`team_id` = `team`.`id` WHERE `team_user`.`user_id` = %s AND `team`.`active` = TRUE''', user_id) data = [r[0] for r in cursor] cursor.close() connection.close() resp.body = dumps(data)
Example #14
Source File: role.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def on_delete(req, resp, role): connection = db.connect() cursor = connection.cursor() # TODO: also remove any schedule and event that references the role? cursor.execute('DELETE FROM `role` WHERE `name`=%s', role) deleted = cursor.rowcount connection.commit() cursor.close() connection.close() if deleted == 0: raise HTTPNotFound()
Example #15
Source File: ical_key_detail.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def on_get(req, resp, key): challenger = req.context['user'] if not (check_ical_key_requester(key, challenger) or check_ical_key_admin(challenger)): raise HTTPForbidden( 'Unauthorized', 'Action not allowed: "%s" is not an admin of ical_key' % (challenger, ), ) results = get_ical_key_detail(key) if not results: raise HTTPNotFound() resp.body = json_dumps(results) resp.set_header('Content-Type', 'application/json')
Example #16
Source File: populate.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def on_post(req, resp, schedule_id): """ Run the scheduler on demand from a given point in time. Deletes existing schedule events if applicable. Given the ``start`` param, this will find the first schedule start time after ``start``, then populate out to the schedule's auto_populate_threshold. It will also clear the calendar of any events associated with the chosen schedule from the start of the first event it created onward. For example, if `start` is Monday, May 1 and the chosen schedule starts on Wednesday, this will create events starting from Wednesday, May 3, and delete any events that start after May 3 that are associated with the schedule. **Example request:** .. sourcecode:: http POST api/v0/ HTTP/1.1 Content-Type: application/json :statuscode 200: Successful populate :statuscode 400: Validation checks failed """ # TODO: add images to docstring because it doesn't make sense data = load_json_body(req) start_time = data['start'] connection = db.connect() cursor = connection.cursor(db.DictCursor) cursor.execute('''SELECT `scheduler`.`name` FROM `schedule` JOIN `scheduler` ON `schedule`.`scheduler_id` = `scheduler`.`id` WHERE `schedule`.`id` = %s''', schedule_id) if cursor.rowcount == 0: raise HTTPNotFound() scheduler_name = cursor.fetchone()['name'] scheduler = load_scheduler(scheduler_name) schedule = get_schedules({'id': schedule_id})[0] check_team_auth(schedule['team'], req) scheduler.populate(schedule, start_time, (connection, cursor)) cursor.close() connection.close()
Example #17
Source File: team_service.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def on_delete(req, resp, team, service): """ Delete service team mapping. Only allowed for team admins. **Example request:** .. sourcecode:: http DELETE /api/v0/teams/team-foo/services/service-foo HTTP/1.1 :statuscode 200: Successful delete :statuscode 404: Team-service mapping not found """ team = unquote(team) check_team_auth(team, req) connection = db.connect() cursor = connection.cursor() cursor.execute('''DELETE FROM `team_service` WHERE `team_id`=(SELECT `id` FROM `team` WHERE `name`=%s) AND `service_id`=(SELECT `id` FROM `service` WHERE `name`=%s)''', (team, service)) deleted = cursor.rowcount if deleted == 0: raise HTTPNotFound() connection.commit() cursor.close() connection.close()
Example #18
Source File: team_user.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def on_delete(req, resp, team, user): """ Delete user from a team **Example request:** .. sourcecode:: http DELETE /api/v0/teams/team-foo/users/jdoe HTTP/1.1 :statuscode 200: Successful delete :statuscode 404: User not found in team """ team = unquote(team) check_team_auth(team, req) connection = db.connect() cursor = connection.cursor() cursor.execute('''DELETE FROM `team_user` WHERE `team_id`=(SELECT `id` FROM `team` WHERE `name`=%s) AND `user_id`=(SELECT `id` FROM `user` WHERE `name`=%s)''', (team, user)) deleted = cursor.rowcount if deleted == 0: raise HTTPNotFound() connection.commit() cursor.close() connection.close()
Example #19
Source File: ical_key_requester.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def on_get(req, resp, requester): challenger = req.context['user'] if not (challenger == requester or check_ical_key_admin(challenger)): raise HTTPForbidden( 'Unauthorized', 'Action not allowed: "%s" is not allowed to view ical_keys of "%s"' % (challenger, requester), ) results = get_ical_key_detail_by_requester(requester) if not results: raise HTTPNotFound() resp.body = json_dumps(results) resp.set_header('Content-Type', 'application/json')
Example #20
Source File: login.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def on_post(req, resp): login_info = uri.parse_query_string(req.context['body'].decode('utf-8')) user = login_info.get('username') password = login_info.get('password') if user is None or password is None: raise HTTPBadRequest('Invalid login attempt', 'Missing user/password') if not auth_manager.authenticate(user, password): raise HTTPUnauthorized('Authentication failure', 'bad login credentials', '') connection = db.connect() cursor = connection.cursor(db.DictCursor) data = get_user_data(None, {'name': user}, dbinfo=(connection, cursor)) if not data: cursor.close() connection.close() raise HTTPNotFound() session = req.env['beaker.session'] session['user'] = user session.save() csrf_token = '%x' % SystemRandom().getrandbits(128) try: cursor.execute('INSERT INTO `session` (`id`, `csrf_token`) VALUES (%s, %s)', (req.env['beaker.session']['_id'], csrf_token)) except db.IntegrityError: raise HTTPBadRequest('Invalid login attempt', 'User already logged in') connection.commit() cursor.close() connection.close() # TODO: purge out of date csrf token data[0]['csrf_token'] = csrf_token resp.body = dumps(data[0])
Example #21
Source File: __init__.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def on_get(self, req, resp, filename): suffix = path.splitext(req.path)[1] resp.content_type = mimes.get(suffix, 'application/octet-stream') filepath = path.join(STATIC_ROOT, self.path, secure_filename(filename)) try: resp.stream = open(filepath, 'rb') resp.stream_len = path.getsize(filepath) except IOError: raise HTTPNotFound()
Example #22
Source File: healthcheck.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def on_get(self, req, resp): if self.dummy_status: status = self.dummy_status else: try: with open(self.path) as f: status = f.readline().strip() except: raise HTTPNotFound() resp.content_type = 'text/plain' resp.body = status
Example #23
Source File: resources.py From falcon-swagger-ui with MIT License | 5 votes |
def __call__(self, req, resp, filepath): resp.content_type = mimetypes.guess_type(filepath)[0] curr_dir = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join( os.path.join(curr_dir, self.static_path), filepath ) if not os.path.exists(file_path): raise falcon.HTTPNotFound() else: stream = open(file_path, 'rb') stream_len = os.path.getsize(file_path) resp.set_stream(stream, stream_len)
Example #24
Source File: resource.py From monasca-api with Apache License 2.0 | 5 votes |
def resource_try_catch_block(fun): def try_it(*args, **kwargs): try: return fun(*args, **kwargs) except falcon.HTTPError: raise except exceptions.DoesNotExistException: raise falcon.HTTPNotFound except exceptions.MultipleMetricsException as ex: raise falcon.HTTPConflict("MultipleMetrics", str(ex)) except exceptions.AlreadyExistsException as ex: raise falcon.HTTPConflict(ex.__class__.__name__, str(ex)) except exceptions.InvalidUpdateException as ex: raise HTTPUnprocessableEntityError(ex.__class__.__name__, str(ex)) except exceptions.RepositoryException as ex: LOG.exception(ex) msg = " ".join(map(str, ex.args[0].args)) raise falcon.HTTPInternalServerError('The repository was unable ' 'to process your request', msg) except Exception as ex: LOG.exception(ex) raise falcon.HTTPInternalServerError('Service unavailable', str(ex)) return try_it
Example #25
Source File: team_admin.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def on_delete(req, resp, team, user): """ Delete team admin user. Removes admin from the team if he/she is not a member of any roster. **Example request:** .. sourcecode:: http DELETE /api/v0/teams/team-foo/admins/jdoe HTTP/1.1 :statuscode 200: Successful delete :statuscode 404: Team admin not found """ check_team_auth(team, req) connection = db.connect() cursor = connection.cursor() cursor.execute('''DELETE FROM `team_admin` WHERE `team_id`=(SELECT `id` FROM `team` WHERE `name`=%s) AND `user_id`=(SELECT `id` FROM `user` WHERE `name`=%s)''', (team, user)) deleted = cursor.rowcount if deleted == 0: raise HTTPNotFound() create_audit({'user': user}, team, ADMIN_DELETED, req, cursor) # Remove user from the team if needed query = '''DELETE FROM `team_user` WHERE `user_id` = (SELECT `id` FROM `user` WHERE `name`=%s) AND `user_id` NOT IN (SELECT `roster_user`.`user_id` FROM `roster_user` JOIN `roster` ON `roster`.`id` = `roster_user`.`roster_id` WHERE team_id = (SELECT `id` FROM `team` WHERE `name`=%s) UNION (SELECT `user_id` FROM `team_admin` WHERE `team_id` = (SELECT `id` FROM `team` WHERE `name`=%s))) AND `team_user`.`team_id` = (SELECT `id` FROM `team` WHERE `name` = %s)''' cursor.execute(query, (user, team, team, team)) if cursor.rowcount != 0: unsubscribe_notifications(team, user, cursor) connection.commit() cursor.close() connection.close()
Example #26
Source File: schedule.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
def verify_auth(req, schedule_id, connection, cursor): team_query = ('SELECT `team`.`name` FROM `schedule` JOIN `team` ' 'ON `schedule`.`team_id` = `team`.`id` WHERE `schedule`.`id` = %s') cursor.execute(team_query, schedule_id) if cursor.rowcount == 0: cursor.close() connection.close() raise HTTPNotFound() try: check_team_auth(cursor.fetchone()[0], req) except HTTPForbidden: cursor.close() connection.close() raise
Example #27
Source File: __init__.py From iris with BSD 2-Clause "Simplified" License | 5 votes |
def on_get(self, req, resp, filename): suffix = os.path.splitext(req.path)[1] resp.content_type = mimes.get(suffix, 'application/octet-stream') filepath = os.path.join(ui_root, self.path, secure_filename(filename)) try: resp.stream = open(filepath, 'rb') resp.stream_len = os.path.getsize(filepath) except IOError: raise HTTPNotFound()
Example #28
Source File: request.py From certidude with MIT License | 5 votes |
def on_get(self, req, resp, cn): """ Fetch certificate signing request as PEM """ try: path, buf, _, submitted = self.authority.get_request(cn) except errors.RequestDoesNotExist: logger.warning("Failed to serve non-existant request %s to %s", cn, req.context.get("remote_addr")) raise falcon.HTTPNotFound() resp.set_header("Content-Type", "application/pkcs10") logger.debug("Signing request %s was downloaded by %s", cn, req.context.get("remote_addr")) preferred_type = req.client_prefers(("application/json", "application/x-pem-file")) if preferred_type == "application/x-pem-file": # For certidude client, curl scripts etc resp.set_header("Content-Type", "application/x-pem-file") resp.set_header("Content-Disposition", ("attachment; filename=%s.pem" % cn)) resp.body = buf elif preferred_type == "application/json": # For web interface events resp.set_header("Content-Type", "application/json") resp.set_header("Content-Disposition", ("attachment; filename=%s.json" % cn)) resp.body = json.dumps(dict( submitted = submitted, common_name = cn, address = getxattr(path, "user.request.address").decode("ascii"), # TODO: move to authority.py md5sum = hashlib.md5(buf).hexdigest(), sha1sum = hashlib.sha1(buf).hexdigest(), sha256sum = hashlib.sha256(buf).hexdigest(), sha512sum = hashlib.sha512(buf).hexdigest()), cls=MyEncoder) else: raise falcon.HTTPUnsupportedMediaType( "Client did not accept application/json or application/x-pem-file")
Example #29
Source File: lease.py From certidude with MIT License | 5 votes |
def on_get(self, req, resp, cn): try: path, buf, cert, signed, expires = self.authority.get_signed(cn) return dict( last_seen = xattr.getxattr(path, "user.lease.last_seen").decode("ascii"), inner_address = xattr.getxattr(path, "user.lease.inner_address").decode("ascii"), outer_address = xattr.getxattr(path, "user.lease.outer_address").decode("ascii") ) except EnvironmentError: # Certificate or attribute not found raise falcon.HTTPNotFound()
Example #30
Source File: revoked.py From certidude with MIT License | 5 votes |
def on_get(self, req, resp, serial_number): try: path, buf, cert, signed, expires, revoked, reason = self.authority.get_revoked(serial_number) except EnvironmentError: logger.warning("Failed to serve non-existant revoked certificate with serial %s to %s", serial_number, req.context.get("remote_addr")) raise falcon.HTTPNotFound() resp.set_header("Content-Type", "application/x-pem-file") resp.set_header("Content-Disposition", ("attachment; filename=%x.pem" % cert.serial_number)) resp.body = buf logger.debug("Served revoked certificate with serial %s to %s", serial_number, req.context.get("remote_addr"))