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


Python ndb.Key方法代码示例

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


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

示例1: setUp

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def setUp(self):
    super(LoanerEndpointsTest, self).setUp()
    self.service = FakeApiPermissionChecks()
    self.request = message_types.VoidMessage()

    user_model.Role.create(
        'technical_admin',
        role_permissions=[permissions.Permissions.AUDIT_SHELF],
        associated_group=loanertest.TECHNICAL_ADMIN_EMAIL)

    user_model.User(
        id=loanertest.SUPER_ADMIN_EMAIL, superadmin=True).put()
    user_model.User(
        id=loanertest.TECHNICAL_ADMIN_EMAIL,
        roles=[ndb.Key(user_model.Role, 'technical_admin')]).put()
    user_model.User(id=loanertest.USER_EMAIL).put() 
开发者ID:google,项目名称:loaner,代码行数:18,代码来源:auth_test.py

示例2: create

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def create(cls, name, title=None, body=None):
    """Creates a model and entity."""
    if not name:
      raise datastore_errors.BadValueError(
          'The Template name must not be empty.')
    entity = cls(title=title,
                 body=body)
    template = cls.get_by_id(name)
    if template is not None:
      raise datastore_errors.BadValueError(
          'Create template: A Template entity with name %r already exists.' %
          name)
    entity.key = ndb.Key(cls, name)
    entity.put()
    logging.info('Creating a new template with name %r.', name)
    cls.cached_templates = []
    return entity 
开发者ID:google,项目名称:loaner,代码行数:19,代码来源:template_model.py

示例3: create

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def create(cls, name, role_permissions=None, associated_group=None):
    """Creates a new role.

    Args:
      name: str, name of the new role.
      role_permissions: list|str|, zero or more Permissions to include.
      associated_group: str, name of the Google Group (or other permission
        container) used to associate this group of permissions to users.

    Returns:
      Created Role.

    Raises:
      CreateRoleError: If a role fails to be created.
    """
    if name == 'superadmin':
      raise CreateRoleError(_SUPERADMIN_RESERVED_ERROR)
    if cls.get_by_name(name):
      raise CreateRoleError(_ROLE_ALREADY_EXISTS, name)
    new_role = cls(
        key=ndb.Key(cls, name),
        permissions=role_permissions or [],
        associated_group=associated_group)
    new_role.put()
    return new_role 
开发者ID:google,项目名称:loaner,代码行数:27,代码来源:user_model.py

示例4: get_ndb_key

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def get_ndb_key(urlsafe_key):
  """Builds an ndb.Key from a urlsafe key.

  Args:
    urlsafe_key: str, A urlsafe ndb.Key to cast into an ndb.Key.

  Returns:
    An ndb.Key instance.

  Raises:
    endpoints.BadRequestException: if the creation of the ndb.Key fails.
  """
  try:
    return ndb.Key(urlsafe=urlsafe_key)
  except Exception:  # pylint: disable=broad-except
    raise endpoints.BadRequestException(_CORRUPT_KEY_MSG) 
开发者ID:google,项目名称:loaner,代码行数:18,代码来源:api_utils.py

示例5: post

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def post(self):
  data = self.request.body
  dataDict = marketserver.parsePostData(data)
  taskKey = int(dataDict.get('session', {}).get('correlationid', 0))
  task = ndb.Key(Task, taskKey).get()
  if not task:
   return self.error(404)
  if not task.completed and task.app:
   response = marketserver.getJsonInstallResponse('App', self.uri_for('appSpk', appId = task.app, _full = True))
  else:
   response = marketserver.getJsonResponse()
  task.completed = True
  task.response = data
  task.put()
  updateAppStats(dataDict)
  self.output(marketserver.constants.jsonMimeType, response) 
开发者ID:ma1co,项目名称:Sony-PMCA-RE,代码行数:18,代码来源:main.py

