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


Python db.Key类代码示例

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


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

示例1: get

    def get(self):
        user = users.get_current_user()
        r = FlowerbedAdd()
        if self.request.get('lat') and self.request.get('lon'):
            #TODO: check if flowerbed is far enough from others
            #TODO: check if flowerbed is close enough to user
            lat = int(self.request.get('lat')) / 1000000.0
            lon = int(self.request.get('lon')) / 1000000.0
            gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id())
            gamer_hash = hashlib.md5(user.user_id() + SALT).hexdigest()
            r.timestamp = int(time.time())
            #get backpack
            bp_beds = GqlQuery('SELECT * FROM Backpack WHERE ANCESTOR IS :1 AND name=:2', gamer_key, 'flowerbed').get()
            if bp_beds.amount:
                #lower backpack
                bp_beds.amount -= 1
                bp_beds.put()

                #add flowerbed
                point = GeoPt(lat, lon)
                cell = geocell.compute(point, RULES['GEO_RESOLUTION'])
                flowerbed = kloombaDb.Flowerbed(parent=Key.from_path(kloombaDb.Flowerbed.kind(), cell))
                flowerbed.point = point
                flowerbed.tile = cell
                flowerbed.owner = user.user_id()
                flowerbed.owner_public_id = gamer_hash
                flowerbed.put()

                #save to memcache
                memcache.set(str(flowerbed.key()), flowerbed)

                #add possession
                possession = kloombaDb.Possession(parent=gamer_key)
                possession.flowerbed = flowerbed
                possession.put()

                backpack = GqlQuery('SELECT * FROM Backpack WHERE ANCESTOR IS :1', gamer_key).run()

                #set timestamps
                r.flowerbed.timestamp = int(time.time())
                r.backpack.timestamp = int(time.time())

                #set flowerbed
                r.flowerbed.id = str(flowerbed.key())
                r.flowerbed.latitude = int(self.request.get('lat'))
                r.flowerbed.longitude = int(self.request.get('lon'))
                r.flowerbed.owner = gamer_hash
                r.flowerbed.flowers = 0

                #set backpack
                for i in backpack:
                    bp = r.backpack.item.add()
                    bp.name = i.name
                    bp.amount = i.amount


        if self.request.get('debug', False):
            self.response.out.write(r)
        else:
            self.response.out.write(r.SerializeToString())
开发者ID:glukki,项目名称:kloomba,代码行数:60,代码来源:flowerbed.py

示例2: get

    def get(self, key):
        k = Key(encoded=key)
        if k.kind() == 'NearWooCampaignDS':
            logging.info('is this camp?????')
            camp_obj = models.NearWooCampaignDS.urlsafe_get(key)
            camp = camp_obj.to_dict()
            # logging.info(camp.to_dict())
        elif k.kind() == 'YelpJsonDS':
            yelp = models.YelpJsonDS.urlsafe_get(key)
            camp = models.NearWooCampaignDS.urlsafe_get(yelp.campaign_key)
        elif k.kind() == 'Advertiser':
            camp = models.NearWooCampaignDS.gql(
                'where advertiser_key = :1', key).fetch(1000)
        else:
            camp = None
        if not camp:
            m = "Camp Entity cannot be retrieved with given key"
            msg = make_status_message(success=False, message=m,
                                      code=500, data=None)
            self.response.write(msg)
        else:
            result = None
            if type(camp) == list:
                result = []
                for c in camp:
                    result.append(c.to_dict())
            else:
                result = camp

            msg = make_status_message(
                success=True, message='successfully retrieved',
                code=200, data=result)
            self.response.write(msg)
开发者ID:samuelchase,项目名称:yougee,代码行数:33,代码来源:data_service.py

示例3: post

 def post(self):
   model_kind = self.request.get('model_kind')
   frequency = self.request.get('frequency')
   date = str_to_date(self.request.get('date_string'))
   store_key_name = self.request.get('store_key_name')
   
   logging.info('Cleanupworker model kind: %s frequency: \
   %s store: %s' %(model_kind,frequency,store_key_name))
   
   recursion_flag = False
   
   if model_kind == 'ProductRenderer':
     store_key = Key.from_path('Store',store_key_name)
     query = get_renderer_query_for_frequency(frequency, date, store_key)
     keys = query.fetch(200, TEMPLATE_PRODUCT_COUNT)
   elif model_kind == 'ProductCounter':
     store_key = Key.from_path('Store',store_key_name)
     query = get_counter_query_for_frequency(frequency, date, store_key)
     keys = query.fetch(200)
   elif model_kind == 'UserCounter':
     query = USER_COUNTER_CLEANUP_TARGETS
     keys = query.fetch(200)
   else:
     logging.error('No type found for CleanupWorker :%s' %model_kind)
   
   if len(keys):
     recursion_flag = True
     pdb.delete(keys)
   
   if recursion_flag:
     logging.info('Enqueing cleanup for model %s' %model_kind)
     enqueue_cleanup(model_kind,frequency,str(date),store_key_name)
