"""Response. The response is an object that helps communication between our different layers. The response contains 3 fields: message (data), errors (any errors found) and a status. The success property of the object determines whether or not the method was able (or not) to perform the operation. The operation is considered as successful only in the case of a status 200 and absense of errors:: resp = Response(errors='Something', status=200) resp.success # False resp.status # 400 resp = Response() resp.success # True resp.status # 200 """ class Response: """Response.""" def __init__(self, message=None, errors=None, status=200): """Create a Response. Args: message: the message object (it could be any type of object.) errors: the errors to attach (it could be any type of object.) status (int): the status of the response. Errors should use the status that is the most appropriate. System failures should set a 500. """ self.status = status self.message = message self.errors = errors if self.errors and self.status == 200: self.status = 400 @property def success(self): """Success Property. Returns: boolean: if the response is considered as successful. """ return self.status == 200 and not self.errors def __iter__(self): """Iterator. The iterator allows us to return data from the logic layer that can be returned by the handlers as a response. If errors are found, the errors will be returned instead of the message. """ if self.success: data = [self.message, self.status] else: data = [dict(errors=self.errors), self.status] for item in data: yield item def create_fatal_response(errors=None): """Create a fatal response. Args: errors: the error to add (it could be any type of object, from string to dict.) Returns: Response: the response object. """ return Response(errors=errors, status=500) def create_error_response(errors=None, status=400): """Create a fail response. Args: errors: The errors to add (it could be any type of object, from string to dict.) status (int): the status code. Returns: Response: the “failed“ response. """ return Response(errors=errors, status=status) def create_not_found_response(errors=None): """Create a not found response. Args: errors: The errors to add (it could be any type of object, from strings to dict.) Returns: Response: the “not found” response. """ return Response(errors=errors, status=404)