當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。