当前位置: 首页>>代码示例>>Python>>正文


Python Store.add方法代码示例

本文整理汇总了Python中storm.locals.Store.add方法的典型用法代码示例。如果您正苦于以下问题:Python Store.add方法的具体用法?Python Store.add怎么用?Python Store.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在storm.locals.Store的用法示例。


在下文中一共展示了Store.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_migration_error_with_removed_language

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]
    def test_migration_error_with_removed_language(self):
        store = Store(create_database(GLSettings.db_uri))
        zyx = EnabledLanguage('zyx')
        store.add(zyx)
        store.commit()
        store.close()

        self.assertRaises(Exception, migration.perform_data_update, self.db_file)
开发者ID:Taipo,项目名称:GlobaLeaks,代码行数:10,代码来源:test_migration.py

示例2: do_statspollute

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]
def do_statspollute(dbfile):

    # source
    gl_database = create_database("sqlite:%s" % dbfile)
    source_store = Store(gl_database)

    stats = source_store.find(models.Stats)

    counter = 0
    for s in stats:
        source_store.remove(s)
        counter += 1

    print "removed %d entry in stats" % counter

    counter = 0
    # 21 days in the past
    for past_hours in xrange(24 * 7 * 3):
        past_hours += 4
        when = utc_past_date(hours=past_hours)

        newstat = models.Stats()
        newstat.freemb = randint(1000, 1050)
        newstat.year = when.isocalendar()[0]
        newstat.week = when.isocalendar()[1]

        level = round((randint(0, 1000) / 240.0), 1) - 2

        def random_pollution():
            return int(randint(0,11) + (5 * level))

        activity_fake = {
            'successfull_logins': random_pollution(),
            'failed_logins': random_pollution(),
            'started_submissions': random_pollution(),
            'completed_submissions': random_pollution(),
            'uploaded_files': int(randint(0,11) + (5  * level)),
            'appended_files': random_pollution(),
            'wb_comments': random_pollution(),
            'wb_messages': random_pollution(),
            'receiver_comments': random_pollution(),
            'receiver_messages': random_pollution()
        }

        for k, v in activity_fake.iteritems():
            if v < 0:
                activity_fake[k] = 0

        newstat.start = when
        newstat.summary = activity_fake
        counter += 1
        source_store.add(newstat)

    print "Committing %d stats" % counter
    source_store.commit()
开发者ID:RuanAragao,项目名称:GlobaLeaks,代码行数:57,代码来源:pollutestats.py

示例3: testCreate

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]
    def testCreate(self):
        """Test creation of new MusicTrack"""

        store = Store(self.db)
        musictrack = models.MusicTrack()
        musictrack.title = u"The Beautiful Ones"
        store.add(musictrack)
        store.commit()

        self.assertTrue(Store.of(musictrack) is store)

        musictrack_from_database = store.find(models.MusicTrack, models.MusicTrack.title == u"The Beautiful Ones").one()
        self.assertTrue(musictrack is musictrack_from_database)
开发者ID:tiwilliam,项目名称:entertainer,代码行数:15,代码来源:test_models.py

示例4: getStore

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]
def getStore(url, create = False):
    # register new Storm scheme
    register_scheme("sqlitefk", ForeignKeysSQLite)

    d = create_database(url)
    s = Store(d)

    if create:
        schema = file(os.path.join(os.path.dirname(__file__), "schema.sql"), "r").read().split("\n\n")
        for cmd in schema:
            s.execute(cmd)

        version = Meta()
        version.key = u"created"
        s.add(version)

        s.commit()

    return s
开发者ID:MarSik,项目名称:elshelves,代码行数:21,代码来源:model.py

