def generate_error_response(e, request, error, status=500): # We may need to check the roles of the users to show the real error eid = uuid.uuid4().hex http_response = query_adapter( e, IErrorResponseException, kwargs={ 'error': error, 'eid': eid }) if http_response is not None: return http_response message = _('Error on execution of view') + ' ' + eid logger.error(message, exc_info=e, eid=eid, request=request) return response.HTTPInternalServerError(content={ 'message': message, 'reason': error_reasons.UNKNOWN.name, 'details': error_reasons.UNKNOWN.details, 'eid': eid })
async def __call__(self): """To create a content.""" data = await self.get_data() type_ = data.get('@type', None) id_ = data.get('id', None) behaviors = data.get('@behaviors', None) if not type_: raise ErrorResponse('RequiredParam', _("Property '@type' is required"), reason=error_reasons.REQUIRED_PARAM_MISSING, status=412) # Generate a temporary id if the id is not given new_id = None if not id_: generator = query_adapter(self.request, IIDGenerator) if generator is not None: new_id = generator(data) if isinstance(new_id, str) and not valid_id(new_id): raise ErrorResponse('PreconditionFailed', 'Invalid id: {}'.format(new_id), status=412, reason=error_reasons.INVALID_ID) else: if not isinstance(id_, str) or not valid_id(id_): raise ErrorResponse('PreconditionFailed', 'Invalid id: {}'.format(id_), status=412, reason=error_reasons.INVALID_ID) new_id = id_ user = get_authenticated_user_id(self.request) options = {'creators': (user, ), 'contributors': (user, )} if 'uid' in data: options['_p_oid'] = data.pop('uid') # Create object try: obj = await create_content_in_container(self.context, type_, new_id, **options) except ValueError as e: return ErrorResponse('CreatingObject', str(e), status=412) for behavior in behaviors or (): obj.add_behavior(behavior) # Update fields deserializer = query_multi_adapter((obj, self.request), IResourceDeserializeFromJson) if deserializer is None: return ErrorResponse('DeserializationError', 'Cannot deserialize type {}'.format( obj.type_name), status=412, reason=error_reasons.DESERIALIZATION_FAILED) await deserializer(data, validate_all=True, create=True) # Local Roles assign owner as the creator user get_owner = get_utility(IGetOwner) roleperm = IPrincipalRoleManager(obj) owner = await get_owner(obj, user) if owner is not None: roleperm.assign_role_to_principal('guillotina.Owner', owner) data['id'] = obj.id await notify(ObjectAddedEvent(obj, self.context, obj.id, payload=data)) absolute_url = query_multi_adapter((obj, self.request), IAbsoluteURL) headers = { 'Access-Control-Expose-Headers': 'Location', 'Location': absolute_url() } serializer = query_multi_adapter((obj, self.request), IResourceSerializeToJsonSummary) response = await serializer() return Response(content=response, status=201, headers=headers)
async def __call__(self): """To create a content.""" data = await self.get_data() type_ = data.get('@type', None) id_ = data.get('id', None) behaviors = data.get('@behaviors', None) if '__acl__' in data: # we don't allow to change the permisions on this patch del data['__acl__'] if not type_: return ErrorResponse('RequiredParam', _("Property '@type' is required")) # Generate a temporary id if the id is not given if not id_: new_id = None else: if not valid_id(id_): return ErrorResponse('PreconditionFailed', str('Invalid id'), status=412) new_id = id_ user = get_authenticated_user_id(self.request) # Create object try: obj = await create_content_in_container(self.context, type_, new_id, id=new_id, creators=(user, ), contributors=(user, )) except (PreconditionFailed, NotAllowedContentType) as e: return ErrorResponse('PreconditionFailed', str(e), status=412) except ConflictIdOnContainer as e: return ErrorResponse('ConflictId', str(e), status=409) except ValueError as e: return ErrorResponse('CreatingObject', str(e), status=400) for behavior in behaviors or (): obj.add_behavior(behavior) # Update fields deserializer = query_multi_adapter((obj, self.request), IResourceDeserializeFromJson) if deserializer is None: return ErrorResponse('DeserializationError', 'Cannot deserialize type {}'.format( obj.type_name), status=501) try: await deserializer(data, validate_all=True) except DeserializationError as e: return ErrorResponse('DeserializationError', str(e), exc=e, status=400) # Local Roles assign owner as the creator user get_owner = get_utility(IGetOwner) roleperm = IPrincipalRoleManager(obj) owner = await get_owner(obj, user) if owner is not None: roleperm.assign_role_to_principal('guillotina.Owner', owner) data['id'] = obj.id await notify(ObjectAddedEvent(obj, self.context, obj.id, payload=data)) absolute_url = query_multi_adapter((obj, self.request), IAbsoluteURL) headers = { 'Access-Control-Expose-Headers': 'Location', 'Location': absolute_url() } serializer = query_multi_adapter((obj, self.request), IResourceSerializeToJson) response = await serializer() return Response(response=response, headers=headers, status=201)
def generate_error_response(e, request, error, status=500): # We may need to check the roles of the users to show the real error eid = uuid.uuid4().hex message = _('Error on execution of view') + ' ' + eid logger.error(message, exc_info=e, eid=eid, request=request) return ErrorResponse(error, message, status)
def generate_unauthorized_response(e, request): # We may need to check the roles of the users to show the real error eid = uuid.uuid4().hex message = _('Not authorized to render operation') + ' ' + eid logger.error(message, exc_info=e, eid=eid, request=request) return UnauthorizedResponse(message)
async def __call__(self): """To create a content.""" data = await self.get_data() type_ = data.get("@type", None) id_ = data.get("id", None) behaviors = data.get("@behaviors", None) if not type_: raise ErrorResponse( "RequiredParam", _("Property '@type' is required"), reason=error_reasons.REQUIRED_PARAM_MISSING, status=412, ) id_checker = get_adapter(self.context, IIDChecker) # Generate a temporary id if the id is not given new_id = None if not id_: generator = query_adapter(self.request, IIDGenerator) if generator is not None: new_id = await apply_coroutine(generator, data) if isinstance(new_id, str) and not await id_checker(new_id, type_): raise ErrorResponse( "PreconditionFailed", "Invalid id: {}".format(new_id), status=412, reason=error_reasons.INVALID_ID, ) else: if not isinstance(id_, str) or not await id_checker(id_, type_): raise ErrorResponse( "PreconditionFailed", "Invalid id: {}".format(id_), status=412, reason=error_reasons.INVALID_ID, ) new_id = id_ user = get_authenticated_user_id() options = {"creators": (user,), "contributors": (user,)} if "uid" in data: options["__uuid__"] = data.pop("uid") # Create object try: obj = await create_content_in_container( self.context, type_, new_id, check_constraints=True, **options ) except ValueError as e: return ErrorResponse("CreatingObject", str(e), status=412) for behavior in behaviors or (): obj.add_behavior(behavior) # Update fields deserializer = query_multi_adapter((obj, self.request), IResourceDeserializeFromJson) if deserializer is None: return ErrorResponse( "DeserializationError", "Cannot deserialize type {}".format(obj.type_name), status=412, reason=error_reasons.DESERIALIZATION_FAILED, ) await deserializer(data, validate_all=True, create=True) # Local Roles assign owner as the creator user get_owner = get_utility(IGetOwner) roleperm = IPrincipalRoleManager(obj) owner = await get_owner(obj, user) if owner is not None: roleperm.assign_role_to_principal("guillotina.Owner", owner) data["id"] = obj.id await notify(ObjectAddedEvent(obj, self.context, obj.id, payload=data)) headers = {"Access-Control-Expose-Headers": "Location", "Location": get_object_url(obj, self.request)} serializer = query_multi_adapter((obj, self.request), IResourceSerializeToJsonSummary) response = await serializer() return Response(content=response, status=201, headers=headers)