Beispiel #1
0
	def getInventory(self):
		toon = Toon.get_by_key_name(key_names=self.request.get("toonName"))
		inventory = toon.inventories.get()
		items = []
		for item in db.query_descendants(inventory):
			items.append(item.toDict())
		self.res['content']=items
Beispiel #2
0
  def getEmailToEventObject(cycle, opt_pageOffset):
    if (opt_pageOffset):
      page_offset = opt_pageOffset
    else:
      page_offset = 0

    fetched_events = db.query_descendants(cycle).run(
        limit=50, offset=50*page_offset)

    user_event_map = {}
    events_processed = 0
    if (fetched_events):
      for event in fetched_events:
        email = event.owner
        if (not email in user_event_map):
          user_event_map[email] = []
        eventJson = {
          "id": event.event_id,
          "summary": event.summary,
          "state": event.state,
          "calendar_id": event.calendar_id,
          "location": event.event_location,
          "recurrence": event.recurrence,
          "startTime": event.start_time,
          "link": event.link
        }
        user_event_map[email].append(eventJson)
        events_processed += 1

    logging.info("user_event_map: " + str(user_event_map))
    return {
        "events": user_event_map, 
        "more_to_come": not events_processed < 50,
        "next_page": page_offset + 1
      }
Beispiel #3
0
    def post(self):
        form = cgi.FieldStorage()
        category_name = form["category"].value
        if category_name in form:
            category_user = form[category_name].value
        else:
            category_user = form["category_user"].value
        global current_user
        uname = User(key_name=category_user)
        category = Category(key_name=category_name, parent=uname)

        items = db.query_descendants(category)
        item1 = items[randint(0, items.count() - 1)]
        if "item1" in form:
            prev_item1 = form["item1"].value
            while item1.name == prev_item1:
                item1 = items[randint(0, items.count() - 1)]
        item2 = items[randint(0, items.count() - 1)]
        while item1.name == item2.name:
            item2 = items[randint(0, items.count() - 1)]
        template_values = {
            "item1": item1.name,
            "item2": item2.name,
            "category": category_name,
            "category_user": category_user,
        }
        path = os.path.join(os.path.dirname(__file__), "vote_display_items.html")
        self.response.out.write(template.render(path, template_values))
Beispiel #4
0
 def points(self):
     """Returns a list with all the points in the path"""
     indexes = db.query_descendants(self)
     if indexes.count() == 0:
         raise db.InternalError('Index doesn\'t exist')
     # seria mejor hacer un get() con la lista de cada index en vez de uno agrupando todas las listas
     return RouteUserPoint.get(reduce(list.__add__,[index.points for index in indexes]))
Beispiel #5
0
    def post(self):
        form = cgi.FieldStorage()
        category_name = (form["category"].value).strip(" ")
        action = (form["action"].value).strip(" ")
        global current_user

        uname = User(key_name=current_user.nickname())
        category = Category(key_name=category_name, parent=uname)
        items = db.query_descendants(category)

        if action == "Edit Items":
            template_values = {"category": category_name, "allItems": items}
            path = os.path.join(os.path.dirname(__file__), "editItems.html")

        elif action == "Change name":
            template_values = {"category": category_name}
            path = os.path.join(os.path.dirname(__file__), "changeCatName.html")
        else:
            for item in items:
                item.delete()
            category.delete()

            self.response.out.write("You have deleted category: %s" % category_name)
            self.response.out.write("<br><br><div>Go back to the <a href=" "/" ">welcome page</a><div>")
            return

        self.response.out.write(template.render(path, template_values))