示例5: TestChangeTracker

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]
class TestChangeTracker(object):


    class A(object):
        __storm_table__ = 'testob'
        changehistory = ChangeHistory.configure("history")
        clt = ChangeTracker(changehistory)
        id = Int(primary=1)
        textval = Unicode(validator=clt)
        intval = Int(validator=clt)

    def setUp(self):
        database = create_database('sqlite:')
        self.store = Store(database)
        self.store.execute("""
            CREATE table history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                ref_class VARCHAR(200),
                ref_pk VARCHAR(200),
                ref_attr VARCHAR(200),
                new_value VARCHAR(200),
                ctime DATETIME,
                cuser INT
            )
        """)
        self.store.execute("""
            CREATE TABLE testob (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                textval VARCHAR(200),
                intval INT,
                dateval DATETIME
            )""")

    def tearDown(self):
        self.store.rollback()

    def test_calls_next_validator(self):
        clt = ChangeTracker(ChangeHistory.configure("history"), next_validator = lambda ob, attr, v: v*2)

        class B(self.A):
            textval = Unicode(validator=clt)

        b = B()
        b.textval = u'bork'
        assert b.textval == u'borkbork'

    def test_adds_log_entries(self):

        class B(self.A):
            clt = ChangeTracker(ChangeHistory.configure("history"))
            textval = Unicode(validator=clt)

        b = self.store.add(B())
        b.textval = u'pointless'
        b.textval = u'aimless'
        changes = list(self.store.find(b.clt.change_cls))
        assert_equal(len(changes), 2)
        assert_equal(changes[0].new_value, 'pointless')
        assert_equal(changes[1].new_value, 'aimless')

    def test_value_type_preserved(self):
        a = self.store.add(self.A())
        a.textval = u'one'
        a.intval = 1
        changes = list(self.store.find(a.clt.change_cls))
        assert_equal(type(changes[0].new_value), unicode)
        assert_equal(type(changes[1].new_value), int)

    def test_ctime_set(self):
        start = datetime.now()
        a = self.store.add(self.A())
        a.textval = u'x'
        changes = list(self.store.find(a.clt.change_cls))
        assert_equal(type(changes[0].ctime), datetime)
        assert start < changes[0].ctime < datetime.now()

    def test_cuser_set(self):
        def getuser():
            return u'Fred'

        history = ChangeHistory.configure("history", getuser=getuser, usertype=Unicode)
        class B(self.A):
            textval = Unicode(validator=ChangeTracker(history))

        b = self.store.add(B())
        b.textval = u'foo'
        changes = self.store.find(history)
        assert_equal(changes[0].cuser, u'Fred')


    def test_changes_for_returns_change_history(self):
        a = self.store.add(self.A())
        b = self.store.add(self.A())
        a.id = 1
        a.textval = u'one'
        a.textval = u'two'
        b.id = 2
        b.textval = u'ein'
        b.textval = u'zwei'

#.........这里部分代码省略.........
开发者ID:ollyc,项目名称:stormchaser,代码行数:103,代码来源:tests.py

示例6: __repr__

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]
			x = self.x,
			y = self.y
		)

	def __repr__( self ):
		return '<Point2D x:%s, y:%s>' % (
			self.x,
			self.y
		)

database = create_database('sqlite://:memory:')
store = Store(database)
store.execute('''CREATE TABLE point2d (
	id INTEGER PRIMARY KEY,
	x INTEGER,
	y INTEGER
)''')

p1 = Point2D(10,10)
p2 = Point2D(10,20)
p3 = Point2D(20,20)
p4 = Point2D(20,10)

store.add( p1 )
store.add( p2 )
store.add( p3 )
store.add( p4 )

points = store.find(Point2D, Point2D.x == 10)
print points[0] + points[1]
开发者ID:ippo615,项目名称:experiments,代码行数:32,代码来源:main.py

