Beispiel #1
0
def create_node():
    # Read and update id integer counter
    node_id = node_table.update_item(
        Key={'node_id': '0'},
        UpdateExpression='ADD current_id :c',
        ExpressionAttributeValues={':c': 1},
        ReturnValues='UPDATED_NEW')['Attributes']['current_id']
    node_id = str(int(node_id))
    try:
        new_node = node_table.update_item(
            Key={'node_id': node_id},
            UpdateExpression=
            'SET shipping_status = :s, config_status = :c, assigned_to = :a',
            ConditionExpression='attribute_not_exists(node_id)',
            ExpressionAttributeValues={
                ':s': 'pending',
                ':c': 'unconfigured',
                ':a': 'None'
            },
            ReturnValues='ALL_NEW')['Attributes']
    # Error handling in case id is already taken
    except ClientError as e:
        error_code = e.response["Error"]["Code"]
        if error_code == 'ConditionalCheckFailedException':
            message = "An error occured while creating the node. Please try again."
            raise ConflictError(message)
    response = {'Item': new_node, 'Message': 'Node created.'}
    return response
Beispiel #2
0
def get_git_id():
    # Only do this on localhost
    if TM_FRONTEND_HOST == "localhost":
        git_id = str(
            subprocess.check_output(
                ['git', 'describe', '--always', '--dirty',
                 '--abbrev=10']))[2:-3]
        return json.dumps({"git_id": git_id})
    else:
        raise ConflictError("Cannot get git id from serverless host")
Beispiel #3
0
def create_user():

    user_id = app.current_request.json_body.get("user")
    if not user_id:
        raise BadRequestError("No user found in the request body")

    try:
        response = create_new_user(user_id)
    except ValueError:
        raise ConflictError("User already exists")

    return Response(body=response, status_code=201)
Beispiel #4
0
def create_user():

    body = app.current_request.json_body

    try:
        user_id = body['user']
    except KeyError:
        raise BadRequestError('No user found in the request body')

    try:
        response = create_new_user(user_id)
    except ValueError:
        raise ConflictError('User already exists')

    return Response(body=response, status_code=201)
Beispiel #5
0
def create_project():
    # Read and update id integer counter
    project_id = project_table.update_item(
        Key={'project_id': '0'},
        UpdateExpression='ADD current_id :c',
        ExpressionAttributeValues={':c': 1},
        ReturnValues='UPDATED_NEW')['Attributes']['current_id']
    project_id = str(int(project_id))
    try:
        new_project = project_table.update_item(
            Key={'project_id': project_id},
            ConditionExpression='attribute_not_exists(project_id)',
            ReturnValues='ALL_NEW')['Attributes']
    # Error handling in case id is already taken
    except ClientError as e:
        error_code = e.response["Error"]["Code"]
        if error_code == 'ConditionalCheckFailedException':
            message = "An error occured while creating the project. Please try again."
            raise ConflictError(message)
    response = {'Item': new_project, 'Message': 'Project created.'}
    return response
def signup():
    """
    Sign up to get Cloudalbum service account
    :return:
    """
    req_data = app.current_request.json_body
    dig = cognito.generate_digest(req_data)
    client = boto3.client('cognito-idp')
    try:
        cognito.signup(client, req_data, dig)
        return Response(status_code=201, body={'ok': True},
                        headers={'Content-Type': 'application/json'})
    except client.exceptions.UsernameExistsException as e:
        raise ConflictError(e.response['Error']['Message'])
    except client.exceptions.InvalidParameterException as e:
        raise BadRequestError(e.response['Error']['Message'])
    except client.exceptions.InvalidPasswordException as e:
        raise BadRequestError(e.response['Error']['Message'])
    except ParamValidationError as e:
        raise BadRequestError(e)
    except Exception as e:
        raise ChaliceViewError(e)
Beispiel #7
0
    def wrapper(*args, **kwargs):
        headers = {'Content-Type': 'text/json'}
        try:
            log.debug(f"Function: {f.__name__}")
            log.debug(f"ARGS: {args}")
            log.debug(f"KWARGS: {kwargs}")
            log.debug(f"Query Params: {app.current_request.query_params}")
            log.debug(f"Raw Body: {app.current_request.raw_body}")

            result = f(*args, **kwargs)

            log.debug(f"Result of Data API function call: {result}")

            status_code = http.HTTPStatus.OK
            body = None

            if result is None:
                status_code = http.HTTPStatus.NO_CONTENT
            else:
                if isinstance(result, Response):
                    return result
                elif isinstance(result, int):
                    return Response(body=body,
                                    status_code=result,
                                    headers={'Content-Type': 'text/plain'})
                elif isinstance(result, bool):
                    if result is True:
                        status_code = http.HTTPStatus.CREATED
                    else:
                        status_code = http.HTTPStatus.NO_CONTENT
                else:
                    if params.RESPONSE_BODY in result:
                        body = result[params.RESPONSE_BODY]

                        if params.DATA_MODIFIED in result and result.get(params.DATA_MODIFIED) is True:
                            status_code = http.HTTPStatus.CREATED
                        elif params.DATA_MODIFIED in result and result.get(params.DATA_MODIFIED) is False:
                            status_code = http.HTTPStatus.NOT_MODIFIED
                    else:
                        body = utils.decorate(result)

            return Response(body=body,
                            status_code=status_code,
                            headers=headers)
        except ConstraintViolationException as cve:
            log.error(str(cve))
            raise ConflictError(cve)
        except (UnimplementedFeatureException, ResourceNotFoundException) as ufe:
            log.error(str(ufe))
            raise NotFoundError(ufe)
        except InvalidArgumentsException as iae:
            log.error(str(iae))
            raise BadRequestError(iae)
        except DetailedException as ge:
            log.error(str(ge))
            return Response(body=str({"message": ge.message, "detail": ge.detail}),
                            headers={'Content-Type': 'text/json'},
                            status_code=http.HTTPStatus.INTERNAL_SERVER_ERROR)
        except Exception as e:
            log.error(str(e))
            raise e