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


Python connection.Connection类代码示例

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


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

示例1: check_write_conflict

 def check_write_conflict(self):
     s1 = ClientStorage(address=self.address)
     c1 = Connection(s1)
     r1 = c1.get_root()
     s1.s = FakeSocket('\0\0\0\0', STATUS_INVALID)
     r1._p_note_change()
     raises(WriteConflictError, c1.commit)
开发者ID:cfobel,项目名称:durus,代码行数:7,代码来源:utest_client_storage.py

示例2: test_delete

 def test_delete(self):
     connection = Connection(MemoryStorage())
     pd = PersistentDict((x, True) for x in range(10))
     connection.root['x'] = pd
     connection.commit()
     del pd[1]
     assert pd._p_is_unsaved()
开发者ID:ctismer,项目名称:durus,代码行数:7,代码来源:test_persistent_dict.py

示例3: interactive_client

def interactive_client(file, address, cache_size, readonly, repair,
                       startup):
    if file:
        storage = FileStorage(file, readonly=readonly, repair=repair)
        description = file
    else:
        socket_address = SocketAddress.new(address)
        wait_for_server(address=socket_address)
        storage = ClientStorage(address=socket_address)
        description = socket_address
    connection = Connection(storage, cache_size=cache_size)
    console_module = ModuleType('__console__')
    sys.modules['__console__'] = console_module
    namespace = {'connection': connection,
                 'root': connection.get_root(),
                 'get': connection.get,
                 'sys': sys,
                 'os': os,
                 'int8_to_str': int8_to_str,
                 'str_to_int8': str_to_int8,
                 'pp': pprint}
    vars(console_module).update(namespace)
    configure_readline(
        vars(console_module), os.path.expanduser("~/.durushistory"))
    console = InteractiveConsole(vars(console_module))
    if startup:
        src = '''with open('{fn}', 'rb') as _:
                     _ = compile(_.read(), '{fn}', 'exec')
                     exec(globals().pop('_'))
        '''.format(fn = os.path.expanduser(startup)).rstrip()
        console.runsource(src, '-stub-', 'exec')
    help = ('    connection -> the Connection\n'
            '    root       -> the root instance')
    console.interact('Durus %s\n%s' % (description, help))
开发者ID:ctismer,项目名称:durus,代码行数:34,代码来源:__main__.py

示例4: interactive_client

def interactive_client(file, host, port, cache_size, readonly, repair,
                       startup):
    if file:
        storage = FileStorage(file, readonly=readonly, repair=repair)
        description = file
    else:
        wait_for_server(host, port)
        storage = ClientStorage(host=host, port=port)
        description = "%s:%s" % (host, port)
    connection = Connection(storage, cache_size=cache_size)
    namespace = {'connection': connection,
                 'root': connection.get(0),
                 'get': connection.get,
                 'sys': sys,
                 'os': os,
                 'p64': p64,
                 'u64': u64,
                 'pp': pprint}
    configure_readline(namespace, os.path.expanduser("~/.durushistory"))
    console = InteractiveConsole(namespace)
    if startup:
        console.runsource('execfile("%s")' % os.path.expanduser(startup))
    help = ('    connection -> the connection\n'
            '    root       -> get(0)\n'
            '    get(oid)   -> get an object\n'
            '    pp(object) -> pretty-print')
    console.interact('Durus (%s)\n%s' % (description, help))
开发者ID:pruan,项目名称:TestDepot,代码行数:27,代码来源:client.py

示例5: interactive_client

def interactive_client(file, address, cache_size, readonly, repair,
                       startup, storage_class=None):
    if file:
        storage = get_storage(file, storage_class=storage_class,
                readonly=readonly, repair=repair)
        description = file
    else:
        socket_address = SocketAddress.new(address)
        wait_for_server(address=socket_address)
        storage = ClientStorage(address=socket_address)
        description = socket_address
    connection = Connection(storage, cache_size=cache_size)
    console_module = ModuleType('__console__')
    sys.modules['__console__'] = console_module
    namespace = {'connection': connection,
                 'root': connection.get_root(),
                 'get': connection.get,
                 'sys': sys,
                 'os': os,
                 'int8_to_str': int8_to_str,
                 'str_to_int8': str_to_int8,
                 'pp': pprint}
    vars(console_module).update(namespace)
    configure_readline(
        vars(console_module), os.path.expanduser("~/.durushistory"))
    console = InteractiveConsole(vars(console_module))
    if startup:
        console.runsource('execfile("%s")' % os.path.expanduser(startup))
    help = ('    connection -> the Connection\n'
            '    root       -> the root instance')
    console.interact('Durus %s\n%s' % (description, help))
开发者ID:nascheme,项目名称:durus,代码行数:31,代码来源:__main__.py

示例6: end_protocol_error

 def end_protocol_error(self):
     s1 = ClientStorage(address=self.address)
     c1 = Connection(s1)
     r1 = c1.get_root()
     s1.s = FakeSocket('\0\0\0\0?')
     r1._p_note_change()
     raises(ProtocolError, c1.commit)