开发者ID:frankk00,项目名称:TweetHit,代码行数:32,代码来源:taskworker.py

示例4: get

 def get(self):
   checklist = Checklist.get(Key.from_path('Checklist', long(self.request.get('cl_id'))))
   if not helpers.checkPermissionAndRespond(self, cl=checklist): return
   if not self.addable(checklist):
     helpers.createResponse(self, 'message_can_not_create_item.html')
     return 
   helpers.createResponse(self, 'create_item.html', {'checklist': checklist})
开发者ID:yoooyle,项目名称:checklist,代码行数:7,代码来源:create.py

示例5: get_news_item

def get_news_item(id):
  if 'uncached' not in request.args:
    return get_news_item_cached(id)

  key = Key.from_path('NewsItem', str(id))
  news_item = NewsItem.get(key)
  return Response(json.dumps(news_item.jsonData, default=dthandler),  mimetype='application/json')
开发者ID:bbondy,项目名称:brianbondy.gae,代码行数:7,代码来源:api.py

示例6: post_news_item

def post_news_item(news_item_id=None):
  if not users.is_current_user_admin():
    abort(401)

  if news_item_id:
    key = Key.from_path('NewsItem', str(news_item_id))
    news_item = NewsItem.get(key)
    news_item.clearTags();
  else:
    news_item = NewsItem.create()

  # TODO: Most of this code can go in the model with a fromJSONData function
  news_item.title = request.json['title']
  news_item.body = request.json['body']
  news_item.draft = request.json['draft']
  news_item.posted_date = parser.parse(request.json['posted_date'])
  news_item.last_modified_date = parser.parse(request.json['last_modified_date'])
  news_item.put();

  # Loop through the tags to add them
  for tag_name in request.json['tags']:
    tag_name = tag_name.strip()
    if tag_name == '':
      continue  

    tag = Tag(key_name=tag_name, tag=tag_name)
    tag.put()
    news_item_tag = NewsItemTag()
    news_item_tag.tag = tag.key()
    news_item_tag.news_item = news_item.key()
    news_item_tag.put()

  return Response(json.dumps(news_item.jsonData, default=dthandler),  mimetype='application/json')
开发者ID:bbondy,项目名称:brianbondy.gae,代码行数:33,代码来源:api.py

示例7: post

  def post(self):
    cl = Checklist.get(Key.from_path('Checklist', long(self.request.get('cl_id'))))
    if not helpers.checkPermissionAndRespond(self, cl=cl, edit=False):
      return
    
    user = users.get_current_user()
    
    for sub in Subscription.all().filter("user ==", user).filter("deleted ==", False):
      if sub.source.key() == cl.key():
        helpers.createResponse(self, 'message_already_subscribed.html', 
          {'old_checklist': cl})
        
    sub = Subscription(
        user=user,
        source=cl,
        deleted=False,                       
                       )        

    sub.put()

    for item in cl.item_set:
      subItem = SubscribedItem(
          subscription=sub,
          original=item,
          finished=False,
          deleted=False,                               
                               )
      subItem.put()
    
    helpers.createResponse(self, 'message_subscribed.html')
开发者ID:yoooyle,项目名称:checklist,代码行数:30,代码来源:create.py

示例8: post

 def post(self):
   user = self.processPostData()
   syllabusUnitIds = self.request.get_all('keys')
   syllabusUnitKeys = [Key.from_path('SyllabusUnit', int(iid)) for iid in syllabusUnitIds]
   user.syllabusUnitKeys = syllabusUnitKeys
   user.put()
   self.render(user)  
开发者ID:sridharsundaram,项目名称:mazaa,代码行数:7,代码来源:configure.py

示例9: post

	def post( self ):
		result = {
			'result': True,
			'error': ''
		}

		try:
			# input marshalling
			taskId = int( self.request.get( 'taskId' ) )
			projectId = int( self.request.get( 'projectId' ) )
			title = self.request.get( 'title' )
			description = self.request.get( 'description' )
			tagJson = unicode( self.request.get( 'tags' ) )

			tags = simplejson.loads( tagJson ) # should be an array!

			# add the new tags in case we don't have them already
			Tags.InsertIfNotHere( users.GetCurrentUser(), tags )

			# grab the task
			task = Task.get_by_id( taskId, Key.from_path( 'Project', projectId ) )
			task.title = title
			task.description = description
			task.tags = tags
			task.put()

			result['data'] = task.toDict()

		except Exception, e:
			result['result'] = False
			result['error'] = 'Error: %s' % e