示例6: launch_lsh_calc

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def launch_lsh_calc(self):
        # store tweets and kick off run_lsh

        tw_from = self.cursor
        tw_till = len(self.tweets)
        dui = ndb.Key(urlsafe = self.duik).get()
        dui = dui.extend_tweets(self.tweets[tw_from:tw_till])
        self.cursor = len(self.tweets)

        if not self.matrix:
            Matrix._initialize()
            MatrixRow._initialize()
            self.matrix = Matrix.create(filename = dui.filename(), source = 'tweets', file_key = self.duik)
            if self.matrix:
                dui = dui.set_ds_key(self.matrix.ds_key)
        if self.matrix:
            timestamp = datetime.datetime.utcnow().isoformat()
            deferred.defer(run_lsh, self.duik, self.tweets[tw_from:tw_till], self.matrix.ds_key, tw_from, timestamp)
        else:
            frameinfo = getframeinfo(currentframe())
            logging.error('file %s, line %s Matrix is missing', frameinfo.filename, frameinfo.lineno+1) 
开发者ID:singhj,项目名称:locality-sensitive-hashing,代码行数:23,代码来源:read_tweepy.py

示例7: init_zoneinfo

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def init_zoneinfo():
    """
    Add each zone info to the datastore. This will overwrite existing zones.

    This must be called before the AppengineTimezoneLoader will work.
    """
    import os, logging
    from zipfile import ZipFile
    zoneobjs = []

    zoneinfo_path = os.path.abspath(os.path.join(os.path.dirname(__file__),
      'zoneinfo.zip'))

    with ZipFile(zoneinfo_path) as zf:
        for zfi in zf.filelist:
            key = ndb.Key('Zoneinfo', zfi.filename, namespace=NDB_NAMESPACE)
            zobj = Zoneinfo(key=key, data=zf.read(zfi))
            zoneobjs.append(zobj)

    logging.info("Adding %d timezones to the pytz-appengine database" %
        len(zoneobjs)
        )

    ndb.put_multi(zoneobjs) 
开发者ID:Schibum,项目名称:sndlatr,代码行数:26,代码来源:__init__.py

示例8: open_resource

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def open_resource(name):
    """Load the object from the datastore"""
    import logging
    from cStringIO import StringIO
    try:
        data = ndb.Key('Zoneinfo', name, namespace=NDB_NAMESPACE).get().data
    except AttributeError:
        # Missing zone info; test for GMT - which would be there if the 
        # Zoneinfo has been initialized.
        if ndb.Key('Zoneinfo', 'GMT', namespace=NDB_NAMESPACE).get():
          # the user asked for a zone that doesn't seem to exist.
          logging.exception("Requested zone '%s' is not in the database." %
              name)
          raise

        # we need to initialize the database
        init_zoneinfo()
        return open_resource(name)

    return StringIO(data) 
开发者ID:Schibum,项目名称:sndlatr,代码行数:22,代码来源:__init__.py

示例9: push_important_news

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def push_important_news():
    key = request.values.get('key')
    news = ndb.Key(urlsafe=key).get()
    form_fields = {
        "token": app.config["PUSHOVER_APP_KEY"],
        "user": app.config["PUSHOVER_USER_KEY"],
        "message": news.summary.encode("utf-8"),
        "url": news.link.encode("utf-8"),
        "url_title": u"点击访问正文".encode("utf-8"),
        "title": news.title.encode("utf-8"),
    }
    form_data = urllib.urlencode(form_fields)
    urlfetch.fetch(url=app.config["PUSH_OVER_URL"],
                   payload=form_data,
                   method=urlfetch.POST,
                   headers={'Content-Type': 'application/x-www-form-urlencoded'},
                   follow_redirects=False,
                   validate_certificate=False)
    return "Done", 200 
开发者ID:liantian-cn,项目名称:RSSNewsGAE,代码行数:21,代码来源:background.py

示例10: test_correctly_fetches_id_name_rebels

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def test_correctly_fetches_id_name_rebels(self):
        query = '''
            query RebelsQuery {
              rebels {
                id,
                name
              }
            }
          '''
        expected = {
            'rebels': {
                'id': to_global_id('Faction', ndb.Key('Faction', 'rebels').urlsafe()),
                'name': 'Alliance to Restore the Republic'
            }
        }
        result = schema.execute(query)
        self.assertFalse(result.errors, msg=str(result.errors))
        self.assertDictEqual(result.data, expected) 
