def on_get(self, req, resp): # Used to retrieve the overrides for a given discord_guild_id try: # The discord_guild_id is required discord_guild_id = req.get_header('discord-guild-id') if discord_guild_id is None: raise falcon.HTTPBadRequest( 'Missing Requried Headers', 'Required header(s): discord-guild-id') # Retrieve the limits for both Twitch and YouTube twitch_notification_limit = notification_limit().get_twitch_limit( discord_guild_id) youtube_notification_limit = notification_limit( ).get_youtube_limit(discord_guild_id) body = { "twitch": twitch_notification_limit, "youtube": youtube_notification_limit } resp.status = falcon.get_http_status(200) resp.content_type = ['application/json'] resp.body = json.dumps(body) except Exception as e: resp.status = falcon.get_http_status(503) resp.content_type = ['application/json'] resp.body = json.dumps({ "status": "error", "code": 503, "message": str(e) })
def on_get(self, req, resp): try: # Retrieve twitch_username and discrod_channel_id from headers twitch_username = req.get_header('twitch-username') discord_channel_id = req.get_header('discord-channel-id') discord_guild_id = req.get_header('discord-guild-id') # If twitch_username or discord_channel_id are not set then raise exception if (twitch_username is None or discord_channel_id is None or discord_guild_id is None): raise falcon.HTTPBadRequest( 'Missing Requried Headers', 'Required headers: twitch_username and discord_channel_id') # Using twitch_management class attempt to add new notifiaction message = twitch_management(twitch_username, discord_guild_id, discord_channel_id).delete() resp.status = falcon.get_http_status(message['code']) resp.content_type = ['application/json'] resp.body = json.dumps(message) except falcon.HTTPBadRequest as e: message = { "status": "error", "code": 400, "message": e.description } resp.status = falcon.get_http_status(message['code']) resp.content_type = ['application/json'] resp.body = json.dumps(message) except Exception as e: get_logger().error(e, exc_info=True)
def on_get(self, req, resp): try: # Retrieve the Discord channel ID and the YouTube channel URL from the headers disc_guild_id = req.get_header('discord_guild_id') disc_channel_id = req.get_header('discord-channel-id') yt_channel_url = req.get_header('youtube-channel-url') # If either of the two required headers are missing, return bad request if(disc_channel_id == None or yt_channel_url == None): raise falcon.HTTPBadRequest('Missing Requried Headers', 'Required headers: discord-channel-id and youtube-channel-url') # Using the youtube_management class add the subscription to the database message = youtube_management().unsubscribe(yt_channel_url, disc_channel_id) resp.status = falcon.get_http_status(message['code']) resp.content_type = ['application/json'] resp.body = json.dumps(message) except falcon.HTTPBadRequest as e: message = {"status":"error", "code":400, "message":e.description} resp.status = falcon.get_http_status(message['code']) resp.content_type = ['application/json'] resp.body = json.dumps(message) except Exception as e: get_logger().error(e, exc_info=True)
def on_put(self, req, resp): # Used to create/update an override # Get header values discord_guild_id = req.get_header('discord-guild-id') platform = str(req.get_header('platform')).lower() override = int(req.get_header('override')) # Check if header values exist if discord_guild_id is None or platform is None or override is None: raise falcon.HTTPBadRequest( 'Missing Requried Headers', 'Required header(s): discord-guild-id, platform, override') # Check if platform value is valid if platform not in ['twitch', 'youtube']: raise falcon.HTTPBadRequest( 'Invalid Platform Header', 'Accepted platform values: twitch, youtube') # Set the override value for the corresponding platform if (platform == "twitch"): status = notification_limit().set_twitch_limit_override( discord_guild_id, override) elif (platform == "youtube"): status = notification_limit().set_youtube_limit_override( discord_guild_id, override) # Set the content type resp.content_type = ['application/json'] if (status): # Notification limit override update was successful. resp.status = falcon.get_http_status(200) resp.body = json.dumps({ "status": "success", "code": 200, "message": "Override successfully updated." }) else: # Notification limit override update failed. resp.status = falcon.get_http_status(503) resp.body = json.dumps({ "status": "error", "code": 503, "message": "Failed to update override." })
def on_get(self, req, res, category_sub_code=None, due_code=None): res.status = falcon.get_http_status(status_code=200) response = requests.request( "GET", "http://www.mocky.io/v2/5e7beacf2d0000979811aa3e") print("Recebido GET em {}".format(datetime.utcnow().isoformat())) response = json.loads(response.text) res.body = json.dumps(response)
def generate_response(res: Response, status_code: int, body_dict: dict, headers: List[Dict] = []) -> NoReturn: res.status = get_http_status(status_code=status_code) res.media = body_dict res.set_headers(headers=headers)
def on_get(self, req, res): self.logger.info(f'Start Report: GET') res.status = falcon.get_http_status(status_code=200) try: # response = requests.get('http://www.mocky.io/v2/5ea8c3162d0000644f3a40f0') response = [] except HTTPError as http_err: self.logger.error(f'HTTP error occurred: {http_err}') except Exception as err: self.logger.error(f'Other error occurred: {err}') # scr_call = response.json() scr_call = self._mock() full_report = {} a_vencer = {} for operation_item in scr_call.get('operation_items'): due_code = str(operation_item['due_type']['due_code']) category_code = str( operation_item['category_sub']['category']['category_code']) category_sub_code = str( operation_item['category_sub']['category_sub_code']) index = f'{category_code}:{category_sub_code}:{due_code}' if not full_report.get(index): full_report[index] = operation_item.get('due_value') else: full_report[index] += operation_item.get('due_value') description = str(operation_item['due_type']['description']) category_description = str(operation_item['category_sub'] ['category']['category_description']) if not a_vencer.get(description): if operation_item.get('due_value'): a_vencer[description] = {} a_vencer[description]['total'] = operation_item.get( 'due_value') a_vencer[description][ category_description] = operation_item.get('due_value') else: if operation_item.get('due_value'): a_vencer[description]['total'] += operation_item.get( 'due_value') if not a_vencer[description].get(category_description): a_vencer[description][ category_description] = operation_item.get( 'due_value') else: a_vencer[description][ category_description] += operation_item.get( 'due_value') res.body = json.dumps({ 'relatório visual': a_vencer, 'relatório maquina': full_report }) self.logger.info(f'End Report.')
def on_put(self, req, resp): try: yt_management = youtube_management() yt_management.update_display_names() yt_management.update_webhook_subs() resp.status = falcon.get_http_status(200) resp.content_type = ['application/json'] resp.body = json.dumps({"status": "success", "code": 200}) except Exception as e: get_logger().error(e, exc_info=True) resp.status = falcon.get_http_status(400) resp.content_type = ['application/json'] resp.body = json.dumps({"status": "error", "code": 400})
def on_post(self, req, res): body = req.stream.read(req.content_length or 0) body = json.loads(body.decode('utf-8'), parse_float=Decimal) print("Recebido POST em {}".format(datetime.utcnow().isoformat())) res.status = falcon.get_http_status(status_code=200) response_dict = { "company": "qi_tech", "proccess_id": str(os.getpid()), "body": body } res.body = json.dumps(response_dict)
def on_delete(self, req, resp): # Used to delete notifications associated with either a discord_channel_id # or a discord_guild_id try: # Check if discord-channel-id or discord-guild-id is in the headers, else HTTPBadRequest if req.get_header('discord-channel-id') is not None: notifications().delete_by_discord_channel_id( req.get_header('discord-channel-id')) elif req.get_header('discord-guild-id') is not None: notifications().delete_by_discord_guild_id( req.get_header('discord-guild-id')) else: raise falcon.HTTPBadRequest( 'Missing Requried Headers', 'Required header(s): discord-channel-id or discord-guild-id' ) resp.status = falcon.get_http_status(200) resp.content_type = ['application/json'] resp.body = json.dumps({"status": "success", "code": 200}) except falcon.HTTPBadRequest as e: message = { "status": "error", "code": 400, "message": e.description } resp.status = falcon.get_http_status(message['code']) resp.content_type = ['application/json'] resp.body = json.dumps(message) except Exception as e: get_logger().error(e, exc_info=True) message = {"status": "error", "code": 400, "message": 'API ERROR'} resp.status = falcon.get_http_status(message['code']) resp.content_type = ['application/json'] resp.body = json.dumps(message)
def on_get(self, req, res, category_sub_code=None, due_code=None): res.status = falcon.get_http_status(status_code=200) response = requests.request("GET", "http://www.mocky.io/v2/5e7beacf2d0000979811aa3e") print("Limit - Recebido GET em {}".format(datetime.utcnow().isoformat())) response = json.loads(response.text) response["risk_rank"] = operation.risk_rank(response=response) response["operation_items"] = operation.category_code( response=response, category_code=self.category_code, operation_items=self.operation_items ) # busca por código de categoria if category_sub_code and not due_code: # 1 if self.operation_category_sub_code: self.operation_category_sub_code = [] self.operation_items = operation.category_sub_code( response=response, operation_category_sub_code=self.operation_category_sub_code, category_sub_code=str(category_sub_code) ) # busca por código de vencimento if due_code and not category_sub_code: # 20 if self.operation_due_code: self.operation_due_code = [] self.operation_items = operation.due_code( response=response, operation_due_code=self.operation_due_code, due_code=due_code ) # busca por código de categoria e código de vencimento if category_sub_code and due_code: # 1 if self.operation_category_sub_code: self.operation_category_sub_code = [] # 20 if self.operation_due_code: self.operation_due_code = [] self.operation_items = operation.category_sub_code( response=response, operation_category_sub_code=self.operation_category_sub_code, category_sub_code=str(category_sub_code) ) response["operation_items"] = self.operation_items self.operation_items = operation.due_code( response=response, operation_due_code=self.operation_due_code, due_code=due_code ) response["operation_items"] = self.operation_items res.body = json.dumps(response)
def process_response(self, req, resp, resource, req_succeeded): file_upload = {} for key, value in req.params.items(): if type(value) is Parser: file_upload = dict(key=key, filename=value.filename) break req_body = req.media if req.content_length and req.content_type == 'application/json' else {} response = self.route_loader.match_response(req.path, req.method, req_body, req.query_string, file_upload) assert response is not None resp.body = json.dumps(response.get('body', '')) resp.status = falcon.get_http_status(response['status'])
def on_get(self, req, res): self.logger.info(f'Start: GET') res.status = falcon.get_http_status(status_code=200) try: response = requests.get('http://www.mocky.io/v2/5ea8c3162d0000644f3a40f0') except HTTPError as http_err: self.logger.error(f'HTTP error occurred: {http_err}') except Exception as err: self.logger.error(f'Other error occurred: {err}') response_dict = response.json() res.body = json.dumps(response_dict) self.logger.info(f'End.')
def test_get_http_status(self): self.assertEqual(falcon.get_http_status(404), falcon.HTTP_404) self.assertEqual(falcon.get_http_status(404.3), falcon.HTTP_404) self.assertEqual(falcon.get_http_status("404.3"), falcon.HTTP_404) self.assertEqual(falcon.get_http_status(404.9), falcon.HTTP_404) self.assertEqual(falcon.get_http_status("404"), falcon.HTTP_404) self.assertEqual(falcon.get_http_status(123), "123 Unknown") self.assertRaises(ValueError, falcon.get_http_status, "not_a_number") self.assertRaises(ValueError, falcon.get_http_status, 0) self.assertRaises(ValueError, falcon.get_http_status, 99) self.assertRaises(ValueError, falcon.get_http_status, -404.3) self.assertRaises(ValueError, falcon.get_http_status, "-404") self.assertRaises(ValueError, falcon.get_http_status, "-404.3") self.assertEqual(falcon.get_http_status(123, "Go Away"), "123 Go Away")
def test_get_http_status(self): self.assertEqual(falcon.get_http_status(404), falcon.HTTP_404) self.assertEqual(falcon.get_http_status(404.3), falcon.HTTP_404) self.assertEqual(falcon.get_http_status('404.3'), falcon.HTTP_404) self.assertEqual(falcon.get_http_status(404.9), falcon.HTTP_404) self.assertEqual(falcon.get_http_status('404'), falcon.HTTP_404) self.assertEqual(falcon.get_http_status(123), '123 Unknown') self.assertRaises(ValueError, falcon.get_http_status, 'not_a_number') self.assertRaises(ValueError, falcon.get_http_status, 0) self.assertRaises(ValueError, falcon.get_http_status, 99) self.assertRaises(ValueError, falcon.get_http_status, -404.3) self.assertRaises(ValueError, falcon.get_http_status, '-404') self.assertRaises(ValueError, falcon.get_http_status, '-404.3') self.assertEqual(falcon.get_http_status(123, 'Go Away'), '123 Go Away')
def cloud_storage_service(_req, resp): """Send the request through to the cloudstorage microservice""" path = urlparse(_req.uri).path[1:] # determine whether to use amazon s3 or azure blob storage # Use 'az' at beginning of the path to signal that file is from azure # eg. https://domain.com/az/some_file.pdf microservice_url = os.environ.get('CLOUDSTORAGE_URL') # default to s3 if path[0:3] == 'az/': microservice_url = microservice_url.replace('1.0', '2.0', 1) path = path[3:] response = requests.get(microservice_url, params={ 'name': path, 'apikey': os.environ.get('CLOUDSTORAGE_API_KEY') }) resp.status = falcon.get_http_status(response.status_code) resp.content_type = response.headers['Content-Type'] resp.body = response.content
def on_post(self, req, res): res.status = falcon.get_http_status(status_code=200) url = 'http://www.mocky.io/v2/5e5c4f25300000745ef9f35d' r = requests.post(url) r_json = json.loads(r.text) print("Recebido POST em {}".format(datetime.utcnow().isoformat())) response_dict = r_json res.body = json.dumps(response_dict) # return r_json # body = req.stream.read(req.content_length or 0) # body = json.loads(body.decode('utf-8'), parse_float=Decimal) # print("Recebido POST em {}".format(datetime.utcnow().isoformat())) # res.status = falcon.get_http_status(status_code=200) # response_dict = { # "company": "qi_tech", # "proccess_id": str(os.getpid()), # "body": body # } # res.body = json.dumps(response_dict) # http://www.mocky.io/v2/5e5c4f25300000745ef9f35d # retorno json mockado
def handle_sensu_access_denied(exception, response): response.status = get_http_status(500) return {'error': 'Failed to connect to Sensu'}
def on_get(self, req, res): res.status = falcon.get_http_status(status_code=200) print("Recebido GET em {}".format(datetime.utcnow().isoformat())) response_dict = {"company": "qi_tech", "proccess_id": str(os.getpid())} res.body = json.dumps(response_dict)
def test_get_http_status(self): assert falcon.get_http_status(404) == falcon.HTTP_404 assert falcon.get_http_status(404.3) == falcon.HTTP_404 assert falcon.get_http_status('404.3') == falcon.HTTP_404 assert falcon.get_http_status(404.9) == falcon.HTTP_404 assert falcon.get_http_status('404') == falcon.HTTP_404 assert falcon.get_http_status(123) == '123 Unknown' with pytest.raises(ValueError): falcon.get_http_status('not_a_number') with pytest.raises(ValueError): falcon.get_http_status(0) with pytest.raises(ValueError): falcon.get_http_status(0) with pytest.raises(ValueError): falcon.get_http_status(99) with pytest.raises(ValueError): falcon.get_http_status(-404.3) with pytest.raises(ValueError): falcon.get_http_status('-404') with pytest.raises(ValueError): falcon.get_http_status('-404.3') assert falcon.get_http_status(123, 'Go Away') == '123 Go Away'
def test_get_http_status_warns(self): with pytest.warns(UserWarning, match='Please use falcon'): falcon.get_http_status(400)
def get_aggregate_detail(sensu: Sensu, aggregate_name: str, response): status_code, data = sensu.aggregate_detail(aggregate_name) response.status = get_http_status(status_code) return data
def post_request(sensu: Sensu, body, response, request): creator = request.context['user']['username'] status_code, data = sensu.request_check(body['check'], body['subscribers'], creator, body['reason']) response.status = get_http_status(status_code) return data
def post_resolve(sensu: Sensu, body, response): status_code, data = sensu.resolve_event(body['client'], body['check']) response.status = get_http_status(status_code) return data
def delete_result(sensu: Sensu, client_name: str, check_name: str, response): status_code, data = sensu.delete_result(client_name, check_name) response.status = get_http_status(status_code) return data
def post_silenced(sensu: Sensu, body, response): status_code, data = sensu.create_silenced(body) response.status = get_http_status(status_code) return data
def on_get(self, req, resp): try: # Check if discord-channel-id is in headers, if not return HTTPBadRequest discord_channel_id = req.get_header('discord-channel-id') if discord_channel_id is None: raise falcon.HTTPBadRequest( 'Missing Requried Headers', 'Required header(s): discord-channel-id') # Get the parent guild of the discord_channel_id discord_guild_id = discord_management().find_parent_guild( discord_channel_id) # Create object for notifications class, get notification data for twitch and youtube # If no notifications are found, type None will be returned notifications_obj = notifications() # Create object for notification limit class, get notification limit and number of # notifications registered for each platform notification_limit_obj = notification_limit() # Create dict with notification data data = { discord_channel_id: { 'twitch': notifications_obj.get_twitch_notifications( discord_channel_id), 'youtube': notifications_obj.get_youtube_notifications( discord_channel_id), 'limits': { 'twitch': { 'limit': notification_limit_obj.get_twitch_limit( discord_guild_id), 'used': notification_limit_obj. get_twitch_notification_count(discord_guild_id) }, 'youtube': { 'limit': notification_limit_obj.get_youtube_limit( discord_guild_id), 'used': notification_limit_obj. get_youtube_notification_count(discord_guild_id) } } } } # Set http status to 200, set content_type to JSON, and convert the data dict into JSON resp.status = falcon.get_http_status(200) resp.content_type = ['application/json'] resp.body = json.dumps(data) except falcon.HTTPBadRequest as e: message = { "status": "error", "code": 400, "message": e.description } resp.status = falcon.get_http_status(message['code']) resp.content_type = ['application/json'] resp.body = json.dumps(message) except Exception as e: get_logger().error(e, exc_info=True) message = {"status": "error", "code": 400, "message": 'API ERROR'} resp.status = falcon.get_http_status(message['code']) resp.content_type = ['application/json'] resp.body = json.dumps(message)