Example #1
0
def page_not_found(e):
    response = ApiResponse('not_found')
    notifications['errors'] = {
        'type': 'not_found',
        'details': 'Route not found.'
    }

    return response.serialize('json')
Example #2
0
    def log_handler(*args, **kwargs):
        token = request.headers.get('Token')
        if not token:
            return ApiResponse({"Error": "Token not found"}, 400)
        http_method = request.method
        http_url = request.url
        payload = json.dumps(request.get_json())

        token_dec = jwt.decode(token,
                               PUBLIC_KEY,
                               algorithms=['RS256'],
                               audience='dashboard',
                               options={
                                   "verify_signature": False,
                                   "verify_aud": False,
                                   "verify_iat": False,
                                   "verify_exp": False,
                                   "verify_nbf": False,
                                   "verify_iss": False,
                                   "verify_sub": False,
                                   "verify_jti": False,
                                   "verify_at_hash": False
                               })
        user_name = token_dec["name"]
        user_email = token_dec["email"]
        date_start = datetime.datetime.utcnow()
        try:
            response = func(*args, **kwargs)
        except ApiException as err:
            response = err
        except Exception as err:
            response = ApiException('Internal server error', 500, str(err))

        if isinstance(response, ApiResponse):
            response_status_code = response.status
            message = str(response.value or "")[0:250] + "..."
        elif isinstance(response, ApiException):
            message = response.message
            response_status_code = response.status
            response = ApiResponse(message, response_status_code)
        date_end = datetime.datetime.utcnow()
        LogService.create({
            "http_method": http_method,
            "http_url": http_url,
            "payload": payload,
            "user_name": user_name,
            "user_email": user_email,
            "date_start": date_start,
            "response_status_code": response_status_code,
            "message": message,
            "date_end": date_end
        })
        return response
Example #3
0
 def put(self, id: int):
     """
     Actualiza un único Job por ID.
     """
     body = interfaces.single_schema.load(request.json).data
     Job = JobService.update(id, body)
     return ApiResponse(interfaces.single_schema.dump(Job).data)
Example #4
0
 def delete(self, id: int) -> Response:
     """
     Elimina un único Switch por ID.
     """
     from flask import jsonify
     id = SwitchService.delete_by_id(id)
     return ApiResponse(None, 204)
Example #5
0
def display_status():
    """
    Provides status of app and dependencies.
    """
    response = ApiResponse('status')

    response.resource_data = {
        "service_name": "flask-boilerplate",
        "build_date": datetime.utcnow(),
        "version": "1.0.0",
        "SHA": "github sha"
    }

    response.status_code = 200

    return response.serialize('json')
    def delete(self, id: int) -> Response:
        """
        Delete a single Entity
        """
        from flask import jsonify

        id = EntityService.delete_by_id(id)
        return ApiResponse(None, 204)
def test_api_flask_make_response(api, app):
    # should convert the ApiResponse object to a `Response` by calling 
    # its `to_response` method.
    with app.test_request_context('/healthz'):
        api_response = ApiResponse(value={'ok': True}, status=200)
        response = api.make_response(api_response)
        expected = isinstance(response, Response)
        assert expected == True
Example #8
0
 async def get(self, switch_id: int):
     """
     Devuelve la lista de Interfaces obtenidas desde el CISCO PRIME
     """
     try:
         result = await NicsService.get_from_prime_by_switch_id(switch_id)
         return ApiResponse(result)        
     except SwitchNotFound:
         raise ApiException(f'En el Cisco Prime no se encuentra un switch con el id:{switch_id}')
Example #9
0
 def put(self, id: int):
     """
     Actualiza un batch de Switches por su ID.
     """
     json_data = request.get_json()
     sw_updated = []
     for item in json_data:
         sw = interfaces.single_schema.load(request.json).data
         sw_updated.append(SwitchService.update(id, sw))
     return ApiResponse(interfaces.many_schema.dump(sw_updated).data)
Example #10
0
 def post(self):
     """
     Crea un nuevo Job.
     """
     json_data = request.get_json()
     if json_data is None:
         raise ApiException('JSON body is undefined')
     body = interfaces.single_schema.load(json_data).data
     Job = JobService.create(body)
     return ApiResponse(interfaces.single_schema.dump(Job).data)
