def test_poc_assocproxy(self): from datetime import datetime article = Article( author='unknown', release=datetime.now(), title='A Thousand and one nights', content='It has been related to me, O happy King, said Shahrazad') session.add(article) session.flush() session.expunge_all() article = Article.get(1) fr = article.add_locale('fr', title='Les mille et une nuits', content=u"J'ai entendu dire, Ô mon roi, dit Scheherazade") assert fr is not None session.commit() session.expunge_all() article = Article.get(1) author = article.get_localized('fr').author assert author is not None release = article.get_localized('fr').release assert release is not None
def entity_setstate(entity, d): """Set the state of an SQLAlchemy entity In: - ``entity`` -- the newly created and not yet initialized SQLAlchemy entity - ``d`` -- the state dictionary (created by ``entity_getstate()``) """ # Copy the _not_ SQLAlchemy managed attributes to our entity key = d.pop('_sa_key', None) entity.__dict__.update(d) if key is not None: # Fetch a new and initialized SQLAlchemy from the database x = session.query(entity.__class__).get(key) session.expunge(x) # Copy its state to our entity entity.__dict__.update(x.__dict__) # Adjust the entity SQLAlchemy state state = x._sa_instance_state.__getstate__() state['instance'] = entity entity._sa_instance_state.__setstate__(state) # Add the entity to the current database session session.add(entity)
def setUp(self): """Method used to build a database""" metadata.bind = engine setup_all() create_all() article = Article(author='unknown', title='A Thousand and one nights', content='It has been related to me, O happy King, said Shahrazad') session.add(article) session.flush() session.expunge_all() self.article = Article.get(1)
def post(self): """Creates a new instance of a given model based on request data. This function parses the string contained in :attr:`flask.request.data`` as a JSON object and then validates it with a validator specified in the constructor of this class. The :attr:`flask.request.data` attribute will be parsed as a JSON object containing the mapping from field name to value to which to initialize the created instance of the model. After that, it separates all columns that defines relationships with other entities, creates a model with the simple columns and then creates instances of these submodels and associates them with the related fields. This happens only at the first level of nesting. Currently, this method can only handle instantiating a model with a single level of relationship data. """ self._check_authentication() # try to read the parameters for the model from the body of the request try: params = json.loads(request.data) except (TypeError, ValueError, OverflowError): return jsonify_status_code(400, message='Unable to decode data') # Getting the list of relations that will be added later cols = self.model.get_columns() relations = self.model.get_relations() # Looking for what we're going to set on the model right now colkeys = cols.keys() paramkeys = params.keys() props = set(colkeys).intersection(paramkeys).difference(relations) # Instantiate the model with the parameters instance = self.model(**dict([(i, params[i]) for i in props])) # Handling relations, a single level is allowed for col in set(relations).intersection(paramkeys): submodel = cols[col].property.mapper.class_ for subparams in params[col]: subinst = submodel.get_or_create(**subparams)[0] getattr(instance, col).append(subinst) # add the created model to the session session.add(instance) session.commit() return jsonify_status_code(201, id=instance.id)
def get_or_create(model, **kwargs): """Helper function to search for an object or create it otherwise, based on the Django's Model.get_or_create() method. """ instance = model.query.filter_by(**kwargs).first() if instance: return instance, False else: params = {} for key, val in kwargs.iteritems(): params[key] = val instance = model(**params) session.add(instance) return instance, True
def setUp(self): """Adds some initial people to the database after creating and initializing it. """ super(TestSupportPrefilled, self).setUp() # create some people in the database for testing lincoln = Person(name=u'Lincoln', age=23, other=22) mary = Person(name=u'Mary', age=19, other=19) lucy = Person(name=u'Lucy', age=25, other=20) katy = Person(name=u'Katy', age=7, other=10) john = Person(name=u'John', age=28, other=10) self.people = [lincoln, mary, lucy, katy, john] for person in self.people: session.add(person) session.commit()
def test_get_localized_versions(self): movie = Movie(author='unknown', title='A Thousand and one nights', content='It has been related to me, O happy King, said Shahrazad', resume='not suitable for young children') session.add(movie) session.commit() session.expunge_all() # media attribute retrieved_movie = Movie.get(1) fr = retrieved_movie.add_locale('fr', title='Les mille et une nuits', content=u"J'ai entendu dire, Ô mon roi, dit Scheherazade", resume=u'déconseillé au jeune public') session.commit() session.expunge_all() retrieved_movie = Movie.query.one() assert retrieved_movie.get_localized('fr').title == 'Les mille et une nuits' # movie attribute assert retrieved_movie.get_localized('fr').resume == u'déconseillé au jeune public'
def setUp(self): """Creates the database and all necessary tables, and adds some initial rows to the Person table. """ # set up the database self.db_fd, self.db_file = mkstemp() setup(create_engine('sqlite:///%s' % self.db_file)) create_all() session.commit() # create some people in the database for testing lincoln = Person(name=u'Lincoln', age=23, other=22) mary = Person(name=u'Mary', age=19, other=19) lucy = Person(name=u'Lucy', age=25, other=20) katy = Person(name=u'Katy', age=7, other=10) john = Person(name=u'John', age=28, other=10) self.people = [lincoln, mary, lucy, katy, john] for person in self.people: session.add(person) session.commit()
def setUp(self): """Creates the database, the Flask application, and the APIManager.""" # create the database super(TestSupportWithManagerPrefilled, self).setUp() # create the Flask application app = Flask(__name__) app.config['DEBUG'] = True app.config['TESTING'] = True self.app = app.test_client() # setup the URLs for the Person API self.manager = APIManager(app) # create some people in the database for testing lincoln = Person(name=u'Lincoln', age=23, other=22) mary = Person(name=u'Mary', age=19, other=19) lucy = Person(name=u'Lucy', age=25, other=20) katy = Person(name=u'Katy', age=7, other=10) john = Person(name=u'John', age=28, other=10) self.people = [lincoln, mary, lucy, katy, john] for person in self.people: session.add(person) session.commit()
def get_or_create(cls, **kwargs): """Returns the first instance of the specified model filtered by the keyword arguments, or creates a new instance of the model and returns that. This function returns a two-tuple in which the first element is the created or retrieved instance and the second is a boolean value which is ``True`` if and only if an instance was created. The idea for this function is based on Django's ``Model.get_or_create()`` method. ``kwargs`` are the keyword arguments which will be passed to the :func:`sqlalchemy.orm.query.Query.filter_by` function. """ instance = cls.query.filter_by(**kwargs).first() if instance: return instance, False else: instance = cls(**kwargs) session.add(instance) session.commit() return instance, True
def add(cls, entity): """ Ajoute un objet en session """ session.add(entity)
def create(self, dict_attrs): obj = self.Entity() obj.from_dict(dict_attrs) session.add(obj) self.commitChanges()
def addRow(self, entity): session.add(entity) self.saveChanges() self.load()
relations = model.get_relations() # Looking for what we're going to set to the model right now props = set(cols.keys()).intersection(params.keys()).difference(relations) instance = model(**dict([(i, params[i]) for i in props])) # Handling relations, a single level is allowed for col in set(relations).intersection(params.keys()): submodel = cols[col].property.mapper.class_ subvalidator = getattr(CONFIG['validators'], submodel.__name__) for subparams in params[col]: subparams = subvalidator.to_python(subparams) subinst = get_or_create(submodel, **subparams)[0] getattr(instance, col).append(subinst) session.add(instance) session.commit() # We return a ok message and the just created instance id return dumps({'status': 'ok', 'message': 'You rock!', 'id': instance.id}) def build_search_param(model, fname, relation, operation, value): """Translates an operation described as a string to a valid sqlalchemy query parameter. This takes, for example, the operation ``gt`` and converts it to something like this: ``field > value``. `model`