• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python registry.Registry类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twistar.registry.Registry的典型用法代码示例。如果您正苦于以下问题:Python Registry类的具体用法?Python Registry怎么用?Python Registry使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Registry类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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']
开发者ID:ChillingChua,项目名称:twistar,代码行数:34,代码来源:relationships.py


示例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)
开发者ID:treidel,项目名称:collection,代码行数:8,代码来源:database.py


示例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()
开发者ID:janpascal,项目名称:denyhosts_sync,代码行数:13,代码来源:base.py


示例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)
开发者ID:eallik,项目名称:twistar,代码行数:29,代码来源:dbobject.py


示例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
开发者ID:Paranaix,项目名称:twistar,代码行数:9,代码来源:transaction.py


示例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
开发者ID:Paranaix,项目名称:twistar,代码行数:9,代码来源:transaction.py


示例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))
开发者ID:yombo,项目名称:twistar,代码行数:11,代码来源:utils.py


示例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)
开发者ID:flaviogrossi,项目名称:twistar,代码行数:12,代码来源:dbobject.py


示例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)
开发者ID:VoiSmart,项目名称:twistar,代码行数:12,代码来源:test_dbobject.py


示例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)
开发者ID:eallik,项目名称:twistar,代码行数:13,代码来源:dbobject.py


示例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)
开发者ID:VoiSmart,项目名称:twistar,代码行数:13,代码来源:test_dbobject.py


示例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)
开发者ID:eallik,项目名称:twistar,代码行数:14,代码来源:dbobject.py


示例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
开发者ID:jdrago999,项目名称:lightning,代码行数:14,代码来源:sql.py


示例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))
开发者ID:vik-singh,项目名称:inbox,代码行数:16,代码来源:inbox.py


示例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))
开发者ID:Paranaix,项目名称:twistar,代码行数:47,代码来源:transaction.py


示例16: __init__

    def __init__(self, **kwargs):
        """
        Constructor.  DO NOT OVERWRITE.  Use the L{DBObject.afterInit} method.
        
        @param kwargs: An optional dictionary containing the properties that
        should be initially set for this object.

        @see: L{DBObject.afterInit}
        """
        self.id = None
        self._deleted = False
        self.errors = Errors()
        self.updateAttrs(kwargs)
        self._config = Registry.getConfig()

        if self.__class__.RELATIONSHIP_CACHE is None:
            self.__class__.initRelationshipCache()
开发者ID:eallik,项目名称:twistar,代码行数:17,代码来源:dbobject.py


示例17: test_creation

    def test_creation(self):
        # test creating blank object 
        u = yield User().save()
        self.assertTrue(type(u.id) == int or type(u.id) == long)

        # test creating object with props that don't correspond to columns
        u = yield User(a_fake_column="blech").save()
        self.assertTrue(type(u.id) == int or type(u.id) == long)        

        # Test table doesn't exist
        f = FakeObject(blah = "something")
        self.failUnlessFailure(f.save(), ImaginaryTableError)

        dateklass = Registry.getDBAPIClass("Date")
        args = {'first_name': "a", "last_name": "b", "age": 10, "dob": dateklass(2000, 1, 1)}
        u = yield User(**args).save()
        for key, value in args.items():
            self.assertEqual(getattr(u, key), value)
开发者ID:VoiSmart,项目名称:twistar,代码行数:18,代码来源:test_dbobject.py


示例18: __init__

    def __init__(self, parent, thread_check=True):
        # Transactions must be started in db thread unless explicitely permitted
        if thread_check and threading.current_thread() not in Registry.DBPOOL.threadpool.threads:
            raise TransactionError("Transaction must only be started in a db pool thread")

        if parent is None:
            self._root = self
        else:
            self._root = parent._root

        self._actual_parent = parent
        self.is_active = True
        self._threadId = threadable.getThreadID()
        self._savepoint_seq = 0

        if not self._parent.is_active:
            raise TransactionError("Parent transaction is inactive")

        Registry.getConfig().txnGuard.txn = self
开发者ID:Paranaix,项目名称:twistar,代码行数:19,代码来源:transaction.py


示例19: get_polymorphic

 def get_polymorphic(row):
     kid = getattr(row, "%s_id" % self.args['class_name'])
     kname = getattr(row, "%s_type" % self.args['class_name'])
     return Registry.getClass(kname).find(kid)
开发者ID:ChillingChua,项目名称:twistar,代码行数:4,代码来源:relationships.py


示例20: FakeObject

    HABTM = ['users']    

class FakeObject(DBObject):
    pass

class Coltest(DBObject):
    pass

class Boy(DBObject):
    HASMANY = [{'name': 'nicknames', 'as': 'nicknameable'}]

class Girl(DBObject):
    HASMANY = [{'name': 'nicknames', 'as': 'nicknameable'}]    

class Nickname(DBObject):
    BELONGSTO = [{'name': 'nicknameable', 'polymorphic': True}]

class Pen(DBObject):
    pass

class Table(DBObject):
    HABTM = ['pens']
    HASMANY = ['rubbers']

class Rubber(DBObject):
    pass

Registry.register(Picture, User, Comment, Avatar, FakeObject, FavoriteColor)
Registry.register(Boy, Girl, Nickname)
Registry.register(Pen, Table, Rubber)
开发者ID:davec82,项目名称:twistar,代码行数:30,代码来源:utils.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python twisted._checkRequirements函数代码示例发布时间:2022-05-27
下一篇:
Python twindb_backup.LOG类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap