def _delete_service_log(parent_service_user, service_user):
    keys = ServiceLog.all(keys_only=True).filter("user", service_user).fetch(1000)
    if keys:
        db.delete(keys)
        deferred.defer(_delete_service_log, parent_service_user, service_user, _countdown=5)
    else:
        _decrease_and_verify(parent_service_user, service_user)
Example #2
0
  def post(self):
    if Config().is_dev:
      # Only allow this if it's the dev server.
      entry = self.request.body
      logging.debug("Got new entry: " + entry)
      entry = json.loads(entry)
      # Change formatted date back into datetime.
      for key in entry.keys():
        if type(getattr(Membership, key)) == db.DateTimeProperty:
          if not entry[key]:
            # It could be None as well.
            continue
          entry[key] = pickle.loads(str(entry[key]))
      # entry should have everything nicely in a dict...
      member = Membership(**entry)

      # Is this an update or a new model?
      match = Membership.all().filter("email =", member.email).get()
      if match:
        # Replace the old one.
        logging.debug("Found entry with same username. Replacing...")
        db.delete(match)

      member.put()
      logging.debug("Put entry in datastore.")
Example #3
0
 def delete(self):
     while True:
         # HACK: This smells like trouble - switch to Task Queue?
         w_keys = WBO.all(keys_only=True).ancestor(self).fetch(500)
         if not w_keys: break
         db.delete(w_keys)
     db.Model.delete(self)
Example #4
0
	def get(self):
		id=db.Key(self.request.get('id'))
		if not id:
			self.redirect('/error?reason=error')
			return

		allowed= (users.get_current_user() in BlogAdmin)
	
		if not allowed:
			self.redirect('/error?reason=forbidden')
			return
		if not self.request.get('confirm')=='yes':
			object_to_remove=""
			main=MainPage()
			main.isadmin=False
			main.call_user=0
			object=db.get(id)
			if id.kind()=='BlogEntry':
				object_to_remove=main.get_entry(object)
			elif id.kind()=='BlogComment':
				object_to_remove=render_comment(object,main)
				
			values={
				'target':object_to_remove,
				'id':str(object.key())
				}
			path = os.path.join(os.path.dirname(__file__), '../../htmls/page_remove.html')
			self.response.out.write(template.render(path, values))
		else:
			self.remove_daughters(id)
			db.delete(db.get(id))
			self.redirect('/')
Example #5
0
 def GET(self):
     #如果删除了内置书籍py文件,则在数据库中也清除,有最长一天的滞后问题不大
     for bk in Book.all().filter('builtin = ', True):
         found = False
         for book in BookClasses():
             if book.title == bk.title:
                 found = True
                 break
         if not found:
             for fd in bk.feeds:
                 fd.delete()
             bk.delete()
     
     # 停止过期用户的推送
     for user in KeUser.all():
         if user.expires and (user.expires < datetime.datetime.utcnow()):
             user.enable_send = False
             user.put()
     
     query = DeliverLog.all()
     query.filter('datetime < ', datetime.datetime.utcnow() - datetime.timedelta(days=25))
     logs = query.fetch(1000)
     c = len(logs)
     db.delete(logs)
     
     return "%s lines log removed.<br />" % c
Example #6
0
 def upload_model(self,model_class,result):
     from google.appengine.ext import db
     from utils import deserialize
                 
     save = []
     to_delete = []
     for entity in result:
                         
         if "id" in entity:
             existing_entry = model_class.get(db.Key.from_path(model_class.kind(),entity ["id"]))
             if existing_entry:
                 to_delete.append(existing_entry) # Remove the existing entry with numeric ID
             
         object = deserialize(model_class , entity)
                     
         save.append(object)
         
         if len(to_delete) > 100:
             db.delete(to_delete)
             to_delete = []
         if len(save) > 100:
             db.put(save)
             save = []
     
     db.delete(to_delete)    
     db.put(save)
Example #7
0
def bulk_edit_users(request):
  """Renders and processes a form to edit UserProfiles with a csv format.

  Args:
    request: The request object

  Returns:
    A Django HttpResponse object.

  """
  if not request.POST:
    return utility.respond(request, 'admin/bulk_edit_users',
                           {'title': 'Bulk user upload form'})

  data = request.POST['users_text']
  if data and data[-1] != '\n':
    data += '\n'

  if request.FILES and 'users_file' in request.FILES:
    data += request.FILES['users_file']['content']

  if 'complete' in request.POST:
    for profile in models.UserProfile.all():
      db.delete(profile)

  csv_buffer = StringIO.StringIO(data)
  for email, is_superuser in csv.reader(csv_buffer, skipinitialspace=True):
    if not models.UserProfile.update(email, is_superuser == '1'):
      logging.warning('Could not update user %r' % email)

  url = urlresolvers.reverse('views.admin.index')
  return http.HttpResponseRedirect(url)
Example #8
0
    def post(self):
        status = "ok"
        user = self.user
        if not user:
            self.redirect('/login')
        store_name = self.request.get('choose_market')
        logging.error(store_name)
        address = self.request.get('address')
        telephone = self.request.get('telephone')
        stores_list = list(caching.get_stores())
        t = db.GqlQuery('SELECT * FROM UserData WHERE login = :login', login = user.auth_ids)
        new_user = models.UserData()
        new_user = list(t)[0]
        db.delete(t)
        new_user.store_id = int(store_name)
        new_user.address = address
        if re.match('^\+(?:[0-9] ?){6,14}[0-9]$', telephone):
            new_user.telephone = telephone
        else:
            status = "telephone"
        new_user.put()
        memcache.set('current_store', None)
        memcache.set('current_store' + user.auth_ids[0], None)

        self.render('user_profile_change.html',{'m_user': new_user, 
                                                'is_home':1,
                                                'first_name' : user.name,
                                                'last_name' : user.last_name,
                                                'stores_list': stores_list,
                                                'address': new_user.address if new_user.address else "",
                                                'telephone': new_user.telephone if new_user.telephone else "",
                                                'status': status})
Example #9
0
  def delete(self):
    """Exposed as `DELETE /api/photos`.

    Accepts the following request parameters.

    'photoId': id of the photo to delete.

    Returns the following JSON response representing success.
    'Photo successfully deleted.'

    Issues the following errors along with corresponding HTTP response codes:
    401: 'Unauthorized request' (if certain parameters are present in the
         request)
    404: 'Photo with given ID does not exist.'
    """
    try:
      user = self.get_user_from_session()
      photo_id = self.request.get('photoId')
      if photo_id:
        photo = model.Photo.get_by_id(long(photo_id))
        if photo.owner_user_id != user.key().id():
          raise UserNotAuthorizedException
        photoVotes = model.Vote.all().filter(
          "photo_id =", photo.key().id()).run()
        db.delete(photo)
        db.delete(photoVotes)
        self.send_success(model.Message(message = "Photo successfully deleted"))
      else:
        raise NotFoundException
    except NotFoundException as nfe:
      self.send_error(404, nfe.msg)
    except TypeError as te:
      self.send_error(404, "Resource not found")
    except UserNotAuthorizedException as e:
      self.send_error(401, e.msg)
Example #10
0
    def post(self):
        """ Submits data to the server to delete the post """
        auth_error = True
        if self.read_secure_cookie('usercookie'):
            auth_error = False
        else:
            auth_error = True
        username = self.read_secure_cookie('usercookie')
        if not self.user_exists(username):
            auth_error = False
        else:
            auth_error = True

        if not auth_error:
            comment_id = self.request.get('comment_id')
            post_id = self.request.get('post_id')
            key = db.Key.from_path('Comment',
                                   int(comment_id),
                                   parent=post_key(post_id))
            # gets the post data based upon what
            # is passed from post_id into key
            db.delete(key)
            self.render('/commentdeleted.html')
        else:
            self.redirect('/signup')
Example #11
0
    def post(self):
        user= self.current_user
        keys = self.request.get("keys")
        keyList = keys.split("|")
        pRide= Ride.get(keyList[0])
        dRide= Ride.get(keyList[1])
        logging.debug(dRide)
        for passenger in pRide.passengers:
            if dRide.passengers:
                dRide.passengers.append(passenger)
            else:
                dRide.passengers=[passenger]
        dRide.num_passengers = dRide.num_passengers +len(pRide.passengers)
        dRide.put()
        db.delete(keyList[0])

        greeting = ''
        if user:
            greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>) Go to your <a href='/home'>Home Page</a>" %
                        (user.nickname(), users.create_logout_url("/")))
        message = 'You have added passengers to your ride.'
        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path, {
            'greeting' : greeting,
            'message' : message,
            'mapkey':MAP_APIKEY,
            }))
Example #12
0
 def get(self, post_id):
     currentUser = self.checkCurrentUser()
     if currentUser:
         username = currentUser.name
         # code to retrieve selected comment for edit
         key = db.Key.from_path('CommentDB', int(post_id))
         SelectedComment = db.get(key)
         commentor = SelectedComment.username
         blogKey = SelectedComment.blogkey
         selectedBlog = db.get(blogKey)
         if username == commentor :
             # code to delete comment
             db.delete(key)
             #Code to update comment count
             refblogCommentCount = selectedBlog.commentCount
             if refblogCommentCount > 0:
                 refblogCommentCount= int(refblogCommentCount) - 1
             else:
                 refblogCommentCount= 0
             selectedBlog.commentCount = refblogCommentCount
             blogKey = selectedBlog.put()
             # code to redirect to selected blog
             self.redirect("/blog/%s" % blogKey.id())
             self.redirect("/blog/%s" % blogKey.id())
         else:
             self.render("alert.html",currentUser=currentUser.name, message = "Warning! You are not authorized to Delete this comment. Thanks.")
     else:
         #if user not logged in ask user to Login
         self.render('login.html', alert="Please login First.")  
Example #13
0
  def delete(cls,keys,_storage = None):
    """Delete one or more Model instances from given storage layers
  
    Args:
      _storage: string or array of strings for target storage layers
      
      Inherited:
        models: Model instance, key, key string or iterable thereof.
        config: datastore_rpc.Configuration to use for this request.
    """
    keys = map(_key_str, _to_list(keys))
    if _storage is None:
      _storage = ALL_LEVELS
    else:
      _storage = _to_list(_storage)
      _validate_storage(_storage)
    
    if DATASTORE in _storage:
      db.delete(keys)
      
    if LOCAL in _storage:
      _cachepy_delete(keys)

    if MEMCACHE in _storage:
      _memcache_delete(keys)
Example #14
0
    def get(self):
        key = self.request.get('key')
        ride = db.get(key)
        if ride == None:
            doRender(self, 'error.html', {
                'error_message': "No such ride exists."})
        elif ride.num_passengers == 0:
            db.delete(ride)

        else:
            ride.driver = None
            ride.put()
            for p in ride.passengers:
                logging.debug(p.name)
                logging.debug(Passenger.get(p).name)
                to = Passenger.get(p).name
                self.sendRiderEmail(ride,to)

        user = self.current_user
        greeting = ''
        if user:
            greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>) Go to your <a href='/home'>Home Page</a>" %
                        (user.nickname(), users.create_logout_url("/")))
        message = 'Your ride has been deleted.'
        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path, {
            'greeting' : greeting,
            'message' : message,
            'mapkey':MAP_APIKEY,
            'college': mycollege,
            'nick' : user.nickname()
            }))
Example #15
0
    def get(self):

        # Creating a new entity group with a root entity:
        board = MessageBoard(key_name='The_Archonville_Times')
        board.title = 'The Archonville Times'
        board.put()
        
        self.response.write('<p>board key: %s</p>'
                            % printable_path(board.key()))
        
        # Using the object for the "parent" argument:
        msg1 = Message(parent=board, key_name='first!')
        msg1.put()
        
        self.response.write('<p>msg1 key: %s</p>'
                            % printable_path(msg1.key()))
        
        # Using a Key for the "parent" argument:
        p_key = board.key()
        msg2 = Message(parent=p_key, key_name='pk_fest_aug_21')
        msg2.put()
        
        self.response.write('<p>msg2 key: %s</p>'
                            % printable_path(msg2.key()))
        
        # Using an entity that isn't the root as the parent:
        msg3 = Message(parent=msg1, key_name='keep_clean')
        msg3.put()
        
        self.response.write('<p>msg3 key: %s</p>'
                            % printable_path(msg3.key()))
        
        # Deriving a key using the ancestor path:
        k = db.Key.from_path('MessageBoard', 'The_Archonville_Times',
                             'Message', 'first!',
                             'Message', 'keep_clean')
        
        self.response.write('<p>k: %s</p>' % printable_path(k))
        
        # Using a non-existent path part as a parent:
        root = db.Key.from_path('MessageBoard', 'The_Baskinville_Post')
        
        msg4 = Message(parent=root)
        msg4.put()
        
        self.response.write('<p>msg4 key: %s</p>'
                            % printable_path(msg4.key()))
        
        msg5 = Message(parent=root)
        msg5.put()
        
        self.response.write('<p>msg5 key: %s</p>'
                            % printable_path(msg5.key()))
        
        db.delete([msg1, msg2, msg3, msg4, msg5, board])
        self.response.write('<p>Entities deleted.</p>')
        
        
        self.response.write('<p>The time is: %s</p>'
                            % str(datetime.datetime.now()))
