def checkAccess(self): self.check.isProfileActive() request_id = int(self.data.kwargs["id"]) self.data.invite = self.data.request_entity = GSoCRequest.get_by_id(request_id) self.check.isRequestPresent(request_id) self.data.organization = self.data.request_entity.org self.data.invited_user = self.data.requester = self.data.request_entity.user if self.data.POST: self.data.action = self.data.POST["action"] if self.data.action == self.ACTIONS["accept"]: self.check.canRespondToRequest() elif self.data.action == self.ACTIONS["reject"]: self.check.canRespondToRequest() elif self.data.action == self.ACTIONS["resubmit"]: self.check.canResubmitRequest() # withdraw action else: self.check.canViewRequest() self.mutator.canRespondForUser() key_name = "/".join([self.data.program.key().name(), self.data.requester.link_id]) self.data.requester_profile = GSoCProfile.get_by_key_name(key_name, parent=self.data.requester)
def _updateFromForm(self): """Updates a proposal based on the data inserted in the form. Returns: an updated proposal entity or None """ proposal_form = ProposalForm(self.data.POST, instance=self.data.proposal) if not proposal_form.is_valid(): return None q = GSoCProfile.all().filter('mentor_for', self.data.proposal.org) q = q.filter('status', 'active') q.filter('notify_proposal_updates', True) mentors = q.fetch(1000) to_emails = [i.email for i in mentors] proposal_key = self.data.proposal.key() def update_proposal_txn(): proposal = db.get(proposal_key) proposal_form.instance = proposal proposal = proposal_form.save(commit=True) context = notifications.updatedProposalContext(self.data, proposal, to_emails) sub_txn = mailer.getSpawnMailTaskTxn(context, parent=proposal) sub_txn() return proposal return db.run_in_transaction(update_proposal_txn)
def checkAccess(self): self.check.isProfileActive() id = int(self.data.kwargs['id']) self.data.invite = self.data.request_entity = Request.get_by_id(id) self.check.isRequestPresent(self.data.request_entity, id) self.data.organization = self.data.request_entity.group self.data.invited_user = self.data.requester = self.data.request_entity.user if self.data.POST: self.data.action = self.data.POST['action'] if self.data.action == self.ACTIONS['accept']: self.check.canRespondToRequest() elif self.data.action == self.ACTIONS['reject']: self.check.canRespondToRequest() elif self.data.action == self.ACTIONS['resubmit']: self.check.canResubmitRequest() # withdraw action else: self.check.canViewRequest() self.mutator.canRespondForUser() key_name = '/'.join( [self.data.program.key().name(), self.data.requester.link_id]) self.data.requester_profile = GSoCProfile.get_by_key_name( key_name, parent=self.data.requester)
def checkAccess(self): self.check.isProfileActive() invite_id = int(self.data.kwargs['id']) self.data.invite = Request.get_by_id(invite_id) self.check.isInvitePresent(invite_id) self.data.organization = self.data.invite.org self.data.invited_user = self.data.invite.user if self.data.POST: self.data.action = self.data.POST['action'] if self.data.action == self.ACTIONS['accept']: self.check.canRespondToInvite() elif self.data.action == self.ACTIONS['reject']: self.check.canRespondToInvite() elif self.data.action == self.ACTIONS['resubmit']: self.check.canResubmitInvite() else: self.check.canViewInvite() self.mutator.canRespondForUser() if self.data.user.key() == self.data.invited_user.key(): self.data.invited_profile = self.data.profile return key_name = '/'.join([ self.data.program.key().name(), self.data.invited_user.link_id]) self.data.invited_profile = GSoCProfile.get_by_key_name( key_name, parent=self.data.invited_user)
def _createFromForm(self): """Creates a new request based on the data inserted in the form. Returns: a newly created Request entity or None """ assert isSet(self.data.organization) request_form = RequestForm(self.data.POST) if not request_form.is_valid(): return None # create a new invitation entity request_form.cleaned_data["user"] = self.data.user request_form.cleaned_data["org"] = self.data.organization request_form.cleaned_data["role"] = "mentor" request_form.cleaned_data["type"] = "Request" q = GSoCProfile.all().filter("org_admin_for", self.data.organization) q = q.filter("status", "active").filter("notify_new_requests", True) admins = q.fetch(1000) admin_emails = [i.email for i in admins] def create_request_txn(): request = request_form.create(commit=True) context = notifications.requestContext(self.data, request, admin_emails) sub_txn = mailer.getSpawnMailTaskTxn(context, parent=request) sub_txn() return request return db.run_in_transaction(create_request_txn)
def checkAccess(self): self.check.isProfileActive() id = int(self.data.kwargs['id']) self.data.invite = self.data.request_entity = Request.get_by_id(id) self.check.isRequestPresent(self.data.request_entity, id) self.data.organization = self.data.request_entity.group self.data.invited_user = self.data.requester = self.data.request_entity.user if self.data.POST: self.data.action = self.data.POST['action'] if self.data.action == self.ACTIONS['accept']: self.check.canRespondToRequest() elif self.data.action == self.ACTIONS['reject']: self.check.canRespondToRequest() elif self.data.action == self.ACTIONS['resubmit']: self.check.canResubmitRequest() # withdraw action else: self.check.canViewRequest() self.mutator.canRespondForUser() key_name = '/'.join([ self.data.program.key().name(), self.data.requester.link_id]) self.data.requester_profile = GSoCProfile.get_by_key_name( key_name, parent=self.data.requester)
def queryAllMentorsKeysForOrg(org, limit=1000): """Returns a list of keys of all the mentors for the organization Args: org: the organization entity for which we need to get all the mentors limit: the maximum number of entities that must be fetched returns: List of all the mentors for the organization """ # get all mentors keys first query = GSoCProfile.all(keys_only=True) query.filter("mentor_for", org) mentors_keys = query.fetch(limit=limit) # get all org admins keys first query = GSoCProfile.all(keys_only=True) query.filter("org_admin_for", org) oa_keys = query.fetch(limit=limit) return set(mentors_keys + oa_keys)
def context(self): """The context for this template used in render(). """ r = self.data.redirect orgs = [] for org in db.get(self.duplicate.orgs): q = GSoCProfile.all() q.filter("org_admin_for", org) q.filter("status", "active") admins = q.fetch(1000) data = {"name": org.name, "link": r.organization(org).urlOf("gsoc_org_home"), "admins": admins} orgs.append(data) context = {"orgs": orgs} return context
def clear(*args, **kwargs): """Removes all entities from the datastore. """ # TODO(dbentley): If there are more than 1000 instances of any model, # this method will not clear all instances. Instead, it should continually # call .all(), delete all those, and loop until .all() is empty. entities = itertools.chain(*[ Notification.all(), GCIStudent.all(), Survey.all(), SurveyRecord.all(), StudentProposal.all(), GSoCOrganization.all(), GCIOrganization.all(), GSoCTimeline.all(), GCITimeline.all(), GSoCProgram.all(), GSoCProfile.all(), GCIProfile.all(), GSoCProposal.all(), GCIProgram.all(), GCIScore.all(), GSoCStudentInfo.all(), GCIStudentInfo.all(), GCITask.all(), Host.all(), Sponsor.all(), User.all(), Site.all(), Document.all(), ]) try: for entity in entities: entity.delete() except db.Timeout: return http.HttpResponseRedirect('#') # pylint: disable=E1101 memcache.flush_all() return http.HttpResponse('Done')
def _convertReferenceProperty(model_property, entity): """Converts the specified ReferenceProperty whose value is either a key of GSoCProfile or GCIProfile type. Args: model_property: Property instance. entity: Entity. Returns: The new value for the specified property which Profile key. """ reference_key = model_property.get_value_for_datastore(entity) if not reference_key: return None elif reference_key.kind() not in [GSoCProfile.kind(), GCIProfile.kind()]: raise ValueError('Invalid kind %s for property %s', (reference_key.kind(), model_property.name)) else: return _newKey(reference_key)
def context(self): """Returns the context for the current template. """ r = self.data.redirect context = {'duplicate': self.duplicate} orgs = db.get(self.duplicate.orgs) proposals = db.get(self.duplicate.duplicates) orgs_details = {} for org in orgs: orgs_details[org.key().id_or_name()] = { 'name': org.name, 'link': r.organization(org).urlOf('gsoc_org_home') } q = GSoCProfile.all() q.filter('org_admin_for', org) q.filter('status', 'active') org_admins = q.fetch(1000) orgs_details[org.key().id_or_name()]['admins'] = [] for org_admin in org_admins: orgs_details[org.key().id_or_name()]['admins'].append({ 'name': org_admin.name(), 'email': org_admin.email }) orgs_details[org.key().id_or_name()]['proposals'] = [] for proposal in proposals: if proposal.org.key() == org.key(): orgs_details[org.key().id_or_name()]['proposals'].append({ 'key': proposal.key().id_or_name(), 'title': proposal.title, 'link': r.review(proposal.key().id_or_name(), proposal.parent().link_id).urlOf( 'review_gsoc_proposal') }) context['orgs'] = orgs_details return context
def createCommentFromForm(self): """Creates a new comment based on the data inserted in the form. Returns: a newly created comment entity or None """ assert isSet(self.data.public_only) assert isSet(self.data.proposal) if self.data.public_only: comment_form = CommentForm(self.data.request.POST) else: # this form contains checkbox for indicating private/public comments comment_form = PrivateCommentForm(self.data.request.POST) if not comment_form.is_valid(): return None if self.data.public_only: comment_form.cleaned_data["is_private"] = False comment_form.cleaned_data["author"] = self.data.profile q = GSoCProfile.all().filter("mentor_for", self.data.proposal.org) q = q.filter("status", "active") if comment_form.cleaned_data.get("is_private"): q.filter("notify_private_comments", True) else: q.filter("notify_public_comments", True) mentors = q.fetch(1000) to_emails = [i.email for i in mentors if i.key() != self.data.profile.key()] def create_comment_txn(): comment = comment_form.create(commit=True, parent=self.data.proposal) context = notifications.newCommentContext(self.data, comment, to_emails) sub_txn = mailer.getSpawnMailTaskTxn(context, parent=comment) sub_txn() return comment return db.run_in_transaction(create_comment_txn)
def _convertReferenceProperty(model_property, entity): """Converts the specified ReferenceProperty whose value is either a key of GSoCProfile or GCIProfile type. Args: model_property: Property instance. entity: Entity. Returns: The new value for the specified property which Profile key. """ reference_key = model_property.get_value_for_datastore(entity) if not reference_key: return None elif reference_key.kind() not in [GSoCProfile.kind(), GCIProfile.kind()]: raise ValueError( 'Invalid kind %s for property %s', (reference_key.kind(), model_property.name)) else: return _newKey(reference_key)
def canTakeOrgApp(self): """A user can take the GCI org app if he/she participated in GSoC or GCI as a non-student. """ from soc.modules.gsoc.models.profile import GSoCProfile self.isUser() q = GSoCProfile.all() q.filter('is_student', False) q.filter('status', 'active') q.filter('user', self.data.user) gsoc_profile = q.get() q = GCIProfile.all() q.filter('is_student', False) q.filter('status', 'active') q.filter('user', self.data.user) gci_profile = q.get() if not (gsoc_profile or gci_profile): raise AccessViolation(DEF_NO_PREV_ORG_MEMBER)
def createFromForm(self): """Creates a new proposal based on the data inserted in the form. Returns: a newly created proposal entity or None """ proposal_form = ProposalForm(self.data.POST) if not proposal_form.is_valid(): return None # set the organization and program references proposal_form.cleaned_data['org'] = self.data.organization proposal_form.cleaned_data['program'] = self.data.program student_info_key = self.data.student_info.key() q = GSoCProfile.all().filter('mentor_for', self.data.organization) q = q.filter('status', 'active') q.filter('notify_new_proposals', True) mentors = q.fetch(1000) to_emails = [i.email for i in mentors] def create_proposal_trx(): student_info = db.get(student_info_key) student_info.number_of_proposals += 1 student_info.put() proposal = proposal_form.create(commit=True, parent=self.data.profile) context = notifications.newProposalContext(self.data, proposal, to_emails) sub_txn = mailer.getSpawnMailTaskTxn(context, parent=proposal) sub_txn() return proposal return db.run_in_transaction(create_proposal_trx)
def checkAccess(self): self.data.proposer_user = User.get_by_key_name( self.data.kwargs['student']) fields = ['sponsor', 'program', 'student'] key_name = '/'.join(self.data.kwargs[i] for i in fields) self.data.proposer_profile = GSoCProfile.get_by_key_name( key_name, parent=self.data.proposer_user) if not self.data.proposer_profile: raise NotFound('Requested user does not exist') self.data.proposal = GSoCProposal.get_by_id( int(self.data.kwargs['id']), parent=self.data.proposer_profile) if not self.data.proposal: raise NotFound('Requested proposal does not exist') self.data.proposal_org = self.data.proposal.org self.check.canAccessProposalEntity() self.mutator.commentVisible()
def checkAccess(self): self.data.proposer_user = User.get_by_key_name(self.data.kwargs['student']) fields = ['sponsor', 'program', 'student'] key_name = '/'.join(self.data.kwargs[i] for i in fields) self.data.proposer_profile = GSoCProfile.get_by_key_name( key_name, parent=self.data.proposer_user) if not self.data.proposer_profile: raise NotFound('Requested user does not exist') self.data.proposal = GSoCProposal.get_by_id( int(self.data.kwargs['id']), parent=self.data.proposer_profile) if not self.data.proposal: raise NotFound('Requested proposal does not exist') self.data.proposal_org = self.data.proposal.org self.check.canAccessProposalEntity() self.mutator.commentVisible()
def getGSoC2012Profile(link_id): program = GSoCProgram.get_by_key_name('google/gsoc2012') return GSoCProfile.all().filter('scope', program).filter('link_id', link_id).get()
def _continueShipmentSync(self, request, *args, **kwargs): """Continue syncing shipment data. POST Args: program_key: the key of the program which sync is being done for. shipment_info_id: id of the shipment info object that task is running for. column_indexes: column indexes for specific columns in JSON format. sheet_rows: spreadsheets CSV chunk data in JSON format. """ timekeeper = Timekeeper(20000) params = dicts.merge(request.POST, request.GET) redirect = RedirectHelper(None, None) if 'program_key' not in params: logging.error("missing program_key in params: '%s'" % params) return responses.terminateTask() if 'shipment_info_id' not in params: logging.error("missing shipment_info_id in params: '%s'" % params) return responses.terminateTask() self.setProgram(params['program_key']) self.setShipmentInfo(int(params['shipment_info_id'])) if 'sheet_rows' not in params: logging.error("missing sheet_rows data in params: '%s'" % params) return responses.terminateTask() if 'column_indexes' not in params: logging.error("missing column_indexes data in params: '%s'" % params) return responses.terminateTask() column_indexes = simplejson.loads(params['column_indexes']) sheet_rows = simplejson.loads(params['sheet_rows']) try: for remain, row in timekeeper.iterate(sheet_rows): if len(row) < len(column_indexes): row.extend((len(column_indexes) - len(row)) * ['']) data = self.getRowData(row, column_indexes) link_id = data['link_id'] q = GSoCProfile.all().filter('scope', self.__program) q.filter('link_id', link_id) profile = q.get() if not profile: logging.error("Profile link_id '%s' for program '%s' is not found" % (link_id, self.__program.name)) continue #continue to next row if not profile.is_student: logging.error("Profile link_id '%s' is not a student" % link_id) continue tracking = data['tracking'] date_shipped = data['date_shipped'] notes = data['notes'] full_address = " ".join([ data['address_1'], data['address_2'], data['city'], data.get('state', ''), data.get('zip', ''), data.get('zippostal_code', ''), data.get('country', '') ]) self.updateShipmentDataForStudent( profile, tracking, date_shipped, notes, full_address) except DeadlineExceededError: if remain: remaining_rows = sheet_rows[(-1 * remain):] params = { 'program_key': params.get('program_key'), 'sheet_rows': simplejson.dumps(remaining_rows), 'column_indexes': params.get('column_indexes'), 'shipment_info_id': params.get('shipment_info_id'), } taskqueue.add( url=redirect.urlOf('shipment_sync_task_continue'), params=params) return responses.terminateTask() self.finishSync() return responses.terminateTask()
# check if the organization has already sent an invitation to the user query = db.Query(Request) query.filter('type', 'Invitation') query.filter('user', invited_user) query.filter('role', self.request_data.kwargs['role']) query.filter('group', self.request_data.organization) if query.get(): raise djangoforms.ValidationError( 'An invitation to this user has already been sent.') # check if the user that is invited does not have the role key_name = '/'.join([ self.request_data.program.key().name(), invited_user.link_id]) profile = GSoCProfile.get_by_key_name(key_name, parent=invited_user) if not profile: msg = ("The specified user has a User account (the link_id is valid), " "but they do not yet have a profile for this %s. " "You cannot invite them until they create a profile.") raise djangoforms.ValidationError(msg % self.request_data.program.name) if self.request_data.kwargs['role'] == 'org_admin': role_for = profile.org_admin_for else: role_for = profile.mentor_for for key in role_for: if key == self.request_data.organization.key(): raise djangoforms.ValidationError(
def testCreateProfile(self): from soc.modules.gsoc.models.profile import GSoCProfile from soc.modules.gsoc.models.profile import GSoCStudentInfo self.timeline.studentSignup() self.data.createUser() suffix = "%(program)s" % { 'program': self.gsoc.key().name(), } role_suffix = "%(role)s/%(suffix)s" % { 'role': 'student', 'suffix': suffix, } url = '/gsoc/profile/' + suffix role_url = '/gsoc/profile/' + role_suffix # we do not want to seed the data in the datastore, we just # want to get the properties generated for seeding. The post # test will actually do the entity creation, so we reuse the # seed_properties method from the seeder to get the most common # values for Profile and StudentInfo postdata = seeder_logic.seed_properties(GSoCProfile) props = seeder_logic.seed_properties(GSoCStudentInfo, properties={ 'tax_form': None, 'enrollment_form': None, }) props.pop('tax_form') props.pop('enrollment_form') postdata.update(props) postdata.update({ 'link_id': self.data.user.link_id, 'student_info': None, 'user': self.data.user, 'parent': self.data.user, 'scope': self.gsoc, 'status': 'active', 'email': self.data.user.account.email(), 'mentor_for': [], 'org_admin_for': [], 'is_org_admin': False, 'is_mentor': False, }) response = self.post(role_url, postdata) self.assertResponseRedirect(response, url + '?validated') # hacky profile = GSoCProfile.all().get() profile.delete() postdata.update({ 'email': 'somerandominvalid@emailid', }) response = self.post(role_url, postdata) # yes! this is the protocol for form posts. We get an OK response # with the response containing the form's GET request page whenever # the form has an error and could not be posted. This is the architecture # chosen in order to save the form error state's while rendering the # error fields. self.assertResponseOK(response) error_dict = response.context['error'] self.assertTrue('email' in error_dict)
def getListData(self): idx = lists.getListIndex(self.request) def starter(start_key, q): if not start_key: q.filter('org_admin_for IN', self.data.org_admin_for) return True split = start_key.split(':', 1) if len(split) != 2: return False cls, start_key = split if cls == 'org_admin': q.filter('org_admin_for IN', self.data.org_admin_for) elif cls == 'mentor': q.filter('mentor_for IN', self.data.org_admin_for) else: return False if not start_key: return True start_entity = db.get(start_key) if not start_entity: return False q.filter('__key__ >=', start_entity.key()) return True def ender(entity, is_last, start): if not start: if is_last: return 'mentor:' else: return 'org_admin:' + str(entity.key()) split = start.split(':', 1) if len(split) != 2: return False cls, _ = split if is_last: return 'done' return '%s:%s' % (cls, str(entity.key())) def skipper(entity, start): if start.startswith('mentor:'): return False return any(self.data.orgAdminFor(i) for i in entity.mentor_for) q = GSoCProfile.all() if idx == 9: fields = {'mentor_for': self.data.user} response_builder = lists.RawQueryContentResponseBuilder( self.request, self._list_config, q, starter, ender=ender, skipper=skipper, prefetch=['user']) return response_builder.build() else: return None
from soc.models.org_admin import OrgAdmin from soc.models.role import StudentInfo from soc.modules.gsoc.models.mentor import GSoCMentor from soc.modules.gsoc.models.organization import GSoCOrganization from soc.modules.gsoc.models.org_admin import GSoCOrgAdmin from soc.modules.gsoc.models.profile import GSoCProfile from soc.modules.gsoc.models.program import GSoCProgram from soc.modules.gsoc.models.student import GSoCStudent from soc.modules.gsoc.models.student_project import StudentProject from soc.modules.gsoc.models.student_proposal import StudentProposal ROLE_MODELS = [GSoCMentor, GSoCOrgAdmin, GSoCStudent] POPULATED_PROFILE_PROPS = set(GSoCProfile.properties()) - set(Linkable.properties()) POPULATED_STUDENT_PROPS = StudentInfo.properties() def getDjangoURLPatterns(): """Returns the URL patterns for the tasks in this module. """ patterns = [ (r"^tasks/role_conversion/update_references", "soc.tasks.updates.role_conversion.updateReferences"), ( r"^tasks/role_conversion/update_project_references", "soc.tasks.updates.role_conversion.updateStudentProjectReferences", ), (
# check if the organization has already sent an invitation to the user query = db.Query(Request) query.filter('type', 'Invitation') query.filter('user', invited_user) query.filter('role', self.request_data.kwargs['role']) query.filter('org', self.request_data.organization) if query.get(): raise djangoforms.ValidationError( 'An invitation to this user has already been sent.') # check if the user that is invited does not have the role key_name = '/'.join([ self.request_data.program.key().name(), invited_user.link_id]) profile = self.request_data.invite_profile = GSoCProfile.get_by_key_name( key_name, parent=invited_user) if not profile: msg = ('The specified user has a User account (the link_id is valid), ' 'but they do not yet have a profile for this %s. ' 'You cannot invite them until they create a profile.') raise djangoforms.ValidationError(msg % self.request_data.program.name) if profile.student_info: raise djangoforms.ValidationError('That user is a student') if self.request_data.kwargs['role'] == 'org_admin': role_for = profile.org_admin_for else: role_for = set(profile.org_admin_for + profile.mentor_for)
def seed(request, *args, **kwargs): """Seeds the datastore with some default values. """ site_properties = { 'key_name': 'site', 'link_id': 'site', } site = Site(**site_properties) site.put() _, current_user = ensureUser() seeder = UserSeeder() for i in range(15): seeder.seed(i) group_properties = { 'key_name': 'google', 'link_id': 'google', 'name': 'Google Inc.', 'short_name': 'Google', 'founder': current_user, 'home_page': 'http://www.google.com', 'email': '*****@*****.**', 'description': 'This is the profile for Google.', 'contact_street': 'Some Street', 'contact_city': 'Some City', 'contact_country': 'United States', 'contact_postalcode': '12345', 'phone': '1-555-BANANA', 'status': 'active', } google = Sponsor(**group_properties) google.put() role_properties = { 'key_name': 'google/test', 'link_id': 'test', 'scope': google, 'scope_path': 'google', 'user': current_user, 'given_name': 'Test', 'surname': 'Example', 'name_on_documents': 'Test Example', 'email': '*****@*****.**', 'res_street': 'Some Street', 'res_city': 'Some City', 'res_state': 'Some State', 'res_country': 'United States', 'res_postalcode': '12345', 'phone': '1-555-BANANA', 'birth_date': db.DateProperty.now(), 'agreed_to_tos': True, } current_user.host_for = [google.key()] current_user.put() google_host = Host(**role_properties) google_host.put() from datetime import datetime from datetime import timedelta before = datetime.now() - timedelta(365) after = datetime.now() + timedelta(365) timeline_properties = { 'key_name': 'google/gsoc2009', 'link_id': 'gsoc2009', 'scope_path': 'google', 'scope': google, 'program_start': before, 'program_end': after, 'accepted_organization_announced_deadline': after, 'student_signup_start': before, 'student_signup_end': after, } gsoc2009_timeline = GSoCTimeline(**timeline_properties) gsoc2009_timeline.put() program_properties = { 'key_name': 'google/gsoc2009', 'link_id': 'gsoc2009', 'scope_path': 'google', 'scope': google, 'name': 'Google Summer of Code 2009', 'short_name': 'GSoC 2009', 'group_label': 'GSOC', 'description': 'This is the program for GSoC 2009.', 'apps_tasks_limit': 42, 'slots': 42, 'timeline': gsoc2009_timeline, 'status': 'visible', } gsoc2009 = GSoCProgram(**program_properties) gsoc2009.put() site.active_program = gsoc2009 site.put() # TODO: Use real GCIProgram here timeline_properties = { 'key_name': 'google/gci2009', 'link_id': 'gci2009', 'scope_path': 'google', 'scope': google, } gci2009_timeline = GCITimeline(**timeline_properties) #gci2009_timeline.put() program_properties.update({ 'key_name': 'google/gci2009', 'link_id': 'gci2009', 'name': 'Google Code In Contest 2009', 'short_name': 'GCI 2009', 'group_label': 'GCI', 'description': 'This is the program for GCI 2009.', 'timeline': gci2009_timeline, }) gci2009 = GCIProgram(**program_properties) #gci2009.put() group_properties.update({ 'key_name': 'google/gci2009/melange', 'link_id': 'melange', 'name': 'Melange Development Team', 'short_name': 'Melange', 'scope_path': 'google/gci2009', 'scope': gci2009, 'home_page': 'http://code.google.com/p/soc', 'description': 'Melange, share the love!', 'license_name': 'Apache License', 'ideas': 'http://code.google.com/p/soc/issues', }) melange = GCIOrganization(**group_properties) #melange.put() # create a new ranker #ranker_root_logic.create(student_proposal.DEF_RANKER_NAME, melange, # student_proposal.DEF_SCORE, 100) group_properties.update({ 'scope_path': 'google/gsoc2009', 'scope': gsoc2009, }) role_properties.update({ 'key_name': 'google/gsoc2009/test', 'link_id': 'test', 'scope_path': 'google/gsoc2009', 'scope': gsoc2009, 'program': gsoc2009, 'parent': current_user, }) profile = GSoCProfile(**role_properties) role_properties.pop('parent') orgs = [] for i in range(15): group_properties.update({ 'key_name': 'google/gsoc2009/org_%d' % i, 'link_id': 'org_%d' % i, 'name': 'Organization %d' % i, 'short_name': 'Org %d' % i, 'description': 'Organization %d!' % i, }) entity = GSoCOrganization(**group_properties) orgs.append(entity) entity.put() # create a new ranker ranker_root_logic.create(student_proposal.DEF_RANKER_NAME, entity, student_proposal.DEF_SCORE, 100) # Admin for the first org if i == 0: profile.org_admin_for.append(entity.key()) profile.put() # Mentor and admin for the second org if i == 1: profile.org_admin_for.append(entity.key()) profile.mentor_for.append(entity.key()) profile.put() role_properties.update({ 'key_name': 'google/gci2009/melange/test', 'link_id': 'test', 'scope_path': 'google/gci2009/melange', 'scope': melange, 'program': gci2009, }) melange_admin = GCIOrgAdmin(**role_properties) #melange_admin.put() melange_mentor = GCIMentor(**role_properties) #melange_mentor.put() student_id = 'test' student_properties = { 'key_name': gsoc2009.key().name() + "/" + student_id, 'link_id': student_id, 'scope_path': gsoc2009.key().name(), 'scope': gsoc2009, 'program': gsoc2009, 'user': current_user, 'given_name': 'test', 'surname': 'test', 'birth_date': db.DateProperty.now(), 'email': '*****@*****.**', 'im_handle': 'test_im_handle', 'major': 'test major', 'name_on_documents': 'test', 'res_country': 'United States', 'res_city': 'city', 'res_street': 'test street', 'res_postalcode': '12345', 'publish_location': True, 'blog': 'http://www.blog.com/', 'home_page': 'http://www.homepage.com/', 'photo_url': 'http://www.photosite.com/thumbnail.png', 'ship_state': None, 'expected_graduation': 2009, 'school_country': 'United States', 'school_name': 'Test School', 'tshirt_size': 'XS', 'tshirt_style': 'male', 'degree': 'Undergraduate', 'phone': '1650253000', 'can_we_contact_you': True, 'program_knowledge': 'I heard about this program through a friend.' } melange_student = GSoCStudent(**student_properties) melange_student.put() student_id = 'test2' student_properties.update({ 'key_name': gsoc2009.key().name() + "/" + student_id, 'link_id': student_id, 'user': current_user }) melange_student2 = GSoCStudent(**student_properties) melange_student2.put() project_id = 'test_project' project_properties = { 'key_name': gsoc2009.key().name() + "/org_1/" + project_id, 'link_id': project_id, 'scope_path': gsoc2009.key().name() + "/org_1", 'scope': orgs[1].key(), 'title': 'test project', 'abstract': 'test abstract', 'status': 'accepted', 'student': melange_student, 'mentor': profile, 'program': gsoc2009 } melange_project = StudentProject(**project_properties) melange_project.put() project_id = 'test_project2' project_properties.update({ 'key_name': gsoc2009.key().name() + "/org_1/" + project_id, 'link_id': project_id, 'student': melange_student2, 'title': 'test project2' }) melange_project2 = StudentProject(**project_properties) melange_project2.put() document_properties = { 'key_name': 'site/site/home', 'link_id': 'home', 'scope_path': 'site', 'scope': site, 'prefix': 'site', 'author': current_user, 'title': 'Home Page', 'short_name': 'Home', 'content': 'This is the Home Page', 'modified_by': current_user, } home_document = Document(**document_properties) home_document.put() document_logic._onCreate(home_document) document_properties = { 'key_name': 'user/test/notes', 'link_id': 'notes', 'scope_path': 'test', 'scope': current_user, 'prefix': 'user', 'author': current_user, 'title': 'My Notes', 'short_name': 'Notes', 'content': 'These are my notes', 'modified_by': current_user, } notes_document = Document(**document_properties) notes_document.put() document_logic._onCreate(home_document) site.home = home_document site.put() # pylint: disable=E1101 memcache.flush_all() return http.HttpResponse('Done')
def seed(request, *args, **kwargs): """Seeds the datastore with some default values. """ site_properties = { 'key_name': 'site', 'link_id': 'site', } site = Site(**site_properties) site.put() account = accounts.getCurrentAccount() if not account: account = users.User(email='*****@*****.**') user_properties = { 'key_name': 'test', 'link_id': 'test', 'account': account, 'name': 'Test', } current_user = User(**user_properties) current_user.put() group_properties = { 'key_name': 'google', 'link_id': 'google', 'name': 'Google Inc.', 'short_name': 'Google', 'founder': current_user, 'home_page': 'http://www.google.com', 'email': '*****@*****.**', 'description': 'This is the profile for Google.', 'contact_street': 'Some Street', 'contact_city': 'Some City', 'contact_country': 'United States', 'contact_postalcode': '12345', 'phone': '1-555-BANANA', 'status': 'active', } google = Sponsor(**group_properties) google.put() role_properties = { 'key_name': 'google/test', 'link_id': 'test', 'public_name': 'test', 'scope': google, 'scope_path': 'google', 'user': current_user, 'given_name': 'Test', 'surname': 'Example', 'name_on_documents': 'Test Example', 'email': '*****@*****.**', 'res_street': 'Some Street', 'res_city': 'Some City', 'res_state': 'Some State', 'res_country': 'United States', 'res_postalcode': '12345', 'phone': '1-555-BANANA', 'birth_date': db.DateProperty.now(), 'agreed_to_tos': True, 'is_org_admin': True, 'is_mentor': True, } current_user.host_for = [google.key()] current_user.put() google_host = Host(**role_properties) google_host.put() from datetime import datetime from datetime import timedelta now = datetime.now() before = now - timedelta(365) after = now + timedelta(365) timeline_properties = { 'key_name': 'google/gsoc2009', 'link_id': 'gsoc2009', 'scope_path': 'google', 'scope': google, 'program_start': before, 'program_end': after, 'accepted_organization_announced_deadline': before, 'student_signup_start': before, 'student_signup_end': after, } gsoc2009_timeline = GSoCTimeline(**timeline_properties) gsoc2009_timeline.put() program_properties = { 'key_name': 'google/gsoc2009', 'link_id': 'gsoc2009', 'scope_path': 'google', 'scope': google, 'name': 'Google Summer of Code 2009', 'short_name': 'GSoC 2009', 'group_label': 'GSOC', 'description': 'This is the program for GSoC 2009.', 'apps_tasks_limit': 42, 'slots': 42, 'timeline': gsoc2009_timeline, 'status': 'visible', } gsoc2009 = GSoCProgram(**program_properties) gsoc2009.put() timeline_properties.update({ 'key_name': 'google/gsoc2010', 'link_id': 'gsoc2010', }) gsoc2010_timeline = GSoCTimeline(**timeline_properties) gsoc2010_timeline.put() program_properties.update({ 'key_name': 'google/gsoc2010', 'link_id': 'gsoc2010', 'name': 'Google Summer of Code 2010', 'description': 'This is the program for GSoC 2010.', 'short_name': 'GSoC 2010', 'timeline': gsoc2010_timeline, }) gsoc2010 = GSoCProgram(**program_properties) gsoc2010.put() timeline_properties = { 'key_name': 'google/gci2009', 'link_id': 'gci2009', 'scope_path': 'google', 'scope': google, 'program_start': before, 'program_end': after, 'accepted_organization_announced_deadline': before, 'student_signup_start': before, 'student_signup_end': after, 'tasks_publicly_visible': before, 'task_claim_deadline': after, 'stop_all_work_deadline': after, } gci2009_timeline = GCITimeline(**timeline_properties) gci2009_timeline.put() program_properties.update({ 'key_name': 'google/gci2009', 'link_id': 'gci2009', 'name': 'Google Code In Contest 2009', 'short_name': 'GCI 2009', 'group_label': 'GCI', 'description': 'This is the program for GCI 2009.', 'timeline': gci2009_timeline, }) gci2009 = GCIProgram(**program_properties) gci2009.put() site.active_program = gci2009 site.put() group_properties.update({ 'key_name': 'google/gci2009/melange', 'link_id': 'melange', 'name': 'Melange Development Team', 'short_name': 'Melange', 'scope_path': 'google/gci2009', 'scope': gci2009, 'home_page': 'http://code.google.com/p/soc', 'description': 'Melange, share the love!', 'license_name': 'Apache License', 'ideas': 'http://code.google.com/p/soc/issues', }) melange = GCIOrganization(**group_properties) melange.put() group_properties.update({ 'scope_path': 'google/gsoc2009', 'scope': gsoc2009, }) role_properties.update({ 'key_name': 'google/gsoc2009/test', 'link_id': 'test', 'scope_path': 'google/gsoc2009', 'scope': gsoc2009, 'program': gsoc2009, 'parent': current_user, }) profile = GSoCProfile(**role_properties) role_properties.pop('parent') orgs = [] for i in range(15): group_properties.update({ 'key_name': 'google/gsoc2009/org_%d' % i, 'link_id': 'org_%d' % i, 'name': 'Organization %d' % i, 'short_name': 'Org %d' % i, 'description': 'Organization %d!' % i, }) entity = GSoCOrganization(**group_properties) orgs.append(entity) entity.put() # Admin (and thus mentor) for the first org if i == 0: profile.org_admin_for.append(entity.key()) profile.mentor_for.append(entity.key()) profile.is_mentor = True profile.is_org_admin = True profile.put() # Mentor for the second org if i == 1: profile.mentor_for.append(entity.key()) profile.is_mentor = True profile.put() role_properties.update({ 'key_name': 'google/gci2009/test', 'link_id': 'test', 'scope_path': 'google/gci2009', 'scope': gci2009, 'program': gci2009, 'org_admin_for': [melange.key()], 'mentor_for': [melange.key()], 'parent': current_user, }) melange_admin = GCIProfile(**role_properties) # TODO: add GCI orgs melange_admin.put() task_properties = { 'status': 'Open', 'modified_by': melange_admin.key(), 'subscribers': [melange_admin.key()], 'title': 'Awesomeness', 'created_by': melange_admin.key(), 'created_on': now, 'program': gci2009, 'time_to_complete': 1337, 'modified_on': now, 'org': melange.key(), 'description': '<p>AWESOME</p>', 'difficulty_level': DifficultyLevel.MEDIUM, 'types': ['Code'] } gci_task = GCITask(**task_properties) gci_task.put() user_properties = { 'key_name': 'student', 'link_id': 'student', 'account': users.User(email='*****@*****.**'), 'name': 'Student', } student_user = User(**user_properties) student_user.put() student_id = 'student' student_properties = { 'key_name': gsoc2009.key().name() + "/" + student_id, 'link_id': student_id, 'scope_path': gsoc2009.key().name(), 'parent': student_user, 'scope': gsoc2009, 'program': gsoc2009, 'user': student_user, 'is_student': True, 'public_name': 'Student', 'given_name': 'Student', 'surname': 'Student', 'birth_date': db.DateProperty.now(), 'email': '*****@*****.**', 'im_handle': 'student_im_handle', 'major': 'test major', 'name_on_documents': 'Student', 'res_country': 'United States', 'res_city': 'city', 'res_street': 'test street', 'res_postalcode': '12345', 'publish_location': True, 'blog': 'http://www.blog.com/', 'home_page': 'http://www.homepage.com/', 'photo_url': 'http://www.photosite.com/thumbnail.png', 'ship_state': None, 'tshirt_size': 'XS', 'tshirt_style': 'male', 'degree': 'Undergraduate', 'phone': '1650253000', 'can_we_contact_you': True, 'program_knowledge': 'I heard about this program through a friend.' } melange_student = GSoCProfile(**student_properties) student_info_properties = { 'key_name': melange_student.key().name(), 'parent': melange_student, 'expected_graduation': 2009, 'program': gsoc2009, 'school_country': 'United States', 'school_name': 'Test School', 'school_home_page': 'http://www.example.com', 'program': gsoc2009, } student_info = GSoCStudentInfo(**student_info_properties) student_info.put() melange_student.student_info = student_info melange_student.put() user_properties = { 'key_name': 'student2', 'link_id': 'student2', 'account': users.User(email='*****@*****.**'), 'name': 'Student 2', } student_user2 = User(**user_properties) student_user2.put() student_id = 'student2' student_properties.update({ 'key_name': gsoc2009.key().name() + "/" + student_id, 'link_id': student_id, 'user': student_user2, 'parent': student_user2, }) melange_student2 = GSoCProfile(**student_properties) melange_student2.put() project_id = 'test_project' project_properties = { 'key_name': gsoc2009.key().name() + "/org_1/" + project_id, 'link_id': project_id, 'scope_path': gsoc2009.key().name() + "/org_1", 'scope': orgs[1].key(), 'title': 'test project', 'abstract': 'test abstract', 'status': 'accepted', 'student': melange_student, 'mentor': profile, 'program': gsoc2009 } melange_project = StudentProject(**project_properties) melange_project.put() student_info_properties.update({'number_of_projects': 1, 'project_for_orgs': [orgs[1].key()]}) student_info = GSoCStudentInfo(**student_info_properties) student_info.put() melange_student.student_info = student_info melange_student.put() project_id = 'test_project2' project_properties.update({ 'key_name': gsoc2009.key().name() + "/org_1/" + project_id, 'link_id': project_id, 'student': melange_student2, 'title': 'test project2' }) student_info_properties.update({ 'key_name': gsoc2009.key().name() + "/" + student_id, 'link_id': student_id, 'parent': melange_student2, }) student_info2 = GSoCStudentInfo(**student_info_properties) student_info2.put() melange_student2.student_info = student_info2 melange_student2.put() melange_project2 = StudentProject(**project_properties) melange_project2.put() student_id = 'student' student_properties.update({ 'key_name': gci2009.key().name() + '/' + student_id, 'parent': student_user, 'scope': gci2009, 'scope_path': gci2009.key().name(), }) gci_student = GCIProfile(**student_properties) gci_student.put() student_info_properties.update({ 'key_name': gci_student.key().name(), 'parent': gci_student, 'program': gci2009, }) student_info = GCIStudentInfo(**student_info_properties) student_info.put() gci_student.student_info = student_info gci_student.put() score_properties = { 'parent': gci_student, 'program': gci2009, 'points': 5, 'tasks': [gci_task.key()] } score = GCIScore(**score_properties) score.put() document_properties = { 'key_name': 'site/site/home', 'link_id': 'home', 'scope_path': 'site', 'scope': site, 'prefix': 'site', 'author': current_user, 'title': 'Home Page', 'short_name': 'Home', 'content': 'This is the Home Page', 'modified_by': current_user, } home_document = Document(**document_properties) home_document.put() document_properties = { 'key_name': 'user/test/notes', 'link_id': 'notes', 'scope_path': 'test', 'scope': current_user, 'prefix': 'user', 'author': current_user, 'title': 'My Notes', 'short_name': 'Notes', 'content': 'These are my notes', 'modified_by': current_user, } notes_document = Document(**document_properties) notes_document.put() site.home = home_document site.put() # pylint: disable=E1101 memcache.flush_all() return http.HttpResponse('Done')
from soc.models.mentor import Mentor from soc.models.org_admin import OrgAdmin from soc.models.role import StudentInfo from soc.modules.gsoc.models.mentor import GSoCMentor from soc.modules.gsoc.models.organization import GSoCOrganization from soc.modules.gsoc.models.org_admin import GSoCOrgAdmin from soc.modules.gsoc.models.profile import GSoCProfile from soc.modules.gsoc.models.program import GSoCProgram from soc.modules.gsoc.models.student import GSoCStudent from soc.modules.gsoc.models.student_project import StudentProject from soc.modules.gsoc.models.student_proposal import StudentProposal ROLE_MODELS = [GSoCMentor, GSoCOrgAdmin, GSoCStudent] POPULATED_PROFILE_PROPS = set(GSoCProfile.properties()) - set( Linkable.properties()) POPULATED_STUDENT_PROPS = StudentInfo.properties() def getDjangoURLPatterns(): """Returns the URL patterns for the tasks in this module. """ patterns = [ (r'^tasks/role_conversion/update_references', 'soc.tasks.updates.role_conversion.updateReferences'), (r'^tasks/role_conversion/update_project_references', 'soc.tasks.updates.role_conversion.updateStudentProjectReferences'), (r'^tasks/role_conversion/update_proposal_references',
def sendSurveyReminderForProject(self, request, *args, **kwargs): """Sends a reminder mail for a given StudentProject and Survey. A reminder is only send if no record is on file for the given Survey and StudentProject. Expects the following to be present in the POST dict: survey_key: specifies the key name for the ProjectSurvey to send reminders for survey_type: either project or grading depending on the type of Survey project_key: encoded Key which specifies the project to send a reminder for Args: request: Django Request object """ post_dict = request.POST project_key = post_dict.get('project_key') survey_key = post_dict.get('survey_key') survey_type = post_dict.get('survey_type') if not (project_key and survey_key and survey_type): # invalid task data, log and return OK return error_handler.logErrorAndReturnOK( 'Invalid sendSurveyReminderForProject data: %s' % post_dict) # set model depending on survey type specified in POST if survey_type == 'project': survey_model = ProjectSurvey record_model = GSoCProjectSurveyRecord elif survey_type == 'grading': survey_model = GradingProjectSurvey record_model = GSoCGradingProjectSurveyRecord else: return error_handler.logErrorAndReturnOK( '%s is an invalid survey_type' %survey_type) # retrieve the project and survey project_key = db.Key(project_key) project = GSoCProject.get(project_key) if not project: # no existing project found, log and return OK return error_handler.logErrorAndReturnOK( 'Invalid project specified %s:' % project_key) survey = survey_model.get_by_key_name(survey_key) if not survey: # no existing survey found, log and return OK return error_handler.logErrorAndReturnOK( 'Invalid survey specified %s:' % survey_key) # try to retrieve an existing record q = record_model.all() q.filter('project', project) q.filter('survey', survey) record = q.get() if not record: # send reminder email because we found no record student_profile = project.parent() site_entity = site.singleton() if survey_type == 'project': url_name = 'gsoc_take_student_evaluation' to_name = student_profile.name() to_address = student_profile.email mail_template = 'v2/modules/gsoc/reminder/student_eval_reminder.html' elif survey_type == 'grading': url_name = 'gsoc_take_mentor_evaluation' mentors = db.get(project.mentors) to_address = [m.email for m in mentors] to_name = 'mentor(s) for project "%s"' %(project.title) mail_template = \ 'v2/modules/gsoc/reminder/mentor_eval_reminder.html' program = project.program hostname = system.getHostname() url_kwargs = { 'sponsor': program.scope.link_id, 'program': program.link_id, 'survey': survey.link_id, 'user': student_profile.link_id, 'id': str(project.key().id()), } url = reverse(url_name, kwargs=url_kwargs) survey_url = '%s://%s%s' % ('http', hostname, url) # set the context for the mail template mail_context = { 'student_name': student_profile.name(), 'project_title': project.title, 'survey_url': survey_url, 'survey_end': survey.survey_end, 'to_name': to_name, 'site_name': site_entity.site_name, 'sender_name': "The %s Team" % site_entity.site_name, } # set the sender (_, sender_address) = mail_dispatcher.getDefaultMailSender() mail_context['sender'] = sender_address # set the receiver and subject mail_context['to'] = to_address mail_context['subject'] = \ 'Evaluation Survey "%s" Reminder' %(survey.title) # find all org admins for the project's organization org = project.org q = GSoCProfile.all() q.filter('status', 'active') q.filter('org_admin_for', org) org_admins = q.fetch(1000) # collect email addresses for all found org admins org_admin_addresses = [] for org_admin in org_admins: org_admin_addresses.append(org_admin.email) if org_admin_addresses: mail_context['cc'] = org_admin_addresses # send out the email mail_dispatcher.sendMailFromTemplate(mail_template, mail_context) # return OK return http.HttpResponse()
def sendMailAboutGradingRecordResult(self, request, *args, **kwargs): """Sends out a mail about the result of one GradingRecord. Expects the following to be present in the POST dict: record_key: Specifies the key for the record to process. Args: request: Django Request object """ post_dict = request.POST record_key = post_dict.get('record_key') if not record_key: # no GradingRecord key specified, log and return OK error_handler.logErrorAndReturnOK( 'No valid record_key specified in POST data: %s' % request.POST) record = GSoCGradingRecord.get(db.Key(record_key)) if not record: # no valid GradingRecord key specified, log and return OK error_handler.logErrorAndReturnOK( 'No valid GradingRecord key specified: %s' % record_key) survey_group_entity = record.grading_survey_group project_entity = record.parent() student_entity = project_entity.parent() org_entity = project_entity.org site_entity = site.singleton() mail_context = { 'survey_group': survey_group_entity, 'grading_record': record, 'project': project_entity, 'organization': org_entity, 'site_name': site_entity.site_name, 'to_name': student_entity.name() } # set the sender (_, sender_address) = mail_dispatcher.getDefaultMailSender() mail_context['sender'] = sender_address # set the receiver and subject mail_context['to'] = student_entity.email mail_context['cc'] = [] mail_context['subject'] = '%s results processed for %s' %( survey_group_entity.name, project_entity.title) q = GSoCProfile.all() q.filter('org_admin_for', org_entity) org_admins = q.fetch(1000) # collect all mentors mentors = db.get(project_entity.mentors) # add them all to the cc list for org_member in org_admins + mentors: mail_context['cc'].append(org_member.email) # send out the email using a template mail_template = 'modules/gsoc/grading_record/mail/result.html' mail_dispatcher.sendMailFromTemplate(mail_template, mail_context) # return OK return http.HttpResponse()
def getGSoC2011Profile(link_id): program = GSoCProgram.get_by_key_name('google/gsoc2011') return GSoCProfile.all().filter('scope', program).filter('link_id', link_id).get()
def populate(self, redirect, request, args, kwargs): """Populates the fields in the RequestData object. Args: request: Django HTTPRequest object. args & kwargs: The args and kwargs django sends along. """ super(RequestData, self).populate(redirect, request, args, kwargs) if kwargs.get('sponsor') and kwargs.get('program'): program_key_name = "%s/%s" % (kwargs['sponsor'], kwargs['program']) program_key = db.Key.from_path('GSoCProgram', program_key_name) else: from soc.models.site import Site program_key = Site.active_program.get_value_for_datastore(self.site) program_key_name = program_key.name() import logging logging.error("No program specified") timeline_key = db.Key.from_path('GSoCTimeline', program_key_name) org_app_key_name = 'gsoc_program/%s/orgapp' % program_key_name org_app_key = db.Key.from_path('OrgAppSurvey', org_app_key_name) keys = [program_key, timeline_key, org_app_key] self.program, self.program_timeline, self.org_app = db.get(keys) if not self.program: raise NotFound("There is no program for url '%s'" % program_key_name) self.timeline = TimelineHelper(self.program_timeline, self.org_app) if kwargs.get('organization'): fields = [self.program.key().id_or_name(), kwargs.get('organization')] org_key_name = '/'.join(fields) self.organization = GSoCOrganization.get_by_key_name(org_key_name) if not self.organization: raise NotFound("There is no organization for url '%s'" % org_key_name) if self.user: key_name = '%s/%s' % (self.program.key().name(), self.user.link_id) self.profile = GSoCProfile.get_by_key_name( key_name, parent=self.user) from soc.modules.gsoc.models.program import GSoCProgram host_key = GSoCProgram.scope.get_value_for_datastore(self.program) self.is_host = host_key in self.user.host_for if self.profile: org_keys = set(self.profile.mentor_for + self.profile.org_admin_for) prop = GSoCProfile.student_info student_info_key = prop.get_value_for_datastore(self.profile) if student_info_key: self.student_info = db.get(student_info_key) self.is_student = True else: orgs = db.get(org_keys) org_map = self.org_map = dict((i.key(), i) for i in orgs) self.mentor_for = org_map.values() self.org_admin_for = [org_map[i] for i in self.profile.org_admin_for] self.is_org_admin = self.is_host or bool(self.org_admin_for) self.is_mentor = self.is_org_admin or bool(self.mentor_for)