Beispiel #6
0
 def get(self):
     posts = Remind.all()
     tags = Tag.all()
     aggregates = {'nodes': [], 'links': []} # {'source': 0, 'target': 5, 'value':3}
     params = {}
     reminds = {}
     tag_list = {}
     users_array = []
     for p in posts:
        reminds[str(p.key().name())] = p
        parent = len(aggregates['nodes'])
        aggregates['nodes'].append({'pos': parent, 'name' : p.key().name(), 'group': 'Remind', 'relateds': p.countRelated })
        if p.author not in users_array:
          users_array.append(p.author)
        children = db.query_descendants(p)
        for rel in children:
            child = len(aggregates['nodes'])
            aggregates['nodes'].append({'pos': child, 'name': rel.key().name(), 'group': 'Related'})
            aggregates['links'].append({'source': parent, 'target': child, 'value':1})
        
     for t in tags:
        tag_list[str(t.key().name())] = {'tagName' : t.tagName}
        tag_pos = len(aggregates['nodes'])
        aggregates['nodes'].append({'pos': tag_pos, 'name' : t.tagName, 'group': 'Tag', 'relateds': t.tagCounter })
        for p in t.remindsTo:
              for i in aggregates['nodes']:
                 if i['name'] == p.key().name():
                    aggregates['links'].append({'source': tag_pos, 'target': i['pos'], 'value':1})                  
    
     params['reminds'] = reminds
     params['users_array'] = users_array
     params['tags'] = tag_list
     params['aggregates'] = json.dumps(aggregates)
     self.render_template('home.html', params)
Beispiel #7
0
    def post(self):
        global current_user
        form = cgi.FieldStorage()
        category_name = (form["category"].value).strip(" ")
        category_user = (form[category_name].value).strip(" ")
        uname = User(key_name=category_user)
        category = Category(key_name=category_name, parent=uname)
        allItems = db.query_descendants(category)

        doc = Document()
        # create category element
        cat = doc.createElement("CATEGORY")
        doc.appendChild(cat)
        # create name element
        name = doc.createElement("NAME")
        cat.appendChild(name)
        # create text node inside name
        n = doc.createTextNode(category_name)
        name.appendChild(n)

        for i in allItems:
            # create item element
            item = doc.createElement("ITEM")
            cat.appendChild(item)
            # create name element
            name = doc.createElement("NAME")
            item.appendChild(name)
            # create text node inside name
            n = doc.createTextNode(i.name)
            name.appendChild(n)

        self.response.out.write("%s" % doc.toprettyxml())
        self.response.out.write("<br><br><div>Go back to the <a href=" "/" ">welcome page</a><div>")
Beispiel #8
0
    def post(self):
        form = cgi.FieldStorage()
        if "category" not in form:
            self.response.out.write("<h3><i>No keyword was give. Please try again</i><h3>")
            self.response.out.write("<div>Go back to the <a href=" "/" ">welcome page</a><div>")
            return
        keyword = (form["keyword"].value).strip(" ")
        list = []
        allUsers = db.GqlQuery("SELECT * " "FROM User ")

        count = 0
        for user in allUsers:
            all = db.query_descendants(user)
            for a in all:
                if keyword in a.name:
                    list.append(a.name)
                    count = count + 1
                    # self.response.out.write("%s<br>" % a.name)
        if count == 0:
            self.response.out.write("<h3><i>Sorry nothing matched your search</i></h3>")
            self.response.out.write("<div>Go back to the <a href=" "/" ">welcome page</a></div>")
            return

        self.response.out.write("<h3><i>The results for the keyword %s are:</i></h3><br>" % keyword)

        for word in list:
            self.response.out.write("%s<br>" % word)

        self.response.out.write("<br><br><div>Go back to the <a href=" "/" ">welcome page</a><div>")
Beispiel #9
0
    def get(self):
        posts = Remind.all()
        tags = Tag.all()
        aggregates = {
            'nodes': [],
            'links': []
        }  # {'source': 0, 'target': 5, 'value':3}
        params = {}
        reminds = {}
        tag_list = {}
        users_array = []
        for p in posts:
            reminds[str(p.key().name())] = p
            parent = len(aggregates['nodes'])
            aggregates['nodes'].append({
                'pos': parent,
                'name': p.key().name(),
                'group': 'Remind',
                'relateds': p.countRelated
            })
            if p.author not in users_array:
                users_array.append(p.author)
            children = db.query_descendants(p)
            for rel in children:
                child = len(aggregates['nodes'])
                aggregates['nodes'].append({
                    'pos': child,
                    'name': rel.key().name(),
                    'group': 'Related'
                })
                aggregates['links'].append({
                    'source': parent,
                    'target': child,
                    'value': 1
                })

        for t in tags:
            tag_list[str(t.key().name())] = {'tagName': t.tagName}
            tag_pos = len(aggregates['nodes'])
            aggregates['nodes'].append({
                'pos': tag_pos,
                'name': t.tagName,
                'group': 'Tag',
                'relateds': t.tagCounter
            })
            for p in t.remindsTo:
                for i in aggregates['nodes']:
                    if i['name'] == p.key().name():
                        aggregates['links'].append({
                            'source': tag_pos,
                            'target': i['pos'],
                            'value': 1
                        })

        params['reminds'] = reminds
        params['users_array'] = users_array
        params['tags'] = tag_list
        params['aggregates'] = json.dumps(aggregates)
        self.render_template('home.html', params)
Beispiel #10
0
 def points(self):
     """Returns a list with all the points in the path"""
     indexes = db.query_descendants(self)
     if indexes.count() == 0:
         raise db.InternalError('Index doesn\'t exist')
     # seria mejor hacer un get() con la lista de cada index en vez de uno agrupando todas las listas
     return RouteUserPoint.get(
         reduce(list.__add__, [index.points for index in indexes]))
Beispiel #11
0
def generate_survey_csv(brand):
	try:
		out=cStringIO.StringIO()
		surveyProps = configparsers.loadPropertyFile('survey_'+brand)
		
		"""
		Generate CSV file output VALUES
		"""
		surveys = datastore.get_surveys_by_brand(brand)

		# [ST] DEBUG: Returning just the first Survey, to test the Admin mail.send_to_admins() service 
		# due to quota size exception on the attachment
		# surveys = [surveys.get()]
		
		sortedSections = None
		counter = 0
		for survey in surveys:
			sections = dict()
			surveyResults = list()

			descendants = db.query_descendants(survey)
			for descendant in descendants:
				section = descendant
				_id = section.kind()
				# If the Section Model has properties, and it exists in the Survey Properties ConfigParser file (e.g. is not the User model)...
				if hasattr(section, 'properties') and surveyProps.has_section(_id):
					sections[_id] = dict()
					sections[_id]['index'] = surveyProps.getint(_id, 'index')
					sections[_id]['section'] = section
					surveyResults.append(sections[_id])

			sortedSections = sorted(surveyResults, key=itemgetter('index'), reverse=False)
			
			if counter == 0:
				# for each section within the survey
				out.write('Created,Client,Account,')
				for section in sortedSections:
					for question, data in section['section'].properties().items():
						out.write('\"'+str(surveyProps.get(section['section'].kind(), 'name')+' : '+data.verbose_name)+'\",')					
				out.write('\n')
			
			out.write(str(survey.created.date().isoformat())+',')
			out.write(str(survey.user_id.name)+',')
			out.write(str(survey.user_id.account)+',')
			for section in sortedSections:
				for question, data in section['section'].properties().items():
					answer = getattr(section['section'], question)
					# CGI Escape the output of the answer, in case there are '<', '>', '&' or '"' characters in there. The double quote will break the CSV formatting
					out.write('\"'+cgi.escape(str(answer), quote=True)+'\",')
			out.write('\n')
			counter += 1
			
		return out
	except (Exception), e:
		logging.error(e)
		raise e
Beispiel #12
0
	def post(self,survey_id):
		survey = Survey.get_by_id(int(survey_id))
		if survey:
			descendants = db.query_descendants(survey)
			for descendant in descendants:
				descendant.delete()
			survey.delete()
			self.redirect('/')
		else:
			self.redirect(users.create_login_url(self.request.uri))
Beispiel #13
0
def find(specname, sample, similarity, tolerance = 0.0):
    spec = db.get(db.Key.from_path('SpecTable',specname))
    if not spec:
        raise ValueError("Specialiser '%s' not registered" % specname)
    table = db.query_descendants(spec)
    f = get_sim_func(similarity, specname)
    platform = Platform.from_data(sample['platform'])
    sampleRec = Record(parent = spec, platform = platform, **sample['data'])
    logging.debug('Specialiser properties: %s' % spec.key_fields)
    return map(lambda result: dict([(key,result[key]) for key in spec.key_fields]), filter(lambda record: (f(sampleRec, record) >= tolerance), table) )
Beispiel #14
0
 def delete_below(self):
     """
     Delete all nodes below, including descendants.
     Does not delete self.
     TODO: reimplement to use fast delete
     """
     for m in self.dir_members:
         m.delete_below()
         m.delete()
     for d in db.query_descendants(self).run():
         d.delete()
Beispiel #15
0
    def post(self):
        global current_user
        form = cgi.FieldStorage()
        category_name = (form["category"].value).strip(" ")
        category_user = (form["category_user"].value).strip(" ")
        uname = User(key_name=category_user)
        category = Category(key_name=category_name, parent=uname)
        allItems = db.query_descendants(category)

        template_values = {"category": category_name, "allItems": allItems}

        path = os.path.join(os.path.dirname(__file__), "results.html")
        self.response.out.write(template.render(path, template_values))
Beispiel #16
0
 def getEmailToEventId(cycle):
   # Gets a map of email address : event object for the given cycle ID.
   user_event_map = {}
   if (cycle):
     fetched_events = db.query_descendants(cycle).run(batch_size=1000)
     logging.info("got events: " + str(fetched_events))
     if (fetched_events):
       for event in fetched_events:
         email = event.owner
         if (not email in user_event_map):
           user_event_map[email] = []
         user_event_map[email].append(event.event_id)
   logging.info("user_event_map: " + str(user_event_map))
   return user_event_map
Beispiel #17
0
  def post(self, my_list):
    items = db.query_descendants(my_list)

    to_delete = []
    for item in items:
      if item.completed:
        to_delete.append(item)
        my_list.task_count -= 1

    if to_delete:
      my_list.put()
      db.delete(to_delete)

    self.json({'list': my_list.to_dict(), 'items': [i.to_dict() for i in items]})
Beispiel #18
0
    def post(self):
        form = cgi.FieldStorage()
        global current_user

        if "category" not in form:
            self.response.out.write("<h3><i>Wrong input, please try again</i><h3>")
            self.response.out.write("<div>Go back to the <a href=" "/" ">welcome page</a><div>")
            return

        new_name = (form["category"].value).strip(" ")
        old_name = (form["oldCat"].value).strip(" ")
        category = (form["category"].value).strip(" ")

        user_key = db.Key.from_path("User", current_user.nickname())
        userCategories = db.GqlQuery("SELECT * " "FROM Category " "WHERE ANCESTOR IS :1 ", user_key)
        for c in userCategories:
            if c.name == new_name:
                self.response.out.write("<h3><i>You already have a category with this name.</i></h3>")
                self.response.out.write("<div>Go back to the <a href=" "/" ">welcome page</a><div>")
                return

        global current_user
        uname = User(key_name=current_user.nickname())
        # get old category and items
        oldCat = Category(key_name=old_name, parent=uname)
        items = db.query_descendants(oldCat)

        uname = User(key_name=current_user.nickname())
        # create new category with the new name
        category = Category(key_name=new_name, parent=uname)
        category.name = new_name
        category.user = current_user.nickname()
        category.put()

        newCat = Category(key_name=new_name, parent=uname)

        for old_item in items:
            new_item = Item(key_name=old_item.name, parent=newCat)
            new_item.name = old_item.name
            new_item.wins = old_item.wins
            new_item.put()

        for old_item in items:
            old_item.delete()
        oldCat.delete()
        self.response.out.write(
            "<h4>You have changed the name of the category from <i>%s</i> to <i>%s</i></h4>" % (old_name, new_name)
        )
        self.response.out.write("<br><div>Go back to the <a href=" "/" ">welcome page</a></div>")
        return
Beispiel #19
0
	def post(self,survey_id,question_id):
		survey = Survey.get_by_id(int(survey_id))
		if survey:
			question = db.Query(Question).ancestor(survey).filter('index = ', int(question_id)).get()
			greater_questions = db.Query(Question).ancestor(survey).filter('index > ', int(question_id))
			descendants = db.query_descendants(question)
			for descendant in descendants:
				descendant.delete()
			question.delete()
			for greater_question in greater_questions:
				greater_question.index = greater_question.index - 1
				greater_question.put()
			self.redirect('/'+survey_id)
		else:
			self.redirect(users.create_login_url(self.request.uri))
