本文整理汇总了Python中storm.locals.Store.get方法的典型用法代码示例。如果您正苦于以下问题:Python Store.get方法的具体用法?Python Store.get怎么用?Python Store.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类storm.locals.Store
的用法示例。
在下文中一共展示了Store.get方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: StormORM
# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import get [as 别名]
class StormORM(ORM):
"""
Storm implementation of ORM super class.
"""
def __init__(self, uri=None, store=None):
'''
@param uri: Database URI following storm rules.
@param store: Storm store.
If uri is given a new store is instanciated and it is used
to execute the statements.
If both parameters are given the early created store overrides
the store given.
'''
from storm.locals import create_database, Store
self.uri = uri
self.store = store
if self.uri:
database = create_database(self.uri)
self.store = Store(database)
if not self.store:
raise Exception('None storm store')
self.attrParser = StormAttributeParser()
def _getObject(self, csvType, csvStatement):
"""
Retrieves the object to be used at statement execution.
@param csvType: The CSVType
@param csvStatement: The CSVStatement
@return: The object early instanciated (for insert statement) or
retrieved from database (for update or delete statements).
"""
typo = csvType.type
keys = csvType.keys
attributes = csvStatement.attributes
if csvStatement.action in [DELETE, UPDATE]:
if csvType.hasPrimaryKey:
return self.store.get(typo, attributes[ csvType.primaryKey[0] ])
else:
pred = And([Eq(typo, key, attributes[i]) for i,key in keys.iteritems()])
result = self.store.find(typo, pred)
if result.count() == 0:
return None
elif result.count() == 1:
return result.one()
else:
return [r for r in result]
elif csvStatement.action is INSERT:
return typo()
def executeStatement(self, csvType, csvStatement):
"""
Executes csv statements matched by the pair csvType, csvStatement.
@param csvType: The CSVType
@param csvStatement: The CSVStatement
@return: Total statements executed or raises a ValueError if the object retrieved with
the pair csvType, csvStatement is None.
"""
obj = self._getObject(csvType, csvStatement)
if not obj:
msg = 'Statement return None in line %d: %s' % (csvStatement.lineNumber, csvStatement.lineContent)
raise ValueError(msg)
objs = []
if type(obj) is list:
objs += obj
else:
objs.append(obj)
i = 0
for _obj in objs:
self._executeStatement(_obj, csvType, csvStatement)
i += 1
return i
def _executeStatement(self, obj, csvType, csvStatement):
"""
Executes a single csv statement
@param csvType: The CSVType
@param csvStatement: The CSVStatement
"""
keys = csvType.keys
attributes = csvType.attributes
values = csvStatement.attributes
if csvStatement.action is INSERT:
pairs = [(key, values[i]) for i,key in keys.iteritems()]
pairs += [(key, values[i]) for i,key in attributes.iteritems()]
for key, value in pairs:
setattr(obj, key, value)
self.store.add(obj)
elif csvStatement.action is UPDATE:
pairs = [(key, values[i]) for i,key in attributes.iteritems()]
#.........这里部分代码省略.........
示例2: StormStorageBackend
# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import get [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."""
#.........这里部分代码省略.........
示例3: PatchTest
# 需要导入模块: from storm.locals import Store [as 别名]
# 或者: from storm.locals.Store import get [as 别名]
class PatchTest(MockerTestCase):
def setUp(self):
super(PatchTest, self).setUp()
self.patchdir = self.makeDir()
self.pkgdir = os.path.join(self.patchdir, "mypackage")
os.makedirs(self.pkgdir)
f = open(os.path.join(self.pkgdir, "__init__.py"), "w")
f.write("shared_data = []")
f.close()
# Order of creation here is important to try to screw up the
# patch ordering, as os.listdir returns in order of mtime (or
# something).
for pname, data in [("patch_380.py", patch_test_1),
("patch_42.py", patch_test_0)]:
self.add_module(pname, data)
sys.path.append(self.patchdir)
self.filename = self.makeFile()
self.uri = "sqlite:///%s" % self.filename
self.store = Store(create_database(self.uri))
self.store.execute("CREATE TABLE patch "
"(version INTEGER NOT NULL PRIMARY KEY)")
self.assertFalse(self.store.get(Patch, (42)))
self.assertFalse(self.store.get(Patch, (380)))
import mypackage
self.mypackage = mypackage
# Create another connection just to keep track of the state of the
# whole transaction manager. See the assertion functions below.
self.another_store = Store(create_database("sqlite:"))
self.another_store.execute("CREATE TABLE test (id INT)")
self.another_store.commit()
self.prepare_for_transaction_check()
class Committer(object):
def commit(committer):
self.store.commit()
self.another_store.commit()
def rollback(committer):
self.store.rollback()
self.another_store.rollback()
self.committer = Committer()
self.patch_applier = PatchApplier(self.store, self.mypackage,
self.committer)
def tearDown(self):
super(PatchTest, self).tearDown()
self.committer.rollback()
sys.path.remove(self.patchdir)
for name in list(sys.modules):
if name == "mypackage" or name.startswith("mypackage."):
del sys.modules[name]
def add_module(self, module_filename, contents):
filename = os.path.join(self.pkgdir, module_filename)
file = open(filename, "w")
file.write(contents)
file.close()
def remove_all_modules(self):
for filename in os.listdir(self.pkgdir):
os.unlink(os.path.join(self.pkgdir, filename))
def prepare_for_transaction_check(self):
self.another_store.execute("DELETE FROM test")
self.another_store.execute("INSERT INTO test VALUES (1)")
def assert_transaction_committed(self):
self.another_store.rollback()
result = self.another_store.execute("SELECT * FROM test").get_one()
self.assertEquals(result, (1,),
"Transaction manager wasn't committed.")
def assert_transaction_aborted(self):
self.another_store.commit()
result = self.another_store.execute("SELECT * FROM test").get_one()
self.assertEquals(result, None,
"Transaction manager wasn't aborted.")
def test_apply(self):
"""
L{PatchApplier.apply} executes the patch with the given version.
"""
self.patch_applier.apply(42)
x = getattr(self.mypackage, "patch_42").x
self.assertEquals(x, 42)
self.assertTrue(self.store.get(Patch, (42)))
self.assertTrue("mypackage.patch_42" in sys.modules)
#.........这里部分代码省略.........