本文整理汇总了Python中twistar.registry.Registry类的典型用法代码示例。如果您正苦于以下问题:Python Registry类的具体用法?Python Registry怎么用?Python Registry使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Registry类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, inst, propname, givenargs):
"""
Constructor.
@param inst: The L{DBObject} instance.
@param propname: The property name in the L{DBObject} instance that
results in this class being created.
@param givenargs: Any arguments given (through the use of a C{dict}
in the class variable in L{DBObject} rather than a string to describe
the relationship). The given args can include, for all relationships,
a C{class_name}. Depending on the relationship, C{association_foreign_key}
and C{foreign_key} might also be used.
"""
self.infl = Inflector()
self.inst = inst
self.dbconfig = Registry.getConfig()
## Set args
self.args = {
'class_name': propname,
'association_foreign_key': self.infl.foreignKey(self.infl.singularize(propname)),
'foreign_key': self.infl.foreignKey(self.inst.__class__.__name__),
'polymorphic': False
}
self.args.update(givenargs)
otherklassname = self.infl.classify(self.args['class_name'])
if not self.args['polymorphic']:
self.otherklass = Registry.getClass(otherklassname)
self.othername = self.args['association_foreign_key']
self.thisclass = self.inst.__class__
self.thisname = self.args['foreign_key']
示例2: setup
def setup(cls, database):
Log.info("Initializing database")
# create the database connection pool
# sqlite requires that foreign key support be turned on with every connection
# to ensure that we have this turned on we use only one connection
Registry.DBPOOL = adbapi.ConnectionPool('sqlite3', database=database, check_same_thread=False, cp_max=1)
# register our classes with the registry
Registry.register(Record, Measurement)
示例3: setUp
def setUp(self, config_basename="test.conf"):
configfile = os.path.join(
os.path.dirname(inspect.getsourcefile(TestBase)),
config_basename
)
config.read_config(configfile)
Registry.DBPOOL = adbapi.ConnectionPool(config.dbtype, **config.dbparams)
Registry.register(models.Cracker, models.Report, models.Legacy)
yield database.clean_database(quiet=True)
main.configure_logging()
示例4: find
def find(klass, id=None, where=None, group=None, limit=None, orderby=None):
"""
Find instances of a given class.
@param id: The integer of the C{klass} to find. For instance, C{Klass.find(1)}
will return an instance of Klass from the row with an id of 1 (unless it isn't
found, in which case C{None} is returned).
@param where: A C{list} whose first element is the string version of the
condition with question marks in place of any parameters. Further elements
of the C{list} should be the values of any parameters specified. For instance,
C{['first_name = ? AND age > ?', 'Bob', 21]}.
@param group: A C{str} describing the grouping, like C{group='first_name'}.
@param limit: An C{int} specifying the limit of the results. If this is 1,
then the return value will be either an instance of C{klass} or C{None}.
@param orderby: A C{str} describing the ordering, like C{orderby='first_name DESC'}.
@return: A C{Deferred} which returns the following to a callback:
If id is specified (or C{limit} is 1) then a single
instance of C{klass} will be returned if one is found that fits the criteria, C{None}
otherwise. If id is not specified and C{limit} is not 1, then a C{list} will
be returned with all matching results.
"""
config = Registry.getConfig()
d = config.select(klass.tablename(), id, where, group, limit, orderby)
return d.addCallback(createInstances, klass)
示例5: commit
def commit(self):
self._assertCorrectThread()
if not self._parent.is_active:
raise TransactionError("This transaction is inactive")
Registry.getConfig().txnGuard.txn = self._actual_parent
self._do_commit()
self.is_active = False
示例6: rollback
def rollback(self):
self._assertCorrectThread()
if not self._parent.is_active:
return
Registry.getConfig().txnGuard.txn = self._actual_parent
self._do_rollback()
self.is_active = False
示例7: _transaction
def _transaction(txn, args, kwargs):
config = Registry.getConfig()
config.txn = txn
# get the result of the functions *synchronously*, since this is in a transaction
try:
result = threads.blockingCallFromThread(reactor, interaction, txn, *args, **kwargs)
config.txn = None
return result
except Exception, e:
config.txn = None
raise TransactionError(str(e))
示例8: deleteAll
def deleteAll(klass, where=None, transaction=None):
"""
Delete all instances of C{klass} in the database.
@param where: Conditionally delete instances. This parameter is of the same form
found in L{find}.
@return: A C{Deferred}.
"""
config = Registry.getConfig()
tablename = klass.tablename()
return config.delete(tablename, where, transaction)
示例9: test_refresh
def test_refresh(self):
dateklass = Registry.getDBAPIClass("Date")
args = {'first_name': "a", "last_name": "b", "age": 10}
u = yield User(**args).save()
# mess up the props, then refresh
u.first_name = "something different"
u.last_name = "another thing"
yield u.refresh()
for key, value in args.items():
self.assertEqual(getattr(u, key), value)
示例10: count
def count(klass, where=None):
"""
Count instances of a given class.
@param where: An optional C{list} whose first element is the string version of the
condition with question marks in place of any parameters. Further elements
of the C{list} should be the values of any parameters specified. For instance,
C{['first_name = ? AND age > ?', 'Bob', 21]}.
@return: A C{Deferred} which returns the total number of db records to a callback.
"""
config = Registry.getConfig()
return config.count(klass.tablename(), where=where)
示例11: test_update
def test_update(self):
dateklass = Registry.getDBAPIClass("Date")
args = {'first_name': "a", "last_name": "b", "age": 10}
u = yield User(**args).save()
args = {'first_name': "b", "last_name": "a", "age": 100}
for key, value in args.items():
setattr(u, key, value)
yield u.save()
u = yield User.find(u.id)
for key, value in args.items():
self.assertEqual(getattr(u, key), value)
示例12: deleteAll
def deleteAll(klass, where=None):
"""
Delete all instances of C{klass} in the database without instantiating the records
first or invoking callbacks (L{beforeDelete} is not called). This will run a single
SQL DELETE statement in the database.
@param where: Conditionally delete instances. This parameter is of the same form
found in L{find}.
@return: A C{Deferred}.
"""
config = Registry.getConfig()
tablename = klass.tablename()
return config.delete(tablename, where)
示例13: connect
def connect(cls, connection, *args, **kwargs):
"This is how we instantiate a DatastoreSQL object with connection"
obj = cls(connection, *args, **kwargs)
Registry.DBPOOL = adbapi.ConnectionPool(
'pyodbc',
obj.config['connection'],
autocommit=True,
cp_reconnect=True
)
obj.raw_db = Registry.DBPOOL # Accessible if we need *really* low-level access to DB.
obj.db = Registry.getConfig()
return obj
示例14: sendMessage
def sendMessage(subject, body, sender_id, receiver_id):
now = datetime.now()
Timestamp = Registry.getDBAPIClass("Timestamp")
# save message to datastore
message = Message(
subject=subject,
body=body,
sender_id=sender_id,
receiver_id=receiver_id,
sent_at=Timestamp(now.year, now.month, now.day, now.hour, now.minute, now.second)
)
message.save()
# js client is subscribed to topic with name inbox_user_<user_id> so it will publish to their list
self.publish('com.vik.inbox_user_' + str(message.receiver_id), formatMessage(message))
示例15: transaction
def transaction(func=None, nested=False, thread_check=True):
"""Starts a new transaction.
A Transaction object returned by this function can be used as a context manager,
which will atomatically be commited or rolledback if an exception is raised.
Transactions must only be used in db threads. This behaviour can be overriden by setting the
'thread_check' to False, allowing transactions to be started in arbitrary threads which is
useful to e.g simplify testcases.
If this function is used as decorator, the decorated function will be executed in a db thread and
gets the Transaction passed as first argument. Decorated functions are allowed to return Deferreds.
E.g:
@transaction
def someFunc(txn, param1):
# Runs in a db thread
d = someFunc(1) # will be calledback (in mainthread) when someFunc returns
You have to make sure, that you use blockingCallFromThread() or use synchronization if you need to
interact with code which runs in the mainthread. Also care has to be taken when waiting for Deferreds.
You must assure that the callbacks will be invoked from the db thread.
Per default transactions can be nested: Commiting such a "nested" transaction will simply do nothing,
but a rollback on it will rollback the outermost transaction. This allow creation of functions which will
either create a new transaction or will participate in an already ongoing tranaction which is handy for library code.
SAVEPOINT transactions can be used by either setting the 'nested' flag to true or by calling the 'nested_transaction' function.
"""
if nested and Registry.DBPOOL.dbapi.__name__ == "sqlite3":
# needs some modification on our side, see:
# http://docs.sqlalchemy.org/en/latest/dialects/sqlite.html#serializable-isolation-savepoints-transactional-ddl
raise NotImplementedError("sqlite currently not supported")
if func is None:
conn_pool = Registry.DBPOOL
cfg = Registry.getConfig()
if cfg.txnGuard.txn is None:
conn = conn_pool.connectionFactory(conn_pool)
return _RootTransaction(conn_pool, conn, thread_check=thread_check)
elif nested:
return _SavepointTransaction(cfg.txnGuard.txn, thread_check=thread_check)
else:
return _Transaction(cfg.txnGuard.txn, thread_check=thread_check)
else:
return _transaction_dec(func, functools.partial(transaction, nested=nested, thread_check=thread_check))