Beispiel #20
0
  def post(self, my_list):
    items = db.query_descendants(my_list)

    completed = self.request.get('completed') != '0'

    to_put = []
    for item in items:
      if item.completed != completed:
        item.completed = completed
        to_put.append(item)
    if to_put:
      # Saves all the items at once.
      db.put(to_put)

    self.json({'list': my_list.to_dict(), 'items': [i.to_dict() for i in items]})
Beispiel #21
0
 def get(self):
     event = Event.get_by_id(int(self.request.GET.keys()[0]))
     assert users.get_current_user().email() == event.user.email()
     registrations = [x.to_dict() for x in db.query_descendants(event).run()]
     comps = {}
     for r in registrations:
         r['competitions'] = [x for x in r['competitions'] if x[1]]
         for comp in r['competitions']:
             for div in comp[1]:
                 bar = comps.setdefault(comp[0]+' '+div, [])
                 bar.append({
                     'user': r['user'],
                     'first_name': r['first_name'],
                     'last_name': r['last_name'],
                     'lead_follow': r['lead_follow'],
                 })
     result = {
         'event': event.to_dict(),
         'user': users.get_current_user().email(),
         'comps': comps,
         }
     self.response.write(toJSON(result))
Beispiel #22
0
 def delete(self):
     indexes = db.query_descendants(self)
     for index in indexes:
         index.delete()
     super(self.__class__, self).delete()
Beispiel #23
0
    def post(self):
        form = cgi.FieldStorage()
        category_name = form["category"].value
        category_user = form["category_user"].value
        global current_user
        uname = User(key_name=category_user)

        category_name = form["category"].value
        item_name = (form.getvalue("item")).strip(" ")
        item1 = (form.getvalue("item1")).strip(" ")
        item2 = (form.getvalue("item2")).strip(" ")

        item_k = db.Key.from_path("User", category_user, "Category", category_name, "Item", item_name)
        item_address = db.get(item_k)

        item_address.wins = item_address.wins + 1
        item_address.put()

        if item_name == item1:
            winnerWins = item_address.wins
            other_k = db.Key.from_path("User", category_user, "Category", category_name, "Item", item2)
            other_address = db.get(other_k)
            otherWins = other_address.wins
            template_values = {
                "winner": item1,
                "otherItem": item2,
                "winnerWins": winnerWins,
                "otherWins": otherWins,
                "category_user": category_user,
                "category": category_name,
            }
        else:
            winnerWins = item_address.wins
            other_k = db.Key.from_path("User", category_user, "Category", category_name, "Item", item1)
            other_address = db.get(other_k)
            otherWins = other_address.wins
            template_values = {
                "winner": item2,
                "otherItem": item1,
                "winnerWins": winnerWins,
                "otherWins": otherWins,
                "category_user": category_user,
                "category": category_name,
            }
        path = os.path.join(os.path.dirname(__file__), "generate_table.html")
        self.response.out.write(template.render(path, template_values))

        category = Category(key_name=category_name, parent=uname)
        items = db.query_descendants(category)
        item1 = items[randint(0, items.count() - 1)]
        if "item1" in form:
            prev_item1 = form["item1"].value
            while item1.name == prev_item1:
                item1 = items[randint(0, items.count() - 1)]
        item2 = items[randint(0, items.count() - 1)]
        while item1.name == item2.name:
            item2 = items[randint(0, items.count() - 1)]
        template_values = {
            "item1": item1.name,
            "item2": item2.name,
            "category": category_name,
            "category_user": category_user,
        }
        path = os.path.join(os.path.dirname(__file__), "vote_display_items.html")
        self.response.out.write(template.render(path, template_values))
