Generate a new instance.

        The instance will be either 'built' or 'created'.

        Args:
            create (bool): whether to 'build' or 'create' the instance.

        Returns:
            object: the generated instance
186090
def simple_generate(cls, create, **kwargs):
        
        strategy = enums.CREATE_STRATEGY if create else enums.BUILD_STRATEGY
        return cls.generate(strategy, **kwargs)
1315057
def create(cls, *args, **kwargs) -> 'Entity':
        
        logger.debug(
            f'Creating new `{cls.__name__}` object using data {kwargs}')

        model_cls = repo_factory.get_model(cls)
        repository = repo_factory.get_repository(cls)

        try:
            # Build the entity from the input arguments
            # Raises validation errors, if any, at this point
            entity = cls(*args, **kwargs)

            # Do unique checks, create this object and return it
            entity._validate_unique()

            # Perform Pre-Save Actions
            entity.pre_save()

            # Build the model object and create it
            model_obj = repository.create(model_cls.from_entity(entity))

            # Update the auto fields of the entity
            for field_name, field_obj in entity.meta_.declared_fields.items():
                if isinstance(field_obj, Auto):
                    if isinstance(model_obj, dict):
                        field_val = model_obj[field_name]
                    else:
                        field_val = getattr(model_obj, field_name)
                    setattr(entity, field_name, field_val)

            # Set Entity status to saved
            entity.state_.mark_saved()

            # Perform Post-Save Actions
            entity.post_save()

            return entity
        except ValidationError:
            # FIXME Log Exception
            raise
1173528
async def create_or_get(self, model_, **kwargs):
        
        try:
            return (await self.create(model_, **kwargs)), True
        except IntegrityErrors:
            query = []
            for field_name, value in kwargs.items():
                field = getattr(model_, field_name)
                if field.unique or field.primary_key:
                    query.append(field == value)
            return (await self.get(model_, *query)), False
1093082
def get_or_create_instance(self, id=None, application=None, revision=None, environment=None, name=None, parameters=None, submodules=None,
                               destroyInterval=None):
        
        try:
            instance = self.get_instance(id=id, name=name)
            if name and name != instance.name:
                instance.rename(name)
                instance.ready()
            return instance
        except exceptions.NotFoundError:
            return self.create_instance(application, revision, environment, name, parameters, submodules, destroyInterval)
425133
def __create(self):
        
        self.__data = json.dumps({
            'config_path': self.encode(self.config_path),
            'subject': self.encode(self.__subject),
            'text': self.encode(self.__text),
            'html': self.encode(self.__html),
            'files': self.__files,
            'send_as_one': self.send_as_one,
            'addresses': self.__addresses,
            'ccs': self.__ccs,
        })
658812
def load_or_create(cls, filename=None, no_input=False, create_new=False, **kwargs):
        
        parser = argparse.ArgumentParser()
        parser.add_argument('--no_input', action='store_true')
        parser.add_argument('--create_new', action='store_true')
        args = parser.parse_args()

        if args.no_input:
            print('Parameter --no_input was given')
            no_input = True
        if args.create_new:
            print('Parameter --create_new was given')
            create_new = True
            no_input = True

        def savefile_more_recent():
            time_savefile = os.path.getmtime(filename)
            time_program = os.path.getmtime(sys.argv[0])
            return time_savefile > time_program

        def load_pickle():
            with open(filename, 'rb') as of:
                statefile_version, data = pickle.load(of)

            if statefile_version != STATEFILE_VERSION:
                raise RuntimeError(f'Wrong statefile version, please remove state file {filename}')
            return data

        def load():
            print('Loading %s' % filename)
            obj_list, config = load_pickle()
            system = System(load_state=obj_list, filename=filename, **kwargs)

            return system

        def create():
            print('Creating new system')
            config = None
            if filename:
                try:
                    obj_list, config = load_pickle()
                except FileNotFoundError:
                    config = None
            return cls(filename=filename, load_config=config, **kwargs)

        if filename and os.path.isfile(filename):
            if savefile_more_recent() and not create_new:
                return load()
            else:
                if no_input:
                    print('Program file more recent. Loading that instead.')
                    return create()
                while True:
                    answer = input('Program file more recent. Do you want to load it? (y/n) ')
                    if answer == 'y':
                        return create()
                    elif answer == 'n':
                        return load()
        else:
            return create()
52384
def get_or_create(self, **kwargs):
        
        assert kwargs, \
                'get_or_create() must be passed at least one keyword argument'
        defaults = kwargs.pop('defaults', {})
        lookup = kwargs.copy()
        #TODO: check fields
        try:
            return self.get(**lookup), False
        except self.model.DoesNotExist:
            params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
            params.update(defaults)
            obj = self.model(**params)
            meta = obj.get_meta()
            meta.connection = get_es_connection(self.es_url, self.es_kwargs)
            meta.index=self.index
            meta.type=self.type
            obj.save(force=True)
            return obj, True
627117
def _instance(self, cls, *args, **kwargs):
        
        logger.debug(f'args: {args}, kwargs: {kwargs}')
        return cls(*args, **kwargs)
84331
def get_or_create(self, request, *args, **kwargs):
        """"""
        kwargs['get_or_create'] = True
        return self.create(request, *args, **kwargs)
1156832
def get_or_create_by_natural_key(self, *args):
        
        try:
            return self.get_by_natural_key(*args), False
        except self.model.DoesNotExist:
            return self.create_by_natural_key(*args), True
1369430
def create(self):
        
        fdint = os.open(self.path, (os.O_EXCL |
                                    os.O_CREAT |
                                    os.O_RDWR))

        # XXX TODO: 'name' attribute of returned files is not mutable or
        # settable via fdopen, so this file is slighly less functional than the
        # one returned from 'open' by default.  send a patch to Python...

        return os.fdopen(fdint, 'w+b')
1208002
def create(self, _attributes=None, **attributes):
        
        if _attributes is not None:
            attributes.update(_attributes)

        instance = self._related.new_instance(attributes)

        instance.set_attribute(self.get_plain_foreign_key(), self.get_parent_key())

        instance.save()

        return instance
1161214
def create(self, child):
        

        prev_data = self.data
        self.data = child.data  # This way append works appends to the child

        yield child  # allows with ... as to be used as well

        self.data = prev_data
        self.append(child)
799405
def create(self, **kwargs):
        

        response = self.ghost.execute_post('%s/' % self._type_name, json={
            self._type_name: [
                kwargs
            ]
        })

        return self._model_type(response.get(self._type_name)[0])
897866
def perform_create(self, data):
        

        instance = self.model(**data)
        self.request.dbsession.add(instance)
        self.request.dbsession.flush()
        return instance
198232
def get_or_create(cls, **kwargs):
        """"""

        data = cls._get(**kwargs)
        if data is None:
            return cls(**kwargs), True
        return cls.deserialize(data), False
964996
def create(self, **kwargs):
        
        obj = self.resource(**kwargs)
        obj.save(force_insert=True)
        return obj