예제 #1
0
 def get_spec(self):
     if self.unique_field:
         additional_responses = self.additional_responses + (
             responses.AlreadyExistsResponse(
                 entity=[self.entity, self.unique_field]), )
     else:  # pragma: no cover
         additional_responses = self.additional_responses
     if self.ext_body_parameters == ():
         return swagger.specify.get_spec(
             method='post',
             description='Creates new {}'.format(self.entity.lower()),
             path_parameters=self.path_parameters,
             body_parameters=('{} to create'.format(self.entity),
                              self.scheme_class),
             responses=(self.scheme_class.get_object_created_response(
                 entity=self.entity), responses.ValidationErrorResponse(),
                        responses.FkConstraintViolationResponse()) +
             additional_responses +
             self.get_additional_responses(method='post'),
             security=self.get_security(method='post'),
             #consumes='multipart/form-data',
             #ext_body_parameters=self.ext_body_parameters
         )
     else:
         return swagger.specify.get_spec(
             method='post',
             description='Creates new {}'.format(self.entity.lower()),
             path_parameters=self.path_parameters,
             #body_parameters=('{} to create'.format(self.entity), self.scheme_class),
             responses=(self.scheme_class.get_object_created_response(
                 entity=self.entity), responses.ValidationErrorResponse(),
                        responses.FkConstraintViolationResponse()) +
             additional_responses +
             self.get_additional_responses(method='post'),
             security=self.get_security(method='post'),
             consumes=['application/json', 'multipart/form-data'],
             ext_body_parameters=(
                 {
                     'name': 'body',
                     'type': 'object',
                     'in': 'body',
                     'description': '{} to create'.format(self.entity),
                     'schema': {
                         '$ref':
                         '#/definitions/{}'.format(
                             self.scheme_class.__name__.replace(
                                 'Scheme', ''))
                     }
                 }, ) + self.ext_body_parameters)
예제 #2
0
    def on_patch(self, req, resp, **kwargs):
        self.init_req(req)
        kwargs = user_context(self, req, resp, **kwargs)
        if not self.has_modify_operation:  # pragma: no cover
            return self.method_not_allowed_response(resp, 'PATCH')

        if not check_permission(
                self, req, 'modify',
                self.get_object(resp, self.model_class, **kwargs)):
            self.set_response(
                resp,
                responses.ForbiddenErrorResponse(
                    data=errors.AuthErrors.Forbidden))
            return

        try:
            scheme = self.scheme_class_modify(
            ) if self.scheme_class_modify else self.scheme_class()
            if self.check_request_data(req, resp, scheme):
                if self.update_object(
                        req, resp, self.model_class, self.scheme_class_modify
                        if self.scheme_class_modify else self.scheme_class,
                        **kwargs):
                    data = self.get_object_data(resp, self.model_class,
                                                self.scheme_class_get,
                                                **kwargs)
                    if data:
                        self.set_response(
                            resp,
                            responses.SuccessResponseObjectInfo(data=data))
                    else:
                        self.set_response(resp,
                                          responses.SuccessResponseJustOk())
        except IntegrityError as e:
            try:
                msg = str(e).split('\n')[1].split(':')[1]
            except:
                msg = str(e)

            self.set_response(resp, AlreadyExistsResponse(self.entity, msg))
        except FkConstraintViolation as e:
            self.set_response(
                resp,
                responses.FkConstraintViolationResponse(
                    data=errors.CommonErrors.get_fk_violation_error(
                        e.table_name, e.column_name, e.value)))
        except ValidationError as e:
            self.set_response(
                resp, responses.ValidationErrorResponse(data=e.messages))
        except NoResultFound:
            self.set_response(resp, responses.ObjectNotFoundErrorResponse())
        except Exception as e:
            log.error(e)
            #self.set_response(resp, responses.OperationErrorResponse(data=errors.CommonErrors.DataError))
            self.set_response(resp, OperationalError(e))
예제 #3
0
    def on_post(self, req, resp, **kwargs):
        self.init_req(req)
        kwargs = user_context(self, req, resp, **kwargs)
        self.apply_restrict_rules(req, kwargs)
        scheme = self.scheme_class()
        if not check_permission(self, req, 'create'):
            self.set_response(
                resp,
                responses.ForbiddenErrorResponse(
                    data=errors.AuthErrors.Forbidden))
            return

        if self.check_request_data(req, resp, scheme):
            try:
                data = self.create_object(req, scheme, **kwargs)
                self.set_response(
                    resp,
                    self.scheme_class.get_object_created_response(data=data))
                self.after_create(data, req, resp, **kwargs)
            except IntegrityError as e:
                #self.set_response(resp, responses.AlreadyExistsResponse(
                #    data=errors.CommonErrors.get_already_exists_error(self.entity, self.unique_field))
                #)
                try:
                    msg = str(e).split('\n')[1].split(':')[1]
                except:
                    msg = str(e)

                self.set_response(resp,
                                  AlreadyExistsResponse(self.entity, msg))

            except FkConstraintViolation as e:
                self.set_response(
                    resp,
                    responses.FkConstraintViolationResponse(
                        data=errors.CommonErrors.get_fk_violation_error(
                            e.table_name, e.fk_column_name, e.column_name,
                            e.value)))
            except schemes.validate.ValidationError as e:
                self.set_response(
                    resp, responses.ValidationErrorResponse(data=e.messages))

            except DataError as e:
                log.error(e)
                #self.set_response(resp, responses.OperationErrorResponse(data=errors.CommonErrors.DataError))
                self.set_response(resp, OperationalError(e))

            except Exception as e:
                log.error(e)
                # self.set_response(resp, responses.OperationErrorResponse(data=errors.CommonErrors.DataError))
                self.set_response(resp, OperationalError(e))
예제 #4
0
    def proceed(self, req, resp, **kwargs):

        if (not hasattr(self, 'no_auth_needed') or self.no_auth_needed == False) and \
                not check_permission(self, req, self.action, self.get_object(resp, self.model_class, **kwargs)):
            self.set_response(
                resp,
                responses.ForbiddenErrorResponse(
                    data=errors.AuthErrors.Forbidden))
            return

        try:
            obj = self.get_object(resp, self.model_class, **kwargs)
            if self.check_conditions(obj, self.pre_conditions,
                                     lambda a, b: a == b):
                if self.check_conditions(obj, self.pre_conditions_inverted,
                                         lambda a, b: a != b):
                    if self.apply(obj, req, resp, **kwargs):
                        self.set_response(resp,
                                          responses.SuccessResponseJustOk())

        except FkConstraintViolation as e:
            self.set_response(
                resp,
                responses.FkConstraintViolationResponse(
                    data=errors.CommonErrors.get_fk_violation_error(
                        e.table_name, e.column_name, e.value)))
        except IntegrityError as e:
            try:
                msg = str(e).split('\n')[1].split(':')[1]
            except:
                msg = str(e)

            self.set_response(resp, AlreadyExistsResponse(self.entity, msg))
            return False
        except PreConditionFailedException as e:
            self.set_response(
                resp,
                responses.OperationErrorResponse(
                    data=errors.CommonErrors.get_pre_condition_failed_error(
                        e.message)))
        except Exception as e:
            self.set_response(resp, OperationalError(e))
예제 #5
0
    def apply(self, obj, req, resp, **kwargs):
        result = []
        updated = 0
        added = 0
        deleted = 0
        try:
            ids = [
                it[self.id_field] for it in req.data['items']
                if self.id_field in it
            ]
            if not self.modify_only:
                for obj in self.model_class.query().all():
                    if not obj.get_object_primary_key_value() in ids:
                        kwargs[self.id_field] = str(
                            obj.get_object_primary_key_value())
                        if self.delete_object(req, resp, self.model_class,
                                              **kwargs):
                            deleted += 1

            for data in req.data['items']:
                req.data = data
                if self.id_field in data and not data[self.id_field] == 'null':
                    kwargs[self.id_field] = data[self.id_field]
                    if self.update_object(req, resp, self.model_class,
                                          self.scheme_class, **kwargs):

                        updated += 1
                else:
                    if 'id' in kwargs:
                        del kwargs[self.id_field]
                    scheme = self.scheme_class(exclude=(self.id_field, ))
                    if not self.modify_only:
                        if self.check_request_data(req, resp, scheme):
                            #resp = self.scheme_class.get_object_created_response(data=self.create_object(req, scheme, **kwargs) )
                            obj = self.create_object(req, scheme, **kwargs)
                            added += 1

            if (updated + deleted + added) > 0:
                self.set_response(
                    resp,
                    responses.SuccessResponse(data={
                        'updated': updated,
                        'deleted': deleted,
                        'added': added,
                    },
                                              scheme=schemes.ObjectScheme))
                return True
            else:
                self.set_response(resp, responses.SuccessResponseJustOk())
                return True

        except IntegrityError as e:
            try:
                msg = str(e).split('\n')[1].split(':')[1]
            except:
                msg = str(e)

            self.set_response(resp, AlreadyExistsResponse(self.entity, msg))
            return False
        except FkConstraintViolation as e:
            self.set_response(
                resp,
                responses.FkConstraintViolationResponse(
                    data=errors.CommonErrors.get_fk_violation_error(
                        e.table_name, e.column_name, e.value)))
            return False
        except Exception as e:
            self.set_response(resp, OperationalError(e))
            return False