Example #16
0
    def get(self):
        results = Searches.all().filter('user_id', users.get_current_user()).order('-timestamp')

        for result in results:
            db.delete(result)

        self.response.out.write("Your queries have been deleted.")
Example #17
0
def feedback_answers_for_user_data(user_data):
    feedbacks = []

    if not user_data:
        return feedbacks

    notifications = models_discussion.FeedbackNotification.gql("WHERE user = :1", user_data.user)

    for notification in notifications:

        feedback = None

        try:
            feedback = notification.feedback
        except db.ReferencePropertyResolveError:
            pass

        if not feedback or not feedback.video() or not feedback.is_visible_to_public() or not feedback.is_type(models_discussion.FeedbackType.Answer):
            # If we ever run into notification for a deleted or non-FeedbackType.Answer piece of feedback,
            # go ahead and clear the notification so we keep the DB clean.
            db.delete(notification)
            continue

        feedbacks.append(feedback)

    return feedbacks
Example #18
0
	def delete(self):
		q = db.Query(self.counter_shards).filter('name =', self.name)
		shards = q.fetch(limit=self.number_of_shards)
		db.delete(shards)

		self.memcached.delete_count()
		self.delayed_incr.delete_count()
Example #19
0
 def delete(self, note_id):
     if not users.get_current_user():
         webapp2.abort(401)
     iden = int(note_id)
     note = db.get(db.Key.from_path('Note', iden))
     db.delete(note)
     return self.redirect('/note/list')
    def deactivate(self):
        if self.participant:
            if not self._validate():
                return 'Invalid Google Wave account or activation code'

            self.account = phone.get_account(self.participant)
            if not self.account:
                return 'Participant doesn\'t have an account'

            query = model.ParticipantPreferences.all()
            query.filter('account_id =', self.account.account_id)
            if len(list(query)) == 1:
                return 'Cannot deactivate this participant from account. There\'s only participant linked to the account.'

            pp = model.ParticipantPreferences.get_by_pk(self.participant)
            pp.account_id = None
            pp.put()

        elif self.phone_type and self.phone_uid and self.phone_token:
            self._find_account_by_phone()

            query = model.Phone.all()
            query.filter('phone_type =', self.phone_type)
            query.filter('phone_uid =', self.phone_uid)
            query.filter('phone_token =', self.phone_token)
            db.delete(query)
    def delete(self):
        """
        Deletes a session and all it's associated data from the datastore and
        memcache.

        Returns True
        """
        try:
            query = _AppEngineUtilities_SessionData.all()
            query.filter(u"session = ", self)
            results = query.fetch(1000)
            db.delete(results)
            db.delete(self)
            memcache.delete_multi([u"_AppEngineUtilities_Session_%s" % \
                (str(self.key())), \
                u"_AppEngineUtilities_SessionData_%s" % \
                (str(self.key()))])
        except:
            mc = memcache.get(u"_AppEngineUtilities_Session_%s" % \
                (str(self.key())))
            if mc:
                mc.deleted = True
            else:
                # not in the memcache, check to see if it should be
                query = _AppEngineUtilities_Session.all()
                query.filter(u"sid = ", self.sid)
                results = query.fetch(1)
                if len(results) > 0:
                    results[0].deleted = True
                    memcache.set(u"_AppEngineUtilities_Session_%s" % \
                        (unicode(self.key())), results[0])
        return True
Example #22
0
def clear_question_answers_for_current_user(s_question_id):

    user = util.get_current_user()
    if not user:
        return

    question_id = -1
    try:
        question_id = int(s_question_id)
    except:
        return

    if question_id < 0:
        return

    question = models_discussion.Feedback.get_by_id(question_id)
    if not question:
        return;

    user_data = models.UserData.get_or_insert_for(user)

    feedback_keys = question.children_keys()
    for key in feedback_keys:
        notifications = models_discussion.FeedbackNotification.gql("WHERE user = :1 AND feedback = :2", user, key)
        if notifications.count():
            db.delete(notifications)

    user_data.count_feedback_notification = -1
    user_data.put()
Example #23
0
    def get(self):
        db.delete(DeviceVersions.all().fetch(400))

        total = (Device.all().count() / 10) + 1
        for x in xrange(total):
            offset = x * 10
            taskqueue.add(url='/tasks/AggregateVersionsWorker', params={'offset': offset})
Example #24
0
	def remove_daughters(self, id):
		comment_query = db.GqlQuery('SELECT * FROM BlogComment WHERE refers_to = :parent', parent=id)
		
		for comment in comment_query:
			self.remove_daughters(comment.key())
			db.delete(comment)
		return
Example #25
0
 def post(self):
     channel_id = self.request.get('from')
     
     # get channel entry 
     logging.info('ChannelDisconnect: ' + str(channel_id))
     chEntry = ChannelEntry.get_by_key_name(channel_id)
     
     user = chEntry.user
     session_key = chEntry.session_key
     session = Session.get_by_key_name(session_key)
     
     if (session and user == session.host):
         SessionUpdater(session).remove_session()
     elif (session and user in session.listeners):
         SessionUpdater(session).remove_listener(user)
             
     q = Session.all().filter('host =', user)
     for ses in q.run(read_policy=db.STRONG_CONSISTENCY):
         SessionUpdater(ses).remove_session()
         
     chEntry.free = True
     chEntry.put()
     
     # Delete expired entries
     q = ChannelEntry.all().filter('expire <', datetime.datetime.now())
     for expired in q.run():
         db.delete(expired.key())
Example #26
0
    def entity(self, request, model_name=None, key=None):
        real_method = request.method
        if request.method == "POST":
            real_method = request.headers.get(METHOD_OVERRIDE_HEADER, None)
            if real_method:
                real_method = real_method.upper()
            else:
                real_method = "POST"

        if real_method == "GET":
            model_handler = self.get_model_handler(model_name)
            model = model_handler.get(key)
            self.check_authority(request, OP_SHOW, obj=model,
                                 model_name=model_name, prop_name=None)
            if model is None:
                raise NotFound
            return self.out_to_response(
                self.models_to_xml(request, model_name, model_handler, model,
                                   {}))
        elif real_method == "POST":
            return self.update_impl(request, model_name, key, False)
        elif real_method == "PUT":
            return self.update_impl(request, model_name, key, True)
        elif real_method == "DELETE":
            model_handler = self.get_model_handler(model_name)
            model = model_handler.get(key)
            self.check_authority(request, OP_DELETE, obj=model,
                                 model_name=model_name, prop_name=None)
            try:
                db.delete(db.Key(key))
                return Response("OK")
            except Exception:
                logging.warning("delete failed", exc_info=1)
                return InternalServerError()
Example #27
0
  def get_and_store_friends(user):
    """Query Google for the list of the user's friends that they've shared with
    our app, and then store those friends for later use.

    Args:
      user: User to get friends for.
    """

    # Delete the friends for the given user first.
    edges = model.DirectedUserToUserEdge.all().filter(
        'owner_user_id = ', user.key().id()).run()
    db.delete(edges)

    http = httplib2.Http()
    plus = build('plus', 'v1', http=http)
    user.google_credentials.authorize(http)
    friends = plus.people().list(userId='me', collection='visible').execute()
    for google_friend in friends.get('items'):
      # Determine if the friend from Google is a user of our app
      friend = model.User.all().filter('google_user_id = ',
          google_friend.get('id')).get()
      # Only store edges for friends who are users of our app
      if friend is not None:
        edge = model.DirectedUserToUserEdge()
        edge.owner_user_id = user.key().id()
        edge.friend_user_id = friend.key().id()
        edge.put()
def _delete_non_ancestor_models(parent_service_user, service_user):
    sp = get_service_profile(service_user)
    if sp:
        def get_service_identity_based_keys():
            keys = list()
            si_users = list()
            for si in get_service_identities(service_user):
                keys.append(ProfilePointer.create_key(si.service_identity_user))
                si_users.append(si.service_identity_user)
            for qr in ServiceInteractionDef.all().ancestor(parent_key(service_user)):
                keys.append(db.Key.from_path(ShortURL.kind(), ServiceInteractionDef.shortUrl.get_value_for_datastore(qr).id()))
            return keys, si_users

        keys = [db.Key.from_path(Avatar.kind(), sp.avatarId)]
        keys.extend(TrialServiceAccount.all(keys_only=True).filter("service", service_user))
        more_keys, service_identity_users = db.run_in_transaction(get_service_identity_based_keys)
        keys.extend(more_keys)
        keys.extend(MessageFlowRunRecord.all(keys_only=True).filter("service_identity >=", service_user.email() + '/').filter("service_identity <", service_user.email() + u"/\ufffd"))
        keys.extend(Branding.all(keys_only=True).filter("user", service_user))
        keys.extend(SIKKey.all(keys_only=True).filter("user", service_user))
        keys.extend(APIKey.all(keys_only=True).filter("user", service_user))
        logging.info(keys)
        db.delete(keys)

        delete_service_tasks = DeleteServiceTasks(key_name=service_user.email())
        delete_service_tasks.tasks = 3
        delete_service_tasks.put()

        deferred.defer(_delete_sessions, parent_service_user, service_user)
        deferred.defer(_delete_service_log, parent_service_user, service_user)
        deferred.defer(_delete_service_models, parent_service_user, service_user)
        deferred.defer(_cleanup_service_identities, service_identity_users)
    else:
        if parent_service_user and parent_service_user != service_user:
            deferred.defer(delete_service_finished, parent_service_user, service_user.email(), True)
Example #29
0
 def delete_for_blip(cls, blip):
     for _ in xrange(200):
         q = cls.gql('WHERE blip=:1', blip)
         if q.count() <= 0:
             break
         results = q.fetch(900)
         db.delete(results)
Example #30
0
	def get(self):
		
		list = db.get(self.request.get('key'))
		items = db.GqlQuery("SELECT * FROM ListItem WHERE list = :1", list)
		list.delete()
		db.delete(items)
		self.redirect('/todo')
Example #31
0
    def get(self, table_from, table_to):
        """ handle the request to replicate a table """
        pagecount.IncrPageCount("export.TransferTable.attempt", 1)
        verify_dig_sig(self.request, "TransferTable")
        limit = get_limit(self.request, "TransferTable")
        min_key = utils.get_last_arg(self.request, "min_key", "")

        if table_from == table_to:
            pagecount.IncrPageCount("export.TransferTable.sameTableName", 1)
            raise Fail("cannot transfer '%s' to itself" % table_from)

        if (table_to[0:len(table_from)] + '_') != (table_from + '_'):
            raise Fail("destination must start with '%s_'" % table_from)

        verify_table_name(table_to)

        # match our type of table
        source = get_model(table_from, "TransferTable")
        destination = type(table_to, (source, ), {})

        if min_key == "":
            # a blank key means that we are starting at the top of the table
            # so we need to clean out anything that may already be in
            # the destination table
            while True:
                query = destination.all()
                # 500 records is the max
                results = query.fetch(500)
                if results:
                    db.delete(results)
                else:
                    break

        last_key, rows = transfer_table(source, destination, min_key, limit)
        self.response.out.write("from %s to %s\nrows\t%d\nlast_key\t%s\n" %
                                (table_from, table_to, rows, last_key))
        pagecount.IncrPageCount("export.TransferTable.success", 1)
  def get(self):
    self.version_filter = self.request.GET.get('versions', 'all')
    self.sender = self.request.GET['sender']
    self.to = self.request.GET.get('to', None)
    report_date = self.request.GET.get('date', None)
    if report_date:
      self.yesterday = datetime.date(*[int(x) for x in report_date.split('-')])
    else:
      self.yesterday = datetime.date.today() - datetime.timedelta(days=1)
    self.app_id = os.environ['APPLICATION_ID']
    version = os.environ['CURRENT_VERSION_ID']
    self.major_version, self.minor_version = version.rsplit('.', 1)
    self.minor_version = int(self.minor_version)
    self.max_results = int(self.request.GET.get('max_results',
                                                self.DEFAULT_MAX_RESULTS))
    self.debug = isTrue(self.request.GET.get('debug', 'false'))
    self.delete = isTrue(self.request.GET.get('delete', 'true'))

    try:
      exceptions = self.GetQuery(order='-minor_version').fetch(self.max_results)
    except db.NeedIndexError:

      exceptions = self.GetQuery().fetch(self.max_results)

    if exceptions:
      report = self.GenerateReport(exceptions)
      if self.debug:
        self.response.out.write(report)
      else:
        self.SendReport(report)


      if self.delete:
        db.delete(exceptions)
    else:
      if self.debug:
        self.response.out.write("no data\n")