开发者ID:cfobel,项目名称:durus,代码行数:7,代码来源:utest_client_storage.py

示例7: run_trials

def run_trials():
    numTrials = 3000
    gens = 1000
    from multiprocessing.pool import ThreadPool as Pool
    pool = Pool(50)

    jids = pool.map(f,[gens]*numTrials)
    print "Done spawning trials. Retrieving results..."

    results = pool.map(cloud_result, jids)
    firstLocusFreqsHists = zeros((numTrials,gens+1), dtype='float')
    lastLocusFreqsHists = zeros((numTrials,gens+1), dtype='float')
    print "Done retrieving results. Press Enter to serialize..."

    raw_input()

    for i, result in enumerate(results):
        firstLocusFreqsHists[i, :], lastLocusFreqsHists[i, :] = result

    with closing(FileStorage("soda_results.durus")) as durus:
        conn = Connection(durus)
        conn.get_root()[str(int(floor(time.time())))] = (firstLocusFreqsHists, lastLocusFreqsHists)
        conn.commit()

    pool.close()
    pool.join()
开发者ID:burjorjee,项目名称:speedyGApy,代码行数:26,代码来源:soda14.py

示例8: render_results

def render_results(timestamp=None):

    with closing(FileStorage("soda_results.durus")) as durus:
        conn = Connection(durus)
        db = conn.get_root()
        if not timestamp:
            timestamp = sorted(db.keys())[-1]
        firstLocusFreqsHists, lastLocusFreqsHists = db[timestamp]
    print "Done deserializing results. Plotting..."

    x = [(2, 'First', firstLocusFreqsHists, "effective"),
         (3, 'Last', lastLocusFreqsHists, "non-effective")]

    for i, pos, freqsHists, filename in x :
        freqsHists = freqsHists[:,:801]
        f = figure(i)
        hold(False)
        plot(transpose(freqsHists), color='grey')
        hold(True)
        maxGens = freqsHists.shape[1]-1
        plot([0, maxGens], [.05,.05], 'k--')
        plot([0, maxGens], [.95,.95], 'k--')
        axis([0, maxGens, 0, 1])
        xlabel('Generation')
        ylabel('1-Frequency of the '+pos+' Locus')
        f.canvas.draw()
        f.show()
        savefig(filename+'.png', format='png', dpi=200)
开发者ID:burjorjee,项目名称:speedyGApy,代码行数:28,代码来源:soda14.py

示例9: get_config

def get_config():
    connection = Connection(FileStorage("/var/tmp/test.durus"))
    root = connection.get_root()  # connection set as shown above.
    if not root.has_key("_pconfig"):
        cf = GenericConfiguration()
        root["_pconfig"] = cf
        root["_pconfig"]["default"] = SECTION()
        connection.commit()
    return root["_pconfig"]
开发者ID:xiangke,项目名称:pycopia,代码行数:9,代码来源:pconfig.py

示例10: open_document

def open_document(db_path):
    conn = Connection(FileStorage(db_path))
    db_root = conn.get_root()
    if 'doc' not in db_root:
        db_root['doc'] = Document()
        db_root['version'] = updates.current_version
        conn.commit()
    updates.do_updates(conn)
    h = DocumentHandler(conn)
    return h.doc
开发者ID:mgax,项目名称:notespace,代码行数:10,代码来源:document.py

示例11: _Settings

class _Settings(object):
    """Settings singleton object"""
    
    _appName = "MacTimeLog"
    
    _defaultSettings = {
        "dateFormat": "%m-%d-%Y %H:%M",
        "timeFormat": "%H:%M",
        "logDateTimeFormat": "at %H:%M",
        "workEndTime": "06:00",
        "workDayLength": 3600*8,
        "timerInterval": 1,
        "showWorkTill": False,
        "showDateTime": False,
        "logPath": "%s/%s" % (settingsFolder(_appName), "log.txt"),
        "projectsDataPath": "%s/%s" % (settingsFolder(_appName), "projects"),
        "slackingDataPath": "%s/%s" % (settingsFolder(_appName), "slacking"),
        "logEditCommand": "open -a TextEdit \"%s\"",
        "projectSeparator": "::",
        "selectedProject": "Default",
        "startPlaceholder": "__start__",
        "showNotification": False,
        "notificationTime": 40,
        "notificationRepeatTime": 10,
        "soundOnNotification": False,
        "showHelpMessageOnStart": True
    }

    _globalSettings = {}
    
    def __init__(self):
        self._settingsFile = "%s/%s" % (settingsFolder(self._appName), "settings")
        self._conn = Connection(FileStorage(self._settingsFile))
        self._globalSettings = self._conn.get_root()
        
    def get(self, key):
        """Return setting value by key"""
        if key in self._globalSettings:
            return self._globalSettings[key]
        elif key in self._defaultSettings:
            return self._defaultSettings[key]
        else:
            pass
        
    def set(self, key, value):
        """Set setting value by key"""
        self._globalSettings[key] = value
        
    def sync(self):
        self._conn.commit()

    def __del__(self):
        self.sync()