Beispiel #24
0
def change_occurrenceset_key(entity):
    """Changes an OccurrenceSet entity key.

    Note: Entity keys are immutable, so we're just creating a new OccurrenceSet 
    entity and deleting the old one.

    Incoming OccurrenceSet key_names look like this:
        wwf/ecoregion/id
        wdpa/pa/id

    We want to change key_names so that they look like this:
        wwf/ecoregion-group/id
        wdpa/pa-group/id
    
    The following entities have an OccurrenceSet parent, so their keys need
    to change as well. Again, since keys are immutable, these entities will
    be deleted and new ones will be created:
        OccurrenceSetIndex
        MasterSearchIndex

    The following entities have an OccurrenceSet ReferenceProperty which will
    get replaced:
        OccurrenceIndex
    
    Arguments:
        entity - An OccurrenceSet entity

    """
    # Calculates the new OccurrenceSet key_name:
    key_name = entity.key().name()
    if key_name.rfind("ecoregion") > -1:
        new_key_name = key_name.replace("ecoregion", "ecoregion-group")
    elif key_name.rfind("pa") > -1:
        new_key_name = key_name.replace("pa", "pa-group")

    # Creates the new OccurrenceSet entity:
    yield op.db.Put(
        OccurrenceSet(
            key_name=new_key_name,
            name=entity.name,
            subname=entity.subname,
            source=entity.source,
            category=entity.category,
            info=entity.info,
            dateCreated=entity.dateCreated,
        )
    )

    new_key = db.Key.from_path("OccurrenceSet", new_key_name)

    # Updates all OccurrenceSet decendants with a new parent:
    for decendent in db.query_descendants(entity):
        kind = decendent.key().kind()
        if kind == "OccurrenceSetIndex":
            new_decendant = OccurrenceSetIndex(parent=new_key, term=decendent.term, rank=decendent.rank)
        elif kind == "MasterSearchIndex":
            new_decendant = MasterSearchIndex(parent=new_key, term=decendent.term, rank=decendent.rank)
        else:
            logging.error("Unknown decendant of OccurrenceSet: %s" % decendant)
            continue
        yield op.db.Put(new_decendant)
        yield op.db.Delete(decendent)

    # Updates reference property in OccurrenceSetIndex:
    osi = entity.polygons.get()
    if osi:
        osi.occurrenceSet = new_key
        yield op.db.Put(osi)

    # Deletes the OccurrenceSet:
    yield op.db.Delete(entity)
Beispiel #25
0
 def delete_async(self):
     children = db.query_descendants(self).fetch(100)
     for c in children:
         c.delete()
     return db.delete_async(self)
Beispiel #26
0
 def delete(self):
     indexes = db.query_descendants(self)
     for index in indexes:
         index.delete()
     super(self.__class__, self).delete()
Beispiel #27
0
 def delete(self):
     children = db.query_descendants(self).fetch(100)
     for c in children:
         c.delete()
     return db.delete_async(self)
Beispiel #28
0
def deep_delete(obj):

    [deep_delete(item) for item in db.query_descendants(obj).fetch(1000)]

    obj.delete()