Example #11
0
 def put(self, id: int):
     """
     Actualiza un único Switch por ID.
     """
     try:
         body = interfaces.single_schema.load(request.json).data
         Switch = SwitchService.update(id, body)
         return ApiResponse(interfaces.single_schema.dump(Switch).data)
     except SwitchNotFound:
         raise ApiException(f'No se encuentra un switch con el id:{id}')
Example #12
0
 async def get(self):
     """
     Devuelve la lista de Switches
     """
     try:
         entities = await SwitchService.get_all()
         return ApiResponse(interfaces.many_schema.dump(entities).data)
     except JobTemplateNotFound:
         raise ApiException(
             'No existe un playbook para obtener la infrmación de las interfaces'
         )
     except PlaybookTimeout:
         raise ApiException(
             'La ejecución de la tarea supero el tiempo del timeout')
     except PlaybookFailure:
         raise ApiException('Fallo la ejecución de la tarea')
Example #13
0
 async def post(self, switch_id: int):
     """
     Resetea la interface indicada
     """
     try:
         nic_name = request.args.get('nic_name')
         result = await NicsService.reset_switch_nic(switch_id, nic_name)
         return ApiResponse(result)
     except SwitchNotFound:
         raise ApiException(f'No se encuentra un switch con el id:{switch_id}')
     except JobTemplateNotFound:
         raise ApiException('No existe un playbook para obtener la infrmación de las interfaces')
     except PlaybookTimeout:
         raise ApiException('La ejecución de la tarea supero el tiempo del timeout')
     except PlaybookFailure:
         raise ApiException('Fallo la ejecución de la tarea')
Example #14
0
 async def get(self, switch_id: int):
     """
     Devuelve la lista de Interfaces
     """
     # List jobs templates
     # '/api/v2/job_templates/'
     try:
         result = await NicsService.get_by_switch_id(switch_id)
         return ApiResponse(result)
         #return ApiResponse(RESULT)
     except SwitchNotFound:
         raise ApiException(f'No se encuentra un switch con el id:{switch_id}')
     except JobTemplateNotFound:
         raise ApiException('No existe un playbook para obtener la información de las interfaces')
     except PlaybookTimeout:
         raise ApiException('La ejecución de la tarea supero el tiempo del timeout')
     except PlaybookFailure:
         raise ApiException('Fallo la ejecución de la tarea')
Example #15
0
 async def get(self, id: int):
     """
     Obtiene un único Switch por ID.
     """
     try:
         switch = await SwitchService.get_by_id(id)
         return ApiResponse(interfaces.single_schema.dump(switch).data)
     except SwitchNotFound:
         raise ApiException(f'No se encuentra un switch con el id:{id}')
     except JobTemplateNotFound:
         raise ApiException(
             'No existe un playbook para obtener la infrmación de las interfaces'
         )
     except PlaybookTimeout:
         raise ApiException(
             'La ejecución de la tarea supero el tiempo del timeout')
     except PlaybookFailure:
         raise ApiException('Fallo la ejecución de la tarea')
Example #16
0
 async def get(self, switch_id: int):
     """
     Devuelve la lista de todaslas macs del switch
     """
     try:
         resp = await MacService.get(switch_id)
         return ApiResponse(resp)
     except SwitchNotFound:
         raise ApiException(
             f'No se encuentra un switch con el id:{switch_id}')
     except JobTemplateNotFound:
         raise ApiException(
             'No existe un playbook para obtener la infrmación de las interfaces'
         )
     except PlaybookTimeout:
         raise ApiException(
             'La ejecución de la tarea supero el tiempo del timeout')
     except PlaybookFailure:
         raise ApiException('Fallo la ejecución de la tarea')
Example #17
0
    def post(self) -> Entity:
        """
        Creates a single Entity

        La primera oración de este `docstring` se coloca como título del `endpoint`.
        Despues se puede incluir todo el detalle a continuación.

        Por defecto, se acepta Markdown para construir estos menajes. Hasta se pueden
        incluir tablas:

        | Columna 1 | Columna 2  | Columna 3|
        |---|---|---|
        | Valor 1 | Valor 2 | Valor 3|
        """
        json_data = request.get_json()
        if json_data is None:
            raise Exception('JSON body is undefined')
        body = interfaces.single_schema.load(json_data).data
        print(json_data)
        entity = EntityService.create(body)
        return ApiResponse(interfaces.single_schema.dump(entity).data)