Example #33
0
 def testGetAllPaymentAccounts(self):
     # returns empty query if no accounts
     a = mydb.Account.GetAllPaymentAccounts()
     self.assertEqual(a.count(), 0)
     # counts Checking accounts as payment accounts
     self.addAccountStub(type='Checking')
     a = mydb.Account.GetAllPaymentAccounts()
     self.assertEqual(a.count(), 1)
     self.addAccountStub(name='C Account 2', type='Checking')
     a = mydb.Account.GetAllPaymentAccounts()
     self.assertEqual(a.count(), 2)
     # also counts Credit Card accounts as payment accounts
     self.addAccountStub(name='CC Account 1', type='Credit Card')
     a = mydb.Account.GetAllPaymentAccounts()
     self.assertEqual(a.count(), 3)
     self.addAccountStub(name='CC Account 2', type='Credit Card')
     a = mydb.Account.GetAllPaymentAccounts()
     self.assertEqual(a.count(), 4)
     # returns 0 if no Checking or Credit Card Accounts
     for account in a:
         db.delete(account.key())
     a = mydb.Account.GetAllPaymentAccounts()
     self.assertEqual(a.count(), 0)
     # counts Credit Card accounts as payment accounts (without also having Checking accounts)
     self.addAccountStub(name='CC Account 1', type='Credit Card')
     a = mydb.Account.GetAllPaymentAccounts()
     self.assertEqual(a.count(), 1)
     self.addAccountStub(name='CC Account 2', type='Credit Card')
     a = mydb.Account.GetAllPaymentAccounts()
     self.assertEqual(a.count(), 2)
     # doesn't count Investment or Savings accounts
     self.addAccountStub(type='Investment')
     a = mydb.Account.GetAllPaymentAccounts()
     self.assertEqual(a.count(), 2)
     self.addAccountStub(type='Savings')
     a = mydb.Account.GetAllPaymentAccounts()
     self.assertEqual(a.count(), 2)
Example #34
0
def deleteForum(fid):
    if not fid: return None
    forum = ForumList.get_by_key_name(fid)
    topics = ForumTopics.all().filter('forumid =', fid).fetch(999)
    messages = ForumMessages.all().filter('forumid =', fid).fetch(999)
    db.delete(messages)
    db.delete(topics)
    db.delete(forum)
    return fid
Example #35
0
    def post(self):
        status = "ok"
        user = self.user
        if not user:
            self.redirect('/login')
        store_name = self.request.get('choose_market')
        logging.error(store_name)
        address = self.request.get('address')
        telephone = self.request.get('telephone')
        stores_list = list(caching.get_stores())
        t = db.GqlQuery('SELECT * FROM UserData WHERE login = :login',
                        login=user.auth_ids)
        new_user = models.UserData()
        new_user = list(t)[0]
        db.delete(t)
        new_user.store_id = int(store_name)
        new_user.address = address
        if re.match('^\+(?:[0-9] ?){6,14}[0-9]$', telephone):
            new_user.telephone = telephone
        else:
            status = "telephone"
        new_user.put()
        memcache.set('current_store', None)
        memcache.set('current_store' + user.auth_ids[0], None)

        self.render(
            'user_profile_change.html', {
                'm_user': new_user,
                'is_home': 1,
                'first_name': user.name,
                'last_name': user.last_name,
                'stores_list': stores_list,
                'address': new_user.address if new_user.address else "",
                'telephone': new_user.telephone if new_user.telephone else "",
                'status': status
            })
  def post(self):
    """Mapreduce done callback to delete job data if it was successful."""
    if 'Mapreduce-Id' in self.request.headers:
      mapreduce_id = self.request.headers['Mapreduce-Id']
      mapreduce_state = model.MapreduceState.get_by_job_id(mapreduce_id)

      keys = []
      job_success = True
      for shard_state in model.ShardState.find_by_mapreduce_id(mapreduce_id):
        keys.append(shard_state.key())
        if not shard_state.result_status == 'success':
          job_success = False

      if job_success:
        operation = DatastoreAdminOperation.get(
            mapreduce_state.mapreduce_spec.params[
                DatastoreAdminOperation.PARAM_DATASTORE_ADMIN_OPERATION])
        def tx():
          operation.active_jobs -= 1
          operation.completed_jobs += 1
          if not operation.active_jobs:
            operation.status = DatastoreAdminOperation.STATUS_COMPLETED
          db.delete(DatastoreAdminOperationJob.all().ancestor(operation))
          operation.put()
        db.run_in_transaction(tx)

        if config.CLEANUP_MAPREDUCE_STATE:
          keys.append(mapreduce_state.key())
          keys.append(model.MapreduceControl.get_key_by_job_id(mapreduce_id))
          db.delete(keys)
          logging.info('State for successful job %s was deleted.', mapreduce_id)
      else:
        logging.info('Job %s was not successful so no state was deleted.', (
            mapreduce_id))
    else:
      logging.error('Done callback called without Mapreduce Id.')
Example #37
0
 def testGetAllCheckingSavingsAccounts(self):
     # returns empty query if no accounts
     a = mydb.Account.GetAllCheckingSavingsAccounts()
     self.assertEqual(a.count(), 0)
     # counts only Checking accounts
     self.addAccountStub(type='Checking')
     a = mydb.Account.GetAllCheckingSavingsAccounts()
     self.assertEqual(a.count(), 1)
     self.addAccountStub(name='C Account 2', type='Checking')
     a = mydb.Account.GetAllCheckingSavingsAccounts()
     self.assertEqual(a.count(), 2)
     for account in a:
         db.delete(account.key())
     # counts only Savings accounts
     self.addAccountStub(type='Savings')
     a = mydb.Account.GetAllCheckingSavingsAccounts()
     self.assertEqual(a.count(), 1)
     self.addAccountStub(name='S Account 2', type='Savings')
     a = mydb.Account.GetAllCheckingSavingsAccounts()
     self.assertEqual(a.count(), 2)
     for account in a:
         db.delete(account.key())
     # counts both Checking and Savings accounts
     self.addAccountStub(type='Checking')
     a = mydb.Account.GetAllCheckingSavingsAccounts()
     self.assertEqual(a.count(), 1)
     self.addAccountStub(name='S Account', type='Savings')
     a = mydb.Account.GetAllCheckingSavingsAccounts()
     self.assertEqual(a.count(), 2)
     # doesn't count Investment or Credit Card accounts
     self.addAccountStub(name='I Account', type='Investment')
     a = mydb.Account.GetAllCheckingSavingsAccounts()
     self.assertEqual(a.count(), 2)
     self.addAccountStub(name='CC Account', type='Credit Card')
     a = mydb.Account.GetAllCheckingSavingsAccounts()
     self.assertEqual(a.count(), 2)