开发者ID:DMaiorino,项目名称:MacTimeLog,代码行数:53,代码来源:Settings.py

示例12: check_touch_every_reference

 def check_touch_every_reference(self):
     connection = Connection(self._get_storage())
     root = connection.get_root()
     root['a'] = Persistent()
     root['b'] = Persistent()
     from durus.persistent_list import PersistentList
     root['b'].c = PersistentList()
     connection.commit()
     touch_every_reference(connection, 'PersistentList')
     assert root['b']._p_is_unsaved()
     assert root['b'].c._p_is_unsaved()
     assert not root._p_is_unsaved()
     assert len(list(connection.get_cache())) == 4
开发者ID:Schevo,项目名称:durus,代码行数:13,代码来源:utest_connection.py

示例13: _Projects

class _Projects(object):
    """
    Class for managing project and autocompletes
    for each project
    """
    
    def __init__(self):
        self._conn = Connection(FileStorage(Settings.get("projectsDataPath")))
        self._data = self._conn.get_root()

        if not len(self._data.keys()):
            self._data["Default"] = PersistentDict(autocomplete=PersistentDict())
            self.sync()
    
    def get(self):
        """Return projects list"""
        return self._data.keys()
        
    def add(self, name):
        """Add new project"""
        self._data[unicode(name)] = PersistentDict(autocomplete=PersistentDict())
        self.sync()
        
    def remove(self, name):
        """Remove project"""
        del self._data[unicode(name)]
        
    def getAutocomleteList(self, name, appendix={}):
        """
        Return autocomplete list for project, if appendix 
        autocompletes was specified merge it with project autocompletes.
        """
        autocompDict = self._data[unicode(name)]["autocomplete"]
        autocompDict.update(appendix)
        sortedDict = sorted(autocompDict.items(), key=lambda (k, v):(v, k), reverse=True)
        return [a[0] for a in sortedDict]
        
    def addAutocomplete(self, projectName, taskName):
        """Add autocompleted task for peoject"""
        prj = self._data[projectName]
        if taskName not in prj["autocomplete"]:
            prj["autocomplete"][taskName] = 1
        else:
            prj["autocomplete"][taskName] += 1
        self.sync()
 
    def sync(self):
        self._conn.commit()
        
    def __del__(self):
        self.sync()
开发者ID:DMaiorino,项目名称:MacTimeLog,代码行数:51,代码来源:Projects.py

示例14: __init__

class TestBackend:

  def __init__(self, filename, mode):

    self.mode = mode

    if mode == "w":
      self.storage = FileStorage(filename)
      self.connection = Connection(self.storage)
      self.test_db_items = self.connection.get_root()

    elif mode == "r":
      self.storage = FileStorage(filename)
      self.connection = Connection(self.storage)
      self.test_db_items = self.connection.get_root()

      self.next_rec_num = 0   # Initialise next record counter
      self.num_records = len(self.test_db_items)

  def __setitem__(self, key, value):

    self.test_db_items[key] = value

  def __getitem__(self, key):

    return self.test_db_items[str(key)]

  def __len__(self):

    return len(self.test_db_items)

  def first(self):

    return self.test_db_items[0]

  def iteritems(self):

    while(self.next_rec_num < self.num_records):
      value = self.test_db_items[self.next_rec_num]
  
      self.next_rec_num += 1

      yield value

  def close(self):
    self.connection.commit()
    self.storage.close()

  def getTestDBItems(self):
    return self.test_db_items.values()
开发者ID:jialvarez,项目名称:persystems,代码行数:50,代码来源:pydurus.py

示例15: check_storage_tools

 def check_storage_tools(self):
     connection = Connection(self._get_storage())
     root = connection.get_root()
     root['a'] = Persistent()
     root['b'] = Persistent()
     connection.commit()
     index = get_reference_index(connection.get_storage())
     assert index == {
         int8_to_str(1): [int8_to_str(0)], int8_to_str(2): [int8_to_str(0)]}
     census = get_census(connection.get_storage())
     assert census == {as_bytes('PersistentDict'):1, as_bytes('Persistent'):2}
     references = list(gen_referring_oid_record(connection.get_storage(),
                                                int8_to_str(1)))
     assert references == [
         (int8_to_str(0), connection.get_storage().load(int8_to_str(0)))]
     class Fake(object):
         pass
     s = Fake()
     s.__class__ = Storage
     raises(RuntimeError, s.__init__)
     raises(NotImplementedError, s.load, None)
     raises(NotImplementedError, s.begin)
     raises(NotImplementedError, s.store, None, None)
     raises(NotImplementedError, s.end)
     raises(NotImplementedError, s.sync)
     g = s.gen_oid_record()
     raises(NotImplementedError, next, g)
开发者ID:Schevo,项目名称:durus,代码行数:27,代码来源:utest_connection.py


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