Beispiel #29
0
def action_get_survey_by_date_and_brand(date, brand):
	
	memcacheKey = 'survey:results:'+str(date.isoformat())	
	memcacheResult = memcache.get(memcacheKey, namespace=brand)
	if memcacheResult is not None:
		logging.debug('Returning processed Survey results from MEMCACHE')
		return memcacheResult
	else:
		logging.debug('Returning processed Survey results from DATASTORE')
		surveys = datastore.get_surveys_by_date_and_brand(date, brand)	
		
		surveyProps = configparsers.loadPropertyFile('survey_'+brand)
	
		sections = dict()
		surveyResults = list()
		# Prepare an object with the Datastore data
		# for each survey

		"""
			[ST]TODO:
		 		Refactor all of this to use the db.query_descendants() method against the Survey model instance received
		 		This will catch pre-PolyModel Survey instances in the Datastore, and saves iterating over all Survey model instance
		 		properties looking for Survey Sections that are classes, and then getting their properties, etc, etc.

		 		Otherwise we end up collecting Survey model instances that have no connected Section model instances :(
		"""
		for survey in surveys:
			# for each section within the survey
			for surveyAttr in survey.properties():
				#logging.debug('actions.py : action_get_survey_by_date_and_brand() : surveyAttr')
				#logging.debug(surveyAttr)
				section = getattr(survey, surveyAttr)

				#logging.debug('actions.py : action_get_survey_by_date_and_brand() : section')
				#logging.debug(type(section))

				# [ST]TODO: Ugly patch for pre-PolyModel Surveys
				if type(section) is list and surveyAttr == '_class' and len(section) <= 1:
					logging.debug('We have a broken Razorfish Survey connection')
					child_sections = db.query_descendants(survey)
					for child in child_sections:
						logging.debug(child)
				else:
					logging.debug('We have found a Razorfish Survey')

				# If the Section Model has properties, and it exists in the Survey Properties ConfigParser file (e.g. is not the User model)...
				if section is not None and hasattr(section, 'properties') and surveyProps.has_section(section.kind()):
					# If we have not yet created a dict entry for this section, then do so
					
					if surveyAttr not in sections:
						sections[surveyAttr] = dict()
						sections[surveyAttr]['id'] = surveyAttr
						sections[surveyAttr]['created'] = survey.created
						sections[surveyAttr]['index'] = surveyProps.get(section.kind(), 'index')
						sections[surveyAttr]['name'] = surveyProps.get(section.kind(), 'name')
						sections[surveyAttr]['results'] = dict()
						surveyResults.append(sections[surveyAttr])

					# for question name and value in the section
					for question, prop in section.properties().items():
						if type(prop) == db.IntegerProperty:
							answer = getattr(section, question)
							# If we have not yet created a dict entry for this question in this section, then do so
							if question not in sections[surveyAttr]['results']:
								sections[surveyAttr]['results'][question] = dict()
								sections[surveyAttr]['results'][question]['id'] = question
								sections[surveyAttr]['results'][question]['name'] = prop.verbose_name
								sections[surveyAttr]['results'][question]['raw'] = list()
								sections[surveyAttr]['results'][question]['count'] = dict()
								sections[surveyAttr]['results'][question]['percentage'] = dict()
								sections[surveyAttr]['results'][question]['options_length'] = len(prop.choices)
								sections[surveyAttr]['results'][question]['type'] = 'multi'
							# Add the answer to the question list
							sections[surveyAttr]['results'][question]['raw'].append(answer)
						if type(prop) == db.TextProperty:
							answer = getattr(section, question)
							
							# If we have not yet created a dict entry for this question in this section, then do so
							if question not in sections[surveyAttr]['results']:
								sections[surveyAttr]['results'][question] = dict()
								sections[surveyAttr]['results'][question]['id'] = question
								sections[surveyAttr]['results'][question]['name'] = prop.verbose_name
								sections[surveyAttr]['results'][question]['answers'] = list()
								sections[surveyAttr]['results'][question]['type'] = 'single'
							
							# IF an answer exists, include this as a tuple with the User model object as the first argument and the answer Text value as the second argument
							if answer != '':	
								sections[surveyAttr]['results'][question]['answers'].append({'user':getattr(survey, 'user_id'), 'answer':answer, 'date':survey.created})
						
		for section, questionSet in sections.items():
			for question, data in questionSet['results'].items():
				# If we have a multiple choice question we need to process the results
				
				if data.has_key('raw') and type(data['raw']) is list:
					base = {}
					base[1]=0
					base[2]=0
					base[3]=0
					base[4]=0
					base[5]=0
					counted = utils.count_unsorted_list_items(data['raw'])				
					data['count'] = dict(base.items() + counted.items())
					sorted(data['count'], reverse=False)
					data['percentage'] = utils.get_percentage(data['count'])
		
		finalResult = sorted(surveyResults, key=itemgetter('index'), reverse=False)
		if len(finalResult) > 0:
			memcache.set(key=memcacheKey, value=finalResult, time=300, namespace=brand)
		return finalResult