Example #38
0
def feedback_answers_for_user_data(user_data):
    feedbacks = []

    if not user_data:
        return feedbacks

    notifications = models_discussion.FeedbackNotification.gql(
        "WHERE user = :1", user_data.user)

    for notification in notifications:

        feedback = notification.feedback

        if feedback == None or feedback.deleted or feedback.is_hidden_by_flags or not feedback.is_type(
                models_discussion.FeedbackType.Answer):
            # If we ever run into notification for a deleted or non-FeedbackType.Answer piece of feedback,
            # go ahead and clear the notification so we keep the DB clean.
            if feedback:
                db.delete(notification)
            continue

        feedbacks.append(feedback)

    return feedbacks
Example #39
0
def deletePlay(play_key, program=None):
  """Delete a play, and update appropriate memcaches"""
  # This is what you get when you find a stranger in the alps...
  # sorry, I mean don't link a program to this delete play call
  if program is None:
    play = getPlay(play_key).program.key()

  try_delete_keys = [LAST_PLAYS]
  if program is not None:
    try_delete_keys.append(LAST_PLAYS_SHOW %program)
  
  for key in try_delete_keys:
    entry = memcache.get(key)
    if entry is not None:
      try:
        entry.remove(db.Key(encoded=play_key))
        mcset(entry, key)
        logging.info(len(entry))
      except:
        logging.error("%s not found in %s"%(db.Key(play_key), entry))

  # We've removed any other references to this play, so delete it
  db.delete(play_key)
  mcdelete(PLAY_ENTRY, play_key)
Example #40
0
  def remove(self, keys):
    fimgs     = ImageFile.get(keys)
    key       = fimgs[0].property.key()
    property  = self.mine_or_404(str(key))
    
    # Get all blobkeys
    blobkeys = []
    for fimg in fimgs:
      
      # Verifico que sean mias las fotines por 'silas' hacker
      if not self.has_role('ultraadmin') and str(fimg.realestate.key()) != self.get_realestate_key():
        self.abort(500)

      blobkeys.append(fimg.file.key())

    # Delete fileimages
    db.delete(fimgs)
    
    # Delete blobs
    blobstore.delete(blobkeys)

    #Update images_count
    if property.images_count:
      property.images_count = property.images_count - len(blobkeys)
      if property.images_count > 0:
        fi = ImageFile.all().filter('property =',property.key()).order('position').get()
        property.main_image_url = fi.title if fi else None
      else:
        property.main_image_url = None
    else:
      property.images_count = 0
      property.main_image_url   = None
      
    result = property.save(build_index=False)
    if result != 'nones':
      taskqueue.add(url=self.url_for('property/update_index'), params={'key': str(property.key()),'action':result})
Example #41
0
 def get(self):
     user = users.get_current_user()
     if user:
         code = self.request.get("code")
         if code:
             old_userinfos = UserInfo.all().filter('user ='******'ApplicationError: 5') >= 0:
                     pass  # if something bad happens on OAuth, then it currently just redirects to the signup page
                     #TODO find a better way to handle this case, but it's not clear there is a simple way to do it without messing up a bunch of code
                 else:
                     raise err
             try:
                 manage_foursquare_data.update_user_info(userinfo)
                 manage_foursquare_data.fetch_and_store_checkins_next(
                     userinfo, limit=50)
             except foursquare.FoursquareRemoteException, err:
                 if str(err).find('403 Forbidden') >= 0:
                     pass  # if a user tries to sign up while my app is blocked, then it currently just redirects to the signup page
                     #TODO find a better way to handle this case, but it's not clear there is a simple way to do it without messing up a bunch of code
                 else:
                     raise err
             except DownloadError:
                 pass  #TODO make this better, but I'd rather throw the user back to the main page to try again than show the user an error.
Example #42
0
 def action(self, kn, action, d):
     success = False
     message = None
     s = None
     s = Sensor.get_by_key_name(kn, parent=d['enterprise'])
     if s:
         if action == "delete_all_alarms":
             rule_id = self.request.get_range('rule_id')
             if rule_id:
                 deleted = Alarm.Delete(sensor=s, rule_id=rule_id)
                 message = "Deleted %d alarm(s)" % (deleted)
                 success = True
             else:
                 message = "Malformed"
         elif action == "delete_all_records":
             records = Record.all(keys_only=True).filter("sensor =", s).fetch(3000)
             db.delete(records)
             message = "Deleted %d record(s)" % len(records)
             success = True
         else:
             raise Exception("Invalid action: %s" % action)
     else:
         message = "Sensor not found"
     self.json_out({}, message=message, success=success)
Example #43
0
    def conform(self, link):
        """
        Conform registration and activate the user.

        Parameters
        ----------
        link: link send via email

        Returns
        -------
        dict - Response
            response
        """
        query = db.GqlQuery("SELECT * FROM ActiveLinks WHERE link = :1", link)
        result = query.fetch(1)
        if result:
            u_query = db.GqlQuery("SELECT * FROM Users WHERE __key__ = :1", db.Key(result[0].user))
            uresult = u_query.get()
            uresult.active = True
            db.put(uresult)
            db.delete(result)
            return dict(response=True)
        else:
            return dict(response=False)