Example #18
0
 def authorize_handler(*args, **kwargs):
     token = request.headers.get('Token')
     if not token:
         return ApiResponse({"Error": "Token not found"}, 400)
     try:
         jwt.decode(token,
                    PUBLIC_KEY,
                    algorithms=['RS256'],
                    audience='dashboard',
                    options={
                        "leeway": 120,
                        "verify_exp": False
                    })
     except JWTError as error:
         raise ApiException(error)
     except JWTClaimsError as error:
         raise ApiException(error)
     except ExpiredSignatureError as error:
         raise ApiException(error)
     except JWKError as error:
         raise ApiException(error)
     return func(*args, **kwargs)
Example #19
0
 async def get(self):
     """
     Devuelve la lista de Switches
     """
     try:
         entities = await SwitchService.get_all()
         ansible_switches_vars = {}
         for x in entities:
             ansible_switches_vars[x.name] = {
                 "ansible_host": x.ip,
                 "ansible_become": True,
                 "ansible_become_method": "enable",
                 "ansible_connection": "network_cli",
                 "ansible_network_os": "ios",
                 "ansible_port": x.ansible_ssh_port or 22,
                 "ansible_user": decode(x.ansible_user),
                 "ansible_ssh_pass": decode(x.ansible_ssh_pass)
             }
         ansible_switches_hostnames = map(lambda x: x.name, entities)
         sw_inv = {
             'group': {
                 'hosts': list(ansible_switches_hostnames),
             },
             '_meta': {
                 'hostvars': ansible_switches_vars
             }
         }
         return ApiResponse(sw_inv)
     except JobTemplateNotFound:
         raise ApiException(
             'No existe un playbook para obtener la infrmación de las interfaces'
         )
     except PlaybookTimeout:
         raise ApiException(
             'La ejecución de la tarea supero el tiempo del timeout')
     except PlaybookFailure:
         raise ApiException('Fallo la ejecución de la tarea')
def test_api_response_to_response_default_status(app):
    with app.test_request_context('/healthz'):    
        expected = ApiResponse(value=None).to_response()
        assert expected.status == '200 OK'
Example #21
0
 def get(self, id: int) -> Entity:
     """
     Get a single Entity
     """
     entity = EntityService.get_by_id(id)
     return ApiResponse(interfaces.single_schema.dump(entity).data)
Example #22
0
 def put(self, id: int):
     """Update a single Entity"""
     body = interfaces.single_schema.load(request.json).data
     entity = EntityService.update(id, body)
     return ApiResponse(interfaces.single_schema.dump(entity).data)
Example #23
0
 def get(self) -> ApiResponse:
     """
     Returns the list of entities
     """
     entities = EntityService.get_all()
     return ApiResponse(interfaces.many_schema.dump(entities).data)
def test_api_response_to_response_empty_body(app):
    with app.test_request_context('/healthz'): 
        expected = ApiResponse(value=None).to_response()
        assert expected.data == b''
def test_api_response_to_response_value_mimetype(app):
    with app.test_request_context('/healthz'):    
        expected = ApiResponse(value={'ok': True}).to_response()
        assert expected.mimetype == 'application/json'
Example #26
0
 def get(self, id: int):
     """
     Obtiene un único Job por ID.
     """
     Job = JobService.get_by_id(id)
     return ApiResponse(interfaces.single_schema.dump(Job).data)
def test_api_response_to_response_single_value_body(app):
    with app.test_request_context('/healthz'):    
        expected = ApiResponse(value={'ok': True}).to_response()
        assert expected.data == b'{"item": {"ok": true}}'
Example #28
0
 def get(self):
     """
     Devuelve la lista de Jobs
     """
     entities = JobService.get_all()
     return ApiResponse(interfaces.many_schema.dump(entities).data)
def test_api_response_to_response_multiple_value_body(app):
    with app.test_request_context('/healthz'):
        expected = ApiResponse(value=[{'ok': True}, {'ok': False}]).to_response()
        assert expected.data == b'{"count": 2, "current": "http://localhost/healthz?page=1&per_page=3", "items": [{"ok": true}, {"ok": false}], "next": "http://localhost/healthz?page=2&per_page=3"}'
def test_api_response_to_response_returns_a_response_object(app):
    with app.test_request_context('/healthz'):
        expected = ApiResponse(value=None).to_response()
        assert isinstance(expected, Response)