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


Python Connection.collection_names方法代码示例

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


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

示例1: DatastoreMongoStub

# 需要导入模块: from pymongo.connection import Connection [as 别名]
# 或者: from pymongo.connection.Connection import collection_names [as 别名]

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

    def translate_direction(ae_dir):
      if ae_dir == 1:
        return pymongo.ASCENDING
      elif ae_dir == 2:
        return pymongo.DESCENDING
      raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
                                             'Weird direction.')

    collection = index.definition().entity_type()
    spec = []
    for prop in index.definition().property_list():
      spec.append((translate_name(prop.name()), translate_direction(prop.direction())))

    return (collection, spec)

  def _Dynamic_AllocateIds(self, allocate_ids_request, allocate_ids_response):
    model_key = allocate_ids_request.model_key()
    size = allocate_ids_request.size()

    start = self.intid.get()
    for i in xrange(size-1):
        self.intid.get()
    end = self.intid.get()

    allocate_ids_response.set_start(start)
    allocate_ids_response.set_end(end)

  def __has_index(self, index):
    (collection, spec) = self.__collection_and_spec_for_index(index)
    if self.__db[collection]._gen_index_name(spec) in self.__db[collection].index_information().keys():
      return True
    return False

  def _Dynamic_CreateIndex(self, index, id_response):
    if index.id() != 0:
      raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
                                             'New index id must be 0.')
    elif self.__has_index(index):
      logging.getLogger().info(index)
      raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
                                             'Index already exists.')

    (collection, spec) = self.__collection_and_spec_for_index(index)

    if spec: # otherwise it's probably an index w/ just an ancestor specifier
      self.__db[collection].create_index(spec)
      if self.__db.error():
        raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
                                               "Error creating index. Maybe too many indexes?")

    # NOTE just give it a dummy id. we don't use these for anything...
    id_response.set_value(1)

  def _Dynamic_GetIndices(self, app_str, composite_indices):
    if app_str.value() != self.__db.name():
      raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
                                             "Getting indexes for a different app unsupported.")

    def from_index_name(name):
      elements = name.split("_")
      index = []
      while len(elements):
        if not elements[0]:
          elements = elements[1:]
          elements[0] = "_" + elements[0]
        index.append((elements[0], int(elements[1])))
        elements = elements[2:]
      return index

    for collection in self.__db.collection_names():
      info = self.__db[collection].index_information()
      for index in info.keys():
        index_pb = entity_pb.CompositeIndex()
        index_pb.set_app_id(self.__db.name())
        index_pb.mutable_definition().set_entity_type(collection)
        index_pb.mutable_definition().set_ancestor(False)
        index_pb.set_state(2) # READ_WRITE
        index_pb.set_id(1) # bogus id
        for (k, v) in from_index_name(index):
          if k == "_id":
            k = "__key__"
          p = index_pb.mutable_definition().add_property()
          p.set_name(k)
          p.set_direction(v == pymongo.ASCENDING and 1 or 2)
        composite_indices.index_list().append(index_pb)

  def _Dynamic_UpdateIndex(self, index, void):
    logging.log(logging.WARN, 'update index unsupported')

  def _Dynamic_DeleteIndex(self, index, void):
    (collection, spec) = self.__collection_and_spec_for_index(index)
    if not spec:
      return

    if not self.__has_index(index):
      raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
                                             "Index doesn't exist.")
    self.__db[collection].drop_index(spec)
开发者ID:TheProjecter,项目名称:twistedae,代码行数:104,代码来源:datastore_mongo_stub.py

示例2: DatastoreMongoStub

# 需要导入模块: from pymongo.connection import Connection [as 别名]
# 或者: from pymongo.connection.Connection import collection_names [as 别名]
class DatastoreMongoStub(apiproxy_stub.APIProxyStub):
  """Persistent stub for the Python datastore API, using MongoDB to persist.

  A DatastoreMongoStub instance handles a single app's data.
  """

  def __init__(self,
               app_id,
               datastore_file=None,
               require_indexes=False,
               service_name='datastore_v3'):
    """Constructor.

    Initializes the datastore stub.

    Args:
      app_id: string
      datastore_file: ignored
      require_indexes: bool, default False.  If True, composite indexes must
          exist in index.yaml for queries that need them.
      service_name: Service name expected for all calls.
    """
    super(DatastoreMongoStub, self).__init__(service_name)

    assert isinstance(app_id, basestring) and app_id != ''
    self.__app_id = app_id
    self.__require_indexes = require_indexes
    self.__trusted = True

    # TODO should be a way to configure the connection
    self.__db = Connection()[app_id]

    # NOTE our query history gets reset each time the server restarts...
    # should this be fixed?
    self.__query_history = {}

    self.__next_index_id = 1
    self.__indexes = {}
    self.__index_lock = threading.Lock()

    self.__cursor_lock = threading.Lock()
    self.__next_cursor = 1
    self.__queries = {}

    self.__id_lock = threading.Lock()
    self.__id_map = {}

    # Transaction support
    self.__next_tx_handle = 1
    self.__tx_writes = {}
    self.__tx_deletes = set()
    self.__tx_actions = []
    self.__tx_lock = threading.Lock()

  def Clear(self):
    """Clears the datastore.

    This is mainly for testing purposes and the admin console.
    """
    for name in self.__db.collection_names():
      if not name.startswith('system.'):
        self.__db.drop_collection(name)
    self.__queries = {}
    self.__query_history = {}
    self.__indexes = {}
    self.__id_map = {}
    self.__next_tx_handle = 1
    self.__tx_writes = {}
    self.__tx_deletes = set()
    self.__tx_actions = []

    self.__db.datastore.drop()

  def MakeSyncCall(self, service, call, request, response):
    """ The main RPC entry point. service must be 'datastore_v3'.

    So far, the supported calls are 'Get', 'Put', 'Delete', 'RunQuery', 'Next',
    and 'AllocateIds'.
    """
    self.AssertPbIsInitialized(request)

    super(DatastoreMongoStub, self).MakeSyncCall(
        service, call, request, response)

    self.AssertPbIsInitialized(response)

  def AssertPbIsInitialized(self, pb):
    """Raises an exception if the given PB is not initialized and valid."""
    explanation = []
    assert pb.IsInitialized(explanation), explanation
    pb.Encode()

  def QueryHistory(self):
    """Returns a dict that maps Query PBs to times they've been run."""

    return dict((pb, times) for pb, times in self.__query_history.items()
                if pb.app() == self.__app_id)

  def __collection_for_key(self, key):
    collection = key.path().element(-1).type()
#.........这里部分代码省略.........
开发者ID:fajoy,项目名称:typhoonae,代码行数:103,代码来源:datastore_mongo_stub.py


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