示例7: Person

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]
)''')

persons = [
	Person( name=u'Amy', age=52 ),
	Person( name=u'Bob', age=48 ),
	Person( name=u'Cat', age=23 ),
	Person( name=u'Dan', age=17 ),
	Person( name=u'Edd', age=77 ),
	Person( name=u'Fan', age=65 ),
	Person( name=u'Gin', age=27 ),
	Person( name=u'Hil', age=30 ),
	Person( name=u'Iri', age=62 ),
	Person( name=u'Jac', age=18 )
]
for person in persons:
	store.add(person)

def getColumnNames( row ):
	columns = row._storm_columns
	names = []
	for column in columns:
		names.append( columns[column].name )
	return names

# Custom function to save a csv file
def writeClassToFile( class_, store, fileHandle ):
	
	# Get the data and determine the fieldnames
	rows = store.find(class_)
	headers = [x for x in rows[0].as_dict()]
	
开发者ID:ippo615,项目名称:experiments,代码行数:32,代码来源:export.py

示例8: IssuesLog

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]

#.........这里部分代码省略.........
            aux.date = db_ilog.date
            aux.assigned_to = db_ilog.assigned_to

            aux.link = db_ilog.link
            aux.component = db_ilog.component
            aux.version = db_ilog.version
            aux.issue_key = db_ilog.issue_key
            aux.environment = db_ilog.environment
            aux.project = db_ilog.project
            aux.project_key = db_ilog.project_key
            aux.security = db_ilog.security

            return aux

    def get_people_id(self, email, tracker_id):
        """
        Gets the id of an user
        """
        p = self.store.find(DBPeople, DBPeople.email == email).one()
        ##
        ## the code below was created ad-hoc for KDE solid
        ##
        try:
            return p.id
        except AttributeError:
            p = self.store.find(DBPeople, DBPeople.user_id == email).one()
            try:
                return p.id
            except AttributeError:
                # no person was found in People with the email above, so
                # we include it
                printdbg("Person not found. Inserted with email %s " % (email))
                dp = DBPeople(email, tracker_id)
                self.store.add(dp)
                self.store.commit()
                return dp.id

    def get_last_change_date(self):
        """
        This method gets the date of the last change included in the log table
        """
        if self.backend_is_bugzilla():
            result = self.store.find(DBBugzillaIssuesLog)
            aux = result.order_by(Desc(DBBugzillaIssuesLog.date))[:1]
            for entry in aux:
                return entry.date
        elif self.backend_is_jira():
            result = self.store.find(DBJiraIssuesLog)
            aux = result.order_by(Desc(DBJiraIssuesLog.date))[:1]
            for entry in aux:
                return entry.date
        return None

    def get_issues_changed_since(self, date):
        """
        This method fetchs the issues changes since date
        """

        #SELECT DISTINCT(issues.id) FROM issues, changes
        #WHERE issues.id = changes.issue_id
        #AND (issues.submitted_on >= '2012-02-28 12:34:44'
        #    OR changes.changed_on >= '2012-02-28 12:34:44');

        result = self.store.find(DBIssue,
                                 DBChange.issue_id == DBIssue.id,
                                 Or(DBIssue.submitted_on > date,
开发者ID:MetricsGrimoire,项目名称:Bicho,代码行数:70,代码来源:logtable.py

示例9: NCBITaxnomyInserter

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]
class NCBITaxnomyInserter(object):
    
    def __init__(self, divisions_file_path, taxonomy_divisions_file_path):       
        
        self.included_divisions= {0:"Bacteria",3:"Phages",9:"Viruses", 11:"Environmental samples", 
                1:"Invertebrates", 4:"Plants and Fungi"}

        self.divisions_file_path= divisions_file_path
        self.taxonomy_divisions_file_path= taxonomy_divisions_file_path
        self.__init_database()
        
        if not self.init_tables():
            self.create_tables()
        


    def __init_database(self):    
        """
        creates the sqlite database instance and checks if the database exists in biodb.
        """
        database= create_database("sqlite:%s" % biodb_sql_db_path)
        print "Created storm database from %s." % biodb_sql_db_path
        self.store= Store(database)
        

    def init_tables(self):
        self.biodb_table= "biodb_ncbi"
        self.taxonomy_division_table = "biodb_ncbi_taxonomy_division"
        self.division_table= "biodb_ncbi_division"
      
        #### check if the db_name exists in the database
        table_list= [table[0] for table in self.store.execute('select tbl_name from SQLITE_MASTER')]
       
        return 0 if self.taxonomy_division_table not in table_list else 1 


    def create_tables(self):
        self.create_taxonomy_division_string='CREATE TABLE '+ self.taxonomy_division_table +' (taxonID INTEGER PRIMARY KEY, divisionID INTEGER, FOREIGN KEY (taxonID) REFERENCES '+ self.biodb_table+'(id), FOREIGN KEY (divisionID) REFERENCES '+ self.division_table +'(id) )'
        

        self.create_division_string='CREATE TABLE '+ self.division_table +' (id INTEGER PRIMARY KEY, name VARCHAR)'


        self.store.execute(self.create_taxonomy_division_string)
        self.store.execute(self.create_division_string)

    def insert_division(self, div_id, name):
        div= NCBIDivision()
        div.id = int(div_id)
        div.name= unicode(name)

        self.store.add(div)


    def insert_taxonomy_division(self, taxon_id, div_id):
        n_tax_div= NCBITaxonomyDivision()
        n_tax_div.taxonID= int(taxon_id)
        n_tax_div.divisionID= int(div_id)

        self.store.add(n_tax_div)


    def insert_divisions_from_file(self):
        with open(self.divisions_file_path) as div_file:
            for line in div_file:
                cols= line.rstrip('\n').split(sep)
                div_id= cols[0]
                name= cols[2]
                self.insert_division(div_id, name)

        self.store.commit()

    def insert_taxonomy_divisions_from_file(self):
        i=0
        with open(self.taxonomy_divisions_file_path) as tax_div_file:
            for line in tax_div_file:
                cols= line.rstrip('\n').split(sep)
                
                division_id= int(cols[4].strip())
                
                if division_id in self.included_divisions:
                    tax_id= cols[0].strip()
                    self.insert_taxonomy_division(tax_id, division_id)

                    self.store.commit()

                    i+=1
                    if i % 10000 == 0:
                        print "%d taxa inserted!" %i 
开发者ID:ecotox,项目名称:biodb,代码行数:91,代码来源:ncbi_taxonomy_inserter.py

示例10: StormStorageBackend

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]
class StormStorageBackend(StorageBackend):
    """Storage back-end based on the Storm ORM framework."""

    def __init__(self):
        self.store = None

    def set_config(self, **kwargs):
        """Set the configuration of this back-end."""
        uri = kwargs['uri']
        database = create_database(uri)
        self.store = Store(database)
        self.logger = logging.getLogger('StormStorageBackend')
        handler = logging.StreamHandler()
        formatter = logging.Formatter(kwargs['log_format'])
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        self.logger.setLevel(
            logging.__getattribute__(kwargs['log_level']))

    def create_node(self, node, jid, node_config):
        """Create a PubSub node with the given configuration.

        Creates the Node, NodeConfig, Affiliation and Subscription model for
        the given node.
        """
        self.logger.debug('Creating node %s for jid %s with config %s' %
            (node, jid, node_config))
        new_node = Node(node)
        self.store.add(new_node)
        config = copy.deepcopy(DEFAULT_CONFIG)
        config.update(node_config)
        for key, value in config.items():
            new_node_config = NodeConfig(node, key, value)
            new_node_config.updated = datetime.utcnow()
            self.store.add(new_node_config)
        affiliation = Affiliation(node, jid, u'owner', datetime.utcnow())
        self.store.add(affiliation)
        subscription = Subscription(node, jid, jid, u'subscribed',
                datetime.utcnow())
        self.store.add(subscription)

    def create_channel(self, jid):
        """Create a channel for the given JID.

        Creates all the required PubSub nodes that constitute a channel, with
        the appropriate permissions.
        """
        self.logger.debug('Creating channel for %s' % jid)
        creation_date = unicode(datetime.utcnow().isoformat())
        self.create_node(u'/user/%s/posts' % jid, jid,
            {u'channelType': u'personal',
                u'creationDate': creation_date,
                u'defaultAffiliation': u'publisher',
                u'description': u'buddycloud channel for %s' % jid,
                u'title': jid})
        self.create_node(u'/user/%s/geo/current' % jid, jid,
            {u'creationDate': creation_date,
                u'description': u'Where %s is at now' % jid,
                u'title': u'%s Current Location' % jid})
        self.create_node(u'/user/%s/geo/next' % jid, jid,
            {u'creationDate': creation_date,
                u'description': u'Where %s intends to go' % jid,
                u'title': u'%s Next Location' % jid})
        self.create_node(u'/user/%s/geo/previous' % jid, jid,
            {u'creationDate': creation_date,
                u'description': u'Where %s has been before' % jid,
                u'title': u'%s Previous Location' % jid})
        self.create_node(u'/user/%s/status' % jid, jid,
            {u'creationDate': creation_date,
                u'description': u'M000D',
                u'title': u'%s status updates' % jid})
        self.create_node(u'/user/%s/subscriptions' % jid, jid,
            {u'creationDate': creation_date,
                u'description': u'Browse my interests',
                u'title': u'%s subscriptions' % jid})
        self.store.commit()

    def get_node(self, node):
        """Get the requested PubSub node."""
        self.logger.debug('Getting node %s' % node)
        the_node = self.store.get(Node, node)
        self.logger.debug('Returning node %s' % the_node)
        return the_node

    def get_nodes(self):
        """Get a list of all the available PubSub nodes."""
        self.logger.debug('Getting list of available nodes.')
        node_list = self.store.find(Node)
        self.logger.debug('Returning list of available node %s' % node_list)
        return node_list

    def add_item(self, node, item_id, item):
        """Add an item to the requested PubSub node."""
        new_item = Item(node, unicode(item_id), datetime.utcnow(), item)
        self.store.add(new_item)
        self.store.commit()

    def shutdown(self):
        """Shut down this storage module - flush, commit and close the
        store."""
#.........这里部分代码省略.........
开发者ID:LarsDietrich,项目名称:buddycloud-server-python,代码行数:103,代码来源:__init__.py

示例11: TableReplacer

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]

#.........这里部分代码省略.........
        return None

    def get_right_sql_version(self, model_name, version):
        """
        @param model_name:
        @param version:
        @return:
            The SQL right for the stuff we've
        """

        modelobj = self.get_right_model(model_name, version)
        if not modelobj:
            return None

        right_query = generateCreateQuery(modelobj)
        return right_query

    def _perform_copy_list(self, table_name):
        objs_count = self.store_old.find(
            self.get_right_model(table_name, self.start_ver)
        ).count()
        log.msg('{} default {} migration assistant: #{}'.format(
            self.debug_info, table_name, objs_count))

        old_objects = self.store_old.find(self.get_right_model(table_name, self.start_ver))

        for old_obj in old_objects:
            new_obj = self.get_right_model(table_name, self.start_ver + 1)()

            # Storm internals simply reversed
            for _, v in new_obj._storm_columns.iteritems():
                setattr(new_obj, v.name, getattr(old_obj, v.name))

            self.store_new.add(new_obj)

        self.store_new.commit()

    def _perform_copy_single(self, table_name):
        log.msg('{} default {} migration assistant'.format(self.debug_info, table_name))

        old_obj = self.store_old.find(self.get_right_model(table_name, self.start_ver)).one()
        new_obj = self.get_right_model(table_name, self.start_ver + 1)()

        # Storm internals simply reversed
        for _, v in new_obj._storm_columns.iteritems():
            setattr(new_obj, v.name, getattr(old_obj, v.name))

        self.store_new.add(new_obj)
        self.store_new.commit()

    def migrate_Context(self):
        self._perform_copy_list("Context")

    def migrate_Node(self):
        self._perform_copy_single("Node")

    def migrate_User(self):
        self._perform_copy_list("User")

    def migrate_ReceiverTip(self):
        self._perform_copy_list("ReceiverTip")

    def migrate_WhistleblowerTip(self):
        self._perform_copy_list("WhistleblowerTip")

    def migrate_Comment(self):
开发者ID:nsfw,项目名称:GlobaLeaks,代码行数:70,代码来源:base_updater.py

示例12: TableReplacer

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]

#.........这里部分代码省略.........
        return None

    def get_right_sql_version(self, model_name, version):
        """
        @param model_name:
        @param version:
        @return:
            The SQL right for the stuff we've
        """

        modelobj = self.get_right_model(model_name, version)
        if not modelobj:
            return None

        right_query = generateCreateQuery(modelobj)
        return right_query

    def _perform_copy_list(self, table_name):
        models_count = self.store_old.find(
            self.get_right_model(table_name, self.start_ver)
        ).count()
        log.msg('{} default {} migration assistant: #{}'.format(
            self.debug_info, table_name, models_count))

        old_objects = self.store_old.find(self.get_right_model(table_name, self.start_ver))

        for old_obj in old_objects:
            new_obj = self.get_right_model(table_name, self.start_ver + 1)()

            # Storm internals simply reversed
            for _, v in new_obj._storm_columns.iteritems():
                setattr(new_obj, v.name, getattr(old_obj, v.name))

            self.store_new.add(new_obj)

        self.store_new.commit()

    def _perform_copy_single(self, table_name):
        log.msg('{} default {} migration assistant'.format(self.debug_info, table_name))

        old_obj = self.store_old.find(self.get_right_model(table_name, self.start_ver)).one()
        new_obj = self.get_right_model(table_name, self.start_ver + 1)()

        # Storm internals simply reversed
        for _, v in new_obj._storm_columns.iteritems():
            setattr(new_obj, v.name, getattr(old_obj, v.name))

        self.store_new.add(new_obj)
        self.store_new.commit()

    def migrate_Context(self):
        self._perform_copy_list("Context")

    def migrate_Node(self):
        self._perform_copy_single("Node")

    def migrate_User(self):
        self._perform_copy_list("User")

    def migrate_ReceiverTip(self):
        self._perform_copy_list("ReceiverTip")

    def migrate_WhistleblowerTip(self):
        self._perform_copy_list("WhistleblowerTip")

    def migrate_Comment(self):
开发者ID:RuanAragao,项目名称:GlobaLeaks,代码行数:70,代码来源:base_updater.py

示例13: Sale

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]
for description, price, date in [
    ('Cup of coffee', 2.04, today - datetime.timedelta(1)),
    ('Chocolate bar', 1.85, today - datetime.timedelta(40)),
    ('Candy',         0.99, today - datetime.timedelta(30)),
    ('Grape Juice',   3.38, today - datetime.timedelta(23)),
    ('Ice tea',       1.25, today - datetime.timedelta(10)),
    ('Cookies',       0.85, today - datetime.timedelta(5)),
    ('Noogies',       1.45, today - datetime.timedelta(2)),
    ('Chocolate bar', 1.85, today)]:

    s = Sale()
    s.description=unicode(description)
    s.price=price
    s.date=date
    store.add(s)
    store.flush()


class PurchaseViewer(gtk.Window):
    def __init__(self):
        gtk.Window.__init__(self)
        self.set_title('Purchases')
        self.search = SearchContainer(self.get_columns())
        self.search.set_summary_label('price')
        self.add(self.search)
        self._setup_searching()
        self._create_filters()

    def _setup_searching(self):
        self.query = StormQueryExecuter(store)
开发者ID:gxela,项目名称:kiwi-gtk,代码行数:32,代码来源:search_storm.py

示例14: Person

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]
	# instantiate with:
	#     instance = Person()
	#     instance.name = u'John'
	#     instance.age = 55
	def __init__( self, name, age ):
		self.name = name
		self.age = age
	
	def __repr__( self ):
		return '<Person (name=%s, age=%s)>' % (
			self.name,
			self.age,
		)

database = create_database('sqlite://:memory:')
store = Store(database)
store.execute('''CREATE TABLE person (
	id INTEGER PRIMARY KEY,
	name VARCHAR,
	age INTEGER
)''')

amy = Person( name=u'Amy', age=52 )
bob = Person( name=u'Bob', age=48 )

store.add( amy )
store.add( bob )

person = store.find(Person, Person.name == u'Bob').one()
print person
开发者ID:ippo615,项目名称:experiments,代码行数:32,代码来源:main.py

示例15: __init__

# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import add [as 别名]

#.........这里部分代码省略.........
        # This never want happen
        return None

    def get_right_sql_version(self, model_name, version):
        """
        @param model_name:
        @param version:
        @return:
            The SQL right for the stuff we've
        """

        modelobj = self.get_right_model(model_name, version)
        if not modelobj:
            return None

        right_query = generateCreateQuery(modelobj)
        return right_query

    def _perform_copy_list(self, table_name):

        print "%s default %s migration assistant: #%d" % (
            self.debug_info, table_name,
            self.store_old.find(self.get_right_model(table_name, self.start_ver)).count())

        old_objects = self.store_old.find(self.get_right_model(table_name, self.start_ver))

        for old_obj in old_objects:
            new_obj = self.get_right_model(table_name, self.start_ver + 1)()

            # Storm internals simply reversed
            for k, v in new_obj._storm_columns.iteritems():
                setattr(new_obj, v.name, getattr(old_obj, v.name) )

            self.store_new.add(new_obj)

        self.store_new.commit()

    def _perform_copy_single(self, table_name):
        print "%s default %s migration assistant" % (self.debug_info, table_name)

        old_obj = self.store_old.find(self.get_right_model(table_name, self.start_ver)).one()
        new_obj = self.get_right_model(table_name, self.start_ver + 1)()

        # Storm internals simply reversed
        for k, v in new_obj._storm_columns.iteritems():
            setattr(new_obj, v.name, getattr(old_obj, v.name) )

        self.store_new.add(new_obj)
        self.store_new.commit()

    def migrate_Context(self):
        self._perform_copy_list("Context")

    def migrate_Node(self):
        self._perform_copy_single("Node")

    def migrate_User(self):
        self._perform_copy_list("User")

    def migrate_ReceiverTip(self):
        self._perform_copy_list("ReceiverTip")

    def migrate_WhistleblowerTip(self):
        self._perform_copy_list("WhistleblowerTip")

    def migrate_Comment(self):
开发者ID:Acidburn0zzz,项目名称:GLBackend,代码行数:70,代码来源:base_updater.py


注:本文中的storm.locals.Store.add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。