Example #44
0
    def test_subscription(self):
        sd = 'haiti'
        email1 = '*****@*****.**'
        email2 = '*****@*****.**'
        s1 = model.Subscription.create(sd, self.p1.record_id, email1, 'fr')
        s2 = model.Subscription.create(sd, self.p1.record_id, email2, 'en')
        key_s1 = db.put(s1)
        key_s2 = db.put(s2)

        assert model.Subscription.get(sd, self.p1.record_id,
                                      email1) is not None
        assert model.Subscription.get(sd, self.p1.record_id,
                                      email2) is not None
        assert model.Subscription.get(sd, self.p2.record_id, email1) is None
        assert model.Subscription.get(sd, self.p2.record_id, email2) is None
        assert len(self.p1.get_subscriptions()) == 2
        assert len(self.p2.get_subscriptions()) == 0

        s3 = model.Subscription.create(sd, self.p1.record_id, email2, 'ar')
        key_s3 = db.put(s3)
        assert len(self.p1.get_subscriptions()) == 2
        assert model.Subscription.get(sd, self.p1.record_id,
                                      email2).language == 'ar'
        db.delete([key_s1, key_s2, key_s3])
Example #45
0
    def delete(self):
        """Exposed as `DELETE /api/photos`.

    Accepts the following request parameters.

    'photoId': id of the photo to delete.

    Returns the following JSON response representing success.
    'Photo successfully deleted.'

    Issues the following errors along with corresponding HTTP response codes:
    401: 'Unauthorized request' (if certain parameters are present in the
         request)
    404: 'Photo with given ID does not exist.'
    """
        try:
            user = self.get_user_from_session()
            photo_id = self.request.get('photoId')
            if photo_id:
                photo = model.Photo.get_by_id(long(photo_id))
                if photo.owner_user_id != user.key().id():
                    raise UserNotAuthorizedException
                photoVotes = model.Vote.all().filter("photo_id =",
                                                     photo.key().id()).run()
                db.delete(photo)
                db.delete(photoVotes)
                self.send_success(
                    model.Message(message="Photo successfully deleted"))
            else:
                raise NotFoundException
        except NotFoundException as nfe:
            self.send_error(404, nfe.msg)
        except TypeError as te:
            self.send_error(404, "Resource not found")
        except UserNotAuthorizedException as e:
            self.send_error(401, e.msg)
Example #46
0
    def get(self):

        # Create some test data.
        here = Location(name='Upper Shore')
        here.put()
        location_key = here.key()

        bottle = Bottle(name='heavy jug',
                        location=here,
                        weight=125,
                        contents='apple juice',
                        amount=10,
                        is_closed=True)
        bottle.put()

        tuba = MusicalInstrument(name='tuba', location=here, weight=200)
        tuba.put()

        # ...

        here = db.get(location_key)
        self.response.write('<p>Your location: %s</p>' % here.name)

        q = CarryableObject.all()
        q.filter('location', here)
        q.filter('weight >', 100)
        self.response.write('<p>You see the following heavy objects:</p><ul>')
        for obj in q:
            self.response.write('<li>%s</li>' % obj.name)
        self.response.write('</ul>')

        db.delete([here, bottle, tuba])
        self.response.write('<p>Entities deleted.</p>')

        self.response.write('<p>The time is: %s</p>' %
                            str(datetime.datetime.now()))
Example #47
0
 def post(self):
     original_url = self.request.headers['Referer']
     stream_name = re.findall('=(.*)%3D%3D', original_url)[0]
     stream = Stream.query(
         Stream.name == stream_name,
         Stream.author == users.get_current_user()).fetch()[0]
     dellsts = self.request.get_all("status")
     print dellsts
     pictures = db.GqlQuery(
         "SELECT * FROM Picture " + "WHERE ANCESTOR IS :1 AND imgkey IN :2",
         db.Key.from_path('Stream', stream_name), dellsts)
     for picture in pictures:
         blobstore.delete(picture.imgkey)
         images.delete_serving_url(picture.imgkey)
     db.delete(pictures)
     pic_count = Count_pic.query(
         ancestor=ndb.Key('Stream', stream_name)).fetch()[0]
     #  print(pic_counts)
     # for pic_count in pic_counts:
     pic_count.numbers = pic_count.numbers - len(dellsts)
     pic_count.put()
     stream.numberofpictures = pic_count.numbers
     stream.put()
     self.redirect(original_url)
Example #48
0
    def post(self):
        tumblr_email = "*****@*****.**"
        tumblr_password = "******"
        #前回のデータをDBから削除
        q = db.GqlQuery("SELECT * FROM Log_table")
        results = q.fetch(1000)
        db.delete(results)

        #一度に読み込むpost数
        num = 50
        acount = self.request.get('content')
        d = datetime.datetime.today()
        for i in range(2):
            time.sleep(0.2)
            url = 'http://www.tumblr.com/api/dashboard?email=' + tumblr_email + '&password='******'&num=' + str(
                num) + '&start=' + str(i * num) + '&type=photo'
            req = urllib2.Request(url)
            content = urllib2.urlopen(req).read()
            soup = BeautifulSoup.BeautifulSoup(content)
            #postに対する処理
            for post in soup('post'):
                log_table = Log_table()
                log_table.width = int(post.get('width'))
                log_table.height = int(post.get('height'))
                log_table.post_url = post.get('url')
                log_table.img_url = post('photo-url')[3].renderContents()
                log_table.put()

        log_tables_query = Log_table.all()
        log_tables = log_tables_query.fetch(50)

        template_values = {
            'log_tables': log_tables,
        }
        path = os.path.join(os.path.dirname(__file__), 'log2.html')
        self.response.out.write(template.render(path, template_values))
Example #49
0
    def get(self):

        # Create some test data.
        g1 = Guild(name='The Foo Battlers')
        g2 = Guild(name='The Bar Fighters')
        db.put([g1, g2])

        p1 = Player(name='druidjane', guilds=[g1.key(), g2.key()])
        p2 = Player(name='TheHulk', guilds=[g2.key()])
        db.put([p1, p2])

        player_key = p1.key()
        guild_key = g2.key()

        # ...

        # Guilds to which a player belongs:
        p = db.get(player_key)
        guilds = db.get(p.guilds)  # batch get using list of keys
        self.response.write('<p>Guilds to which druidjane belongs:</p><ul>')
        for guild in guilds:
            self.response.write('<li>%s</li>' % guild.name)
        self.response.write('</ul>')

        # Players that belong to a guild:
        g = db.get(guild_key)
        self.response.write('<p>Members of The Bar Fighters:</p><ul>')
        for player in g.members:
            self.response.write('<li>%s</li>' % player.name)
        self.response.write('</ul>')

        db.delete([p1, p2, g1, g2])
        self.response.write('<p>Entities deleted.</p>')

        self.response.write('<p>The time is: %s</p>' %
                            str(datetime.datetime.now()))