Beispiel #30
0
def action_get_survey_sections_by_brand(brand):
	try:
		memcache_key = 'survey:sections:'+str(brand)	
		memcache_result = memcache.get(memcache_key, namespace=brand)
		if memcache_result is not None:
			logging.debug('action_get_survey_sections_by_brand() : Returning processed Survey Section results from MEMCACHE')
			return memcache_result
		else:
			logging.debug('action_get_survey_sections_by_brand() : Returning processed Survey Section results from DATASTORE')
			# Get the Surveys from the Datastore by Brand
			surveys = datastore.get_surveys_by_brand(brand)	
			# Load the Survey Properties, for Content iteration in the HTML Template
			surveyProps = configparsers.loadPropertyFile('survey_'+brand)

			# Create an empty dict for Survey Sections
			sections = dict()
			# Create an empty list for all section results
			section_results = list()
			# For each Survey in the Datastore Query result
			for survey in surveys:
				# Get the Survey descendats
				survey_descendants = db.query_descendants(survey)
				
				for descendant in survey_descendants:
					# Set the Sections dict key to be the Kind (lowercase)
					_id = descendant.kind().lower()
					# Create a Section dict
					if _id not in sections:
						sections[_id] = dict(
							id=_id,
							created=survey.created,
							index=surveyProps.get(descendant.kind(), 'index'),
							name=surveyProps.get(descendant.kind(), 'name'),
							results = dict()
						)
						section_results.append(sections[_id])

					# for question name and value in the descendant section
					for question, prop in descendant.properties().items():
						# If the Property is of type Integer (Long returned from Datastore, actually)
						if type(prop) == db.IntegerProperty:
							answer = getattr(descendant, question)
							
							# If we have not yet created a dict entry for this question in this section, then do so
							if question not in sections[_id]['results']:
								sections[_id]['results'][question] = dict(
									id=question,
									name=prop.verbose_name,
									raw=list(),
									count=dict(),
									percentage=dict(),
									options_length=len(prop.choices),
									type='multi'
								)

							# Add the answer to the question list
							sections[_id]['results'][question]['raw'].append(answer)
							
						# If the Property is of type Text:
						if type(prop) == db.TextProperty:
							answer = getattr(descendant, question)
							
							# If we have not yet created a dict entry for this question in this section, then do so
							if question not in sections[_id]['results']:
								sections[_id]['results'][question] = dict(
									id=question,
									name=prop.verbose_name,
									answers=list(),
									type='single'
								)
							
							# If an answer exists, include this as a tuple with the User model object as the first argument and the answer Text value as the second argument
							if answer != '':	
								sections[_id]['results'][question]['answers'].append({
								'user':getattr(survey, 'user_id'),
								'answer':answer,
								'date':survey.created
							})

				
			# Once we have iterated through all resuts, we need further processing.
			# This calculates the percentages of answers for multiple choice questions
			for section, questionSet in sections.items():
				for question, data in questionSet['results'].items():
					# If we have a multiple choice question we need to process the results
					#logging.debug(question)
					#logging.debug(data)
					if data.has_key('raw') and type(data['raw']) is list:
						base = {}
						if brand == 'razorfish':
							base[0]=0
							base[1]=0
							base[2]=0
							base[3]=0
							base[4]=0
							base[5]=0
						elif brand == 'mcdonalds':
							base[0]=0
							base[1]=0
							base[2]=0
							base[3]=0
							base[4]=0
							
						counted = utils.count_unsorted_list_items(data['raw'])
						#logging.debug('counted')
						#logging.debug(counted)
						data['count'] = dict(base.items() + counted.items())
						sorted(data['count'], reverse=False)
						data['percentage'] = utils.get_percentage(data['count'])
			
			# Finally, we sort our Section Results list, using the index of the section as the sort key
			section_results = sorted(section_results, key=itemgetter('index'), reverse=False)
			
			# Add the result to Memcache, to expire in 5 minutes
			if len(section_results) > 0:
				memcache_stored = memcache.set(memcache_key, value=section_results, time=360, namespace=brand)
			return section_results
	except Exception, e:
		logging.error(type(e))
		logging.error(e)
		raise e
Beispiel #31
0
 def get(self, my_list):
   items = db.query_descendants(my_list)
   items = sorted(items, key=lambda i: i.create_time)
   self.json({'list': my_list.to_dict(), 'items': [i.to_dict() for i in items]})
def students_ofSchool(eSchool):
    returnString = ""
    q = db.query_descendants(eSchool)
    for s in q.run(limit=50):
        returnString += "<p>" + str(s) + "</p>"