开发者ID:graphql-python,项目名称:graphene-gae,代码行数:20,代码来源:test_object_identification.py

示例11: test_correctly_refetches_rebels

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def test_correctly_refetches_rebels(self):
        rebels_key = to_global_id('Faction', ndb.Key('Faction', 'rebels').urlsafe())
        query = '''
            query RebelsRefetchQuery {
              node(id: "%s") {
                id
                ... on Faction {
                  name
                }
              }
            }
          ''' % rebels_key

        expected = {
            'node': {
                'id': rebels_key,
                'name': 'Alliance to Restore the Republic'
            }
        }
        result = schema.execute(query)
        self.assertFalse(result.errors, msg=str(result.errors))
        self.assertDictEqual(result.data, expected) 
开发者ID:graphql-python,项目名称:graphene-gae,代码行数:24,代码来源:test_object_identification.py

示例12: test_correctly_fetches_id_name_empire

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def test_correctly_fetches_id_name_empire(self):
        empire_key = to_global_id('Faction', ndb.Key('Faction', 'empire').urlsafe())
        query = '''
          query EmpireQuery {
            empire {
              id
              name
            }
          }
        '''
        expected = {
            'empire': {
                'id': empire_key,
                'name': 'Galactic Empire'
            }
        }
        result = schema.execute(query)
        self.assertFalse(result.errors, msg=str(result.errors))
        self.assertDictEqual(result.data, expected) 
开发者ID:graphql-python,项目名称:graphene-gae,代码行数:21,代码来源:test_object_identification.py

示例13: test_correctly_refetches_id_name_empire

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def test_correctly_refetches_id_name_empire(self):
        empire_key = to_global_id('Faction', ndb.Key('Faction', 'empire').urlsafe())
        query = '''
            query EmpireRefetchQuery {
              node(id: "%s") {
                id
                ... on Faction {
                  name
                }
              }
            }
          ''' % empire_key
        expected = {
            'node': {
                'id': empire_key,
                'name': 'Galactic Empire'
            }
        }
        result = schema.execute(query)
        self.assertFalse(result.errors, msg=str(result.errors))
        self.assertDictEqual(result.data, expected) 
开发者ID:graphql-python,项目名称:graphene-gae,代码行数:23,代码来源:test_object_identification.py

示例14: to_instance

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def to_instance(cls, json_attributes):
        keys_and_properties = cls._get_keys_and_properties()

        ancestor_kind, ancestor_key = cls.ancestor()
        if not ancestor_kind:
            instance = cls()
        else:
            if ancestor_key not in json_attributes:
                raise Exception('the ancestor key was not found')

            instance = cls(parent=ndb.Key(ancestor_kind, json_attributes[ancestor_key]))
            del json_attributes[ancestor_key]

        for field_name in json_attributes.keys():
            value = json_attributes[field_name]
            if field_name in keys_and_properties:
                json_value = json_attributes[field_name]
                kind, repeated = keys_and_properties[field_name]
                if repeated:
                    value = [ndb.Key(kind, val) for val in json_value]
                else:
                    value = ndb.Key(kind, json_value)

            setattr(instance, field_name, value)
        return instance 
开发者ID:felipevolpone,项目名称:ray,代码行数:27,代码来源:all.py

示例15: story_redirect

# 需要导入模块: from google.appengine.ext import ndb [as 别名]
# 或者: from google.appengine.ext.ndb import Key [as 别名]
def story_redirect(short_id):
  """Redirect to story url"""
  try:
    story_id = str(shortener.decode(short_id))
  except:
    return abort(400)
  redirect_url = memcache.get(story_id)
  if not redirect_url:
    story = ndb.Key(StoryPost, story_id).get()
    if not story:
      return make_response('<h1>Service Unavailable</h1><p>Try again later</p>', 503, {'Retry-After': 5})
    story.add_memcache()
    redirect_url = story.url
  return redirect(redirect_url) 
开发者ID:phil-r,项目名称:hackernewsbot,代码行数:16,代码来源:main.py


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