Example #50
0
def modify_question_act(request):
    user = users.get_current_user()
    if user:
        a = 'aaa'
        #return render(request,'login.html', { 'user':user, 'google_url': users.create_login_url('/reviews/') })
    else:
        return render(request, 'login.html', {
            'user': user,
            'google_url': users.create_login_url('/myquestions/')
        })

    if request.method == 'POST':
        items = request.POST
        idVal = items['identifier']
        myKey = db.Key.from_path('Questions', idVal)
        question = db.get(myKey)
        logging.info("The id is: " + idVal)
        question.modifydate = datetime.datetime.now()
        question.title = items['title']
        question.description = items['description']
        question.put()

        all_tags = db.Query(Tags)
        my_tags = all_tags.filter("question_id =", idVal)
        for tag in my_tags:
            db.delete(tag)

        if items['tag']:
            tags = items['tag'].split(':')
            for i in tags:
                tag = Tags()
                tag.tag_name = i
                tag.question_id = idVal
                tag.put()

    return redirect('/my_question')
Example #51
0
    def delete(self):
        """
        Deletes an entity from the session in memcache and the datastore

        Returns True
        """
        try:
            db.delete(self)
        except:
            self.deleted = True
        mc_items = memcache.get(u"_AppEngineUtilities_SessionData_%s" % \
            (str(self.session.key())))
        value_handled = False
        for item in mc_items:
            if value_handled == True:
                break
            if item.keyname == self.keyname:
                if self.deleted == True:
                    item.deleted = True
                else:
                    mc_items.remove(item)
                memcache.set(u"_AppEngineUtilities_SessionData_%s" % \
                    (str(self.session.key())), mc_items)
        return True
Example #52
0
 def tx():
     operation = DatastoreAdminOperation.get(operation_key)
     if mapreduce_id in operation.active_job_ids:
         operation.active_jobs -= 1
         operation.completed_jobs += 1
         operation.active_job_ids.remove(mapreduce_id)
     if not operation.active_jobs:
         if operation.status == DatastoreAdminOperation.STATUS_ACTIVE:
             operation.status = DatastoreAdminOperation.STATUS_COMPLETED
         db.delete(
             DatastoreAdminOperationJob.all().ancestor(
                 operation),
             config=db_config)
     operation.put(config=db_config)
     if 'done_callback_handler' in mapreduce_params:
         done_callback_handler = util.for_name(
             mapreduce_params['done_callback_handler'])
         if done_callback_handler:
             done_callback_handler(operation, mapreduce_id,
                                   mapreduce_state)
         else:
             logging.error(
                 'done_callbackup_handler %s was not found',
                 mapreduce_params['done_callback_handler'])
Example #53
0
	def deletequiz(self, quiz):
		for session in quiz.sessions:
			self.deletesession(session)
		for question in quiz.questions:
			self.deletequestion(question, users.get_current_user(), True)
		for subscription in quiz.subscriptions:
			db.delete(subscription)
		for selector in quiz.question_selectors:
			db.delete(selector)
		db.delete(quiz)
Example #54
0
	def deletequestion(self, question, user, deleting_quiz=False):
		if user != question.quiz.owner and not users.is_current_user_admin():
			return
		for choice in question.choices:
			self.deletechoice(choice, user)
		for response in question.responses:
			db.delete(response)
		for autoquiz_question in question.autoquiz_questions:
			db.delete(autoquiz_question)
		for comment in question.comments:
			self.deletecomment(comment, user, True)
		for retry in question.retries:
			db.delete(retry)
		
		if not deleting_quiz:
			question.quiz.question_count -= 1
			question.quiz.put()
		db.delete(question)
Example #55
0
    def post(self):
        """Exposed as `POST /api/disconnect`.

    As required by the Google+ Platform Terms of Service, this end-point:

      1. Deletes all data retrieved from Google that is stored in our app.
      2. Revokes all of the user's tokens issued to this app.

    Takes no request payload, and disconnects the user currently identified
    by their session.

    Returns the following JSON response representing the User that was
    connected:

      'Successfully disconnected.'

    Issues the following errors along with corresponding HTTP response codes:
    401: 'Unauthorized request'.  No user was connected to disconnect.
    500: 'Failed to revoke token for given user: '******'Successfully disconnected.')
            return
        except UserNotAuthorizedException as e:
            self.send_error(401, e.msg)
            return
        except RevokeException as e:
            self.send_error(500, e.msg)
            return
Example #56
0
    def DeleteAll(self):
        print "DELETED!"
        db.delete(OilGasLease.all())
        db.delete(DocImage.all())
        db.delete(Tract.all())

        query = blobstore.BlobInfo.all()
        blobs = query.fetch(400)
        if len(blobs) > 0:
            for blob in blobs:
                blob.delete()
Example #57
0
    def purgePrevious(self):
        q = db.GqlQuery("SELECT * FROM GP")
        for ent in q:
            db.delete(ent)
        q = db.GqlQuery("SELECT * FROM C")
        for ent in q:
            db.delete(ent)

        q = db.GqlQuery("SELECT * FROM P")
        for ent in q:
            db.delete(ent)
Example #58
0
    def handle(self):
        mapreduce_id = self.request.get("mapreduce_id")
        db.delete(model.MapreduceControl.get_key_by_job_id(mapreduce_id))

        shards = model.ShardState.find_by_mapreduce_id(mapreduce_id)
        db.delete(shards)

        db.delete(model.MapreduceState.get_key_by_job_id(mapreduce_id))

        self.json_response["status"] = ("Job %s successfully cleaned up." %
                                        mapreduce_id)
Example #59
0
def clean_gae():
    query = Entry.all()
    entries = query.fetch(1000)
    db.delete(entries)

    query = Country.all()
    countries = query.fetch(1000)
    db.delete(countries)

    query = Tag.all()
    tags = query.fetch(1000)
    db.delete(tags)
Example #60
0
 def delete_post(self, user):
     """Delete this post, and all comments and votes related to it."""
     if user.key().id() == self.created_by.key().id():
         blog_entry_votes = VotesEntity.all().filter('voteOn = ', self)
         blog_entry_comments = CommentsEntity.all().filter(
             'commentOn = ', self)
         db.delete(blog_entry_votes)
         db.delete(blog_entry_comments)
         db.delete(self)
     else:
         raise myExceptions.EditOthersPosts(
             'You do not have access to delete this post.')