开发者ID:imclab,项目名称:App-Engine-Task-Manager,代码行数:31,代码来源:Tasks.py

示例10: get

    def get(self, login_user=None, template_values={}):

        # is import or update going on?
        template_values['update_status'] = memcache.get('update_status')
        template_values['import_status'] = memcache.get('import_status')

        # Check for existing data.
        try:
            counter = StopMeta.get(Key.from_path('StopMeta', 1))
            template_values['production_num_stops'] = counter.counter_stop_no_confirm
            template_values['production_num_stations'] = counter.counter_station_no_confirm
            template_values['production_num_places'] = counter.counter_place_no_confirm
            # confirmation outstanding
            template_values['update_num_stops'] = counter.counter_stop_update_confirm
            template_values['update_num_stations'] = counter.counter_station_update_confirm
            template_values['update_num_places'] = counter.counter_place_update_confirm
            template_values['new_num_stops'] = counter.counter_stop_new_confirm
            template_values['new_num_stations'] = counter.counter_station_new_confirm
            template_values['new_num_places'] = counter.counter_place_new_confirm
            # Administrative hierarchy
            template_values['gov_num'] = Comuna.all().count()+Region.all().count()+Country.all().count()
        except AttributeError:
            # no data in database. Redirect to import page
            self.redirect('/import')

        template_values['upload_url'] = blobstore.create_upload_url('/update/upload')
        path = os.path.join(os.path.dirname(__file__), "pages/update.html")
        self.response.out.write(template.render(path, template_values))
        return
开发者ID:navimont,项目名称:balsa.cl,代码行数:29,代码来源:balsa_update.py

示例11: post

	def post( self ):
		result = {
			'result': True,
			'error': ''
		}

		try:
			# input marshalling
			projectId = int( self.request.get( 'projectId' ) )
			taskId = int( self.request.get( 'taskId' ) )
			filename = self.request.POST['Filedata'].filename
			imageData = self.request.get( 'Filedata' )
			
			# grab the task
			task = Task.get_by_id( taskId, Key.from_path( 'Project', projectId ) )

			# create
			theImage = db.Blob( imageData )
			i = Image( parent = task, filename = filename, image = theImage )
			i.put()
			
			result['data'] = i.toDict()

		except Exception, e:
			logging.error( e )
			result['result'] = False
			result['error'] = 'Error: %s' % e
开发者ID:imclab,项目名称:App-Engine-Task-Manager,代码行数:27,代码来源:Images.py

示例12: get_dudle

def get_dudle(id):
    """
    Get dudle for id
    """
    key = Key.from_path('Dudle', id)
    dudle = Dudle.get(key)
    return dudle
开发者ID:djfroofy,项目名称:Dudlr,代码行数:7,代码来源:core.py

示例13: get

	def get(self):
		mcode = self.request.get('mcode')
		lcode = self.request.get('lcode')
		
		q=Lecturer.all()
		q.filter('__key__ =', Key.from_path('Lecturer', lcode))
		lecturers = q.get()
		self.response.write('Lecturer with code "'+lcode+'" is called "'+lecturers.full_name+'"')
		
		q = Module.all()
		q.filter('__key__ = ', Key.from_path('Module',mcode))
		modules = q.get()
		self.response.write('<br/>Module with code "'+modules.code+'" has title "'+modules.title+'"')
		
		Rating(module=modules, lecturer =lecturers).put()
		self.response.write('<br/> Rating probably put successfully')
开发者ID:azardilis,项目名称:seed,代码行数:16,代码来源:test_dio.py

示例14: get

    def get(self):
        r = BookmarkRemove()

        if not self.request.get('id'):
            return

        fb_key = self.request.get('id')
        user = users.get_current_user()
        gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id())

        #get bookmark
        bookmark = GqlQuery('SELECT * FROM Bookmark WHERE ANCESTOR IS :1 AND flowerbed=:2', gamer_key, Key(fb_key)).get()

        if not bookmark:
            return

        bookmark.delete()

        r.timestamp = int(time.time())
        r.id = fb_key

        if self.request.get('debug', False):
            self.response.out.write(r)
        else:
            self.response.out.write(r.SerializeToString())
开发者ID:glukki,项目名称:kloomba,代码行数:25,代码来源:bookmark.py

示例15: FileKey

def FileKey(filename, user):
  if not user:
    u_id = -1
  else:
    u_id = user.user_id()
  
  return Key.from_path('File', '%s_%s' % (filename, u_id))
开发者ID:bradn123,项目名称:naclports,代码行数:7,代码来源:AppEngineMount.py


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