def testFilterNoKeysToFilter(self): """Tests that nothing is filtered if no keys are given. """ keys_to_filter = [] expected_dict = {} self.assertEqual(dicts.filter(self.dummy_dict, keys_to_filter), expected_dict)
def context(self, data, check, mutator): """Handler for default HTTP GET request.""" context = {'page_name': 'Student form upload'} form_data = {} if data.ndb_profile.student_data.consent_form: form_data['consent_form'] = blobstore.BlobInfo( data.ndb_profile.student_data.consent_form) if data.ndb_profile.student_data.enrollment_form: form_data['enrollment_form'] = blobstore.BlobInfo( data.ndb_profile.student_data.enrollment_form) upload_form = UploadForm(data, initial=form_data) if profile_logic.hasStudentFormsUploaded(data.ndb_profile): kwargs = dicts.filter(data.kwargs, ['sponsor', 'program']) claim_tasks_url = reverse('gci_list_tasks', kwargs=kwargs) context['form_instructions'] = CLAIM_TASKS_NOW % claim_tasks_url # TODO(ljvderijk): This can be removed when AppEngine supports 200 response # in the BlobStore API. if data.GET: for key, error in data.GET.iteritems(): if not key.startswith('error_'): continue field_name = key.split('error_', 1)[1] upload_form.errors[field_name] = upload_form.error_class( [error]) context['form'] = upload_form context['form_verification_awaiting'] = ( ci_profile_logic.isFormVerificationAwaiting(data.ndb_profile)) return context
def testFilterKeysToFilterNotInDict(self): """Tests that nothing is filtered if keys are not in dict. """ keys_to_filter = ['foo8'] expected_dict = {} self.assertEqual(dicts.filter(self.dummy_dict, keys_to_filter), expected_dict)
def testFilterKeysToFilterValid(self): """Tests if a dict is filtered correctly if some keys are given. """ keys_to_filter = ['a', 'b', 'c', 'd'] expected_dict = {'a': '1', 'b': '2', 'c': '3', 'd': '1'} self.assertEqual( dicts.filter(self.dummy_dict, keys_to_filter), expected_dict)
def testFilterNoKeysToFilter(self): """Tests that nothing is filtered if no keys are given. """ keys_to_filter = [] expected_dict = {} self.assertEqual( dicts.filter(self.dummy_dict, keys_to_filter), expected_dict)
def _checkIsActive(self, django_args, logic, fields): """Raises an alternate HTTP response if the entity is not active. Args: django_args: a dictionary with django's arguments logic: the logic that should be used to look up the entity fields: the name of the fields that should be copied verbatim from the django_args as filter Raises: AccessViolationResponse: * if no entity is found * if the entity status is not active """ self.checkIsUser() fields = dicts.filter(django_args, fields) fields['status'] = 'active' entity = logic.getForFields(fields, unique=True) if entity: return raise out_of_band.AccessViolation(message_fmt=DEF_NO_ACTIVE_ENTITY_MSG)
def testFilterKeysToFilterNotInDict(self): """Tests that nothing is filtered if keys are not in dict. """ keys_to_filter = ['foo8'] expected_dict = {} self.assertEqual( dicts.filter(self.dummy_dict, keys_to_filter), expected_dict)
def testFilterKeysToFilterValid(self): """Tests if a dict is filtered correctly if some keys are given. """ keys_to_filter = ['a', 'b', 'c', 'd'] expected_dict = {'a': '1', 'b': '2', 'c': '3', 'd': '1'} self.assertEqual(dicts.filter(self.dummy_dict, keys_to_filter), expected_dict)
def context(self, data, check, mutator): """Handler for default HTTP GET request.""" context = {'page_name': 'Student form upload'} form_data = {} if data.ndb_profile.student_data.consent_form: form_data['consent_form'] = blobstore.BlobInfo( data.ndb_profile.student_data.consent_form) if data.ndb_profile.student_data.enrollment_form: form_data['enrollment_form'] = blobstore.BlobInfo( data.ndb_profile.student_data.enrollment_form) upload_form = UploadForm(data, initial=form_data) if profile_logic.hasStudentFormsUploaded(data.ndb_profile): kwargs = dicts.filter(data.kwargs, ['sponsor', 'program']) claim_tasks_url = reverse('gci_list_tasks', kwargs=kwargs) context['form_instructions'] = CLAIM_TASKS_NOW % claim_tasks_url # TODO(ljvderijk): This can be removed when AppEngine supports 200 response # in the BlobStore API. if data.GET: for key, error in data.GET.iteritems(): if not key.startswith('error_'): continue field_name = key.split('error_', 1)[1] upload_form.errors[field_name] = upload_form.error_class([error]) context['form'] = upload_form context['form_verification_awaiting'] = ( ci_profile_logic.isFormVerificationAwaiting(data.ndb_profile)) return context
def __init__(self, *args, **kwargs): """ """ super(TinyMCE, self).__init__(*args, **kwargs) keys = ['mode', 'theme', 'theme_advanced_toolbar_location', 'theme_advanced_toolbar_align', 'relative_urls', 'remove_script_host'] self.mce_settings = dicts.filter(self.mce_settings, keys)
def context(self): organization = self.data.organization context = { 'request_data': self.data, 'current_timeline': self.current_timeline, 'organization': organization, } context['apply_block'] = True if not self.data.profile: kwargs = dicts.filter(self.data.kwargs, ['sponsor', 'program']) suffix = '?org=' + self.data.organization.link_id if self.data.timeline.studentSignup(): kwargs['role'] = 'student' context['student_profile_link'] = reverse('create_gsoc_profile', kwargs=kwargs) + suffix kwargs['role'] = 'mentor' context['mentor_profile_link'] = reverse('create_gsoc_profile', kwargs=kwargs) + suffix else: kwargs_org = dicts.filter(self.data.kwargs, ['sponsor', 'program', 'organization']) if self.data.student_info: context['submit_proposal_link'] = reverse('submit_gsoc_proposal', kwargs=kwargs_org) elif self.data.orgAdminFor(organization): context['mentor_applied'] = True context['role'] = 'an administrator' elif self.data.mentorFor(organization): context['mentor_applied'] = True context['role'] = 'a mentor' elif not self.data.mentorFor(organization): if self.data.appliedTo(organization): context['mentor_applied'] = True else: context['mentor_request_link'] = reverse('gsoc_request', kwargs=kwargs_org) else: context['apply_block'] = False return context
def context(self): context = {} accepted_orgs = None if self.data.timeline.orgsAnnounced(): r = self.data.redirect.program() accepted_orgs = r.urlOf('gsoc_accepted_orgs') context['accepted_orgs_link'] = accepted_orgs context['apache_home_link'] = r.orgHomepage('asf').url() context['mozilla_home_link'] = r.orgHomepage('mozilla').url() context['melange_home_link'] = r.orgHomepage('melange').url() context['wikimedia_home_link'] = r.orgHomepage('wikimedia').url() context['drupal_home_link'] = r.orgHomepage('drupal').url() context['org_signup'] = self.data.timeline.orgSignup() context['student_signup'] = self.data.timeline.studentSignup() context['mentor_signup'] = self.data.timeline.mentorSignup() signup = self.data.timeline.orgSignup( ) or self.data.timeline.studentSignup( ) or self.data.timeline.mentorSignup() if signup and not self.data.gae_user: context['login_link'] = users.create_login_url(self.data.full_path) if signup and not self.data.profile: kwargs = dicts.filter(self.data.kwargs, ['sponsor', 'program']) if self.data.timeline.orgSignup(): kwargs['role'] = 'org_admin' elif self.data.timeline.studentSignup(): kwargs['role'] = 'mentor' context['mentor_profile_link'] = reverse('create_gsoc_profile', kwargs=kwargs) kwargs['role'] = 'student' elif self.data.timeline.mentorSignup(): kwargs['role'] = 'mentor' context['profile_link'] = reverse('create_gsoc_profile', kwargs=kwargs) if ((self.data.timeline.studentSignup() or self.data.timeline.mentorSignup()) and self.data.profile): context['apply_link'] = accepted_orgs if self.data.profile: if self.data.student_info: context['profile_role'] = 'student' else: context['profile_role'] = 'mentor' context['apply_block'] = signup return context
def checkAccess(self): self.check.isLoggedIn() self.check.isProgramActive() if 'role' in self.data.kwargs: role = self.data.kwargs['role'] kwargs = dicts.filter(self.data.kwargs, ['sponsor', 'program']) edit_url = reverse('edit_gsoc_profile', kwargs=kwargs) if role == 'student': self.check.canApplyStudent(edit_url) else: self.check.canApplyNonStudent(role, edit_url) else: self.check.isProfileActive()
def checkAccess(self): self.check.isLoggedIn() self.check.isProgramActive() if "role" in self.data.kwargs: role = self.data.kwargs["role"] kwargs = dicts.filter(self.data.kwargs, ["sponsor", "program"]) edit_url = reverse("edit_gsoc_profile", kwargs=kwargs) if role == "student": self.check.canApplyStudent(edit_url) else: self.check.canApplyNonStudent(role, edit_url) else: self.check.isProfileActive()
def __init__(self, *args, **kwargs): """ """ super(TinyMCE, self).__init__(*args, **kwargs) keys = [ "mode", "theme", "theme_advanced_toolbar_location", "theme_advanced_toolbar_align", "relative_urls", "remove_script_host", ] self.mce_settings = dicts.filter(self.mce_settings, keys)
def context(self): context = {} accepted_orgs = None if self.data.timeline.orgsAnnounced(): r = self.data.redirect.program() accepted_orgs = r.urlOf('gsoc_accepted_orgs') context['accepted_orgs_link'] = accepted_orgs context['apache_home_link'] = r.orgHomepage('asf').url() context['mozilla_home_link'] = r.orgHomepage('mozilla').url() context['melange_home_link'] = r.orgHomepage('melange').url() context['wikimedia_home_link'] = r.orgHomepage('wikimedia').url() context['drupal_home_link'] = r.orgHomepage('drupal').url() context['org_signup'] = self.data.timeline.orgSignup() context['student_signup'] = self.data.timeline.studentSignup() context['mentor_signup'] = self.data.timeline.mentorSignup() signup = self.data.timeline.orgSignup( ) or self.data.timeline.studentSignup( ) or self.data.timeline.mentorSignup() if signup and not self.data.gae_user: context['login_link'] = users.create_login_url(self.data.full_path) if signup and not self.data.profile: kwargs = dicts.filter(self.data.kwargs, ['sponsor', 'program']) if self.data.timeline.orgSignup(): kwargs['role'] = 'org_admin' elif self.data.timeline.studentSignup(): kwargs['role'] = 'mentor' context['mentor_profile_link'] = reverse( 'create_gsoc_profile', kwargs=kwargs) kwargs['role'] = 'student' elif self.data.timeline.mentorSignup(): kwargs['role'] = 'mentor' context['profile_link'] = reverse('create_gsoc_profile', kwargs=kwargs) if ((self.data.timeline.studentSignup() or self.data.timeline.mentorSignup()) and self.data.profile): context['apply_link'] = accepted_orgs if self.data.profile: if self.data.student_info: context['profile_role'] = 'student' else: context['profile_role'] = 'mentor' context['apply_block'] = signup return context
def checkAccess(self, data, check, mutator): check.isProgramVisible() check.isProgramRunning() if 'role' in data.kwargs: role = data.kwargs['role'] kwargs = dicts.filter(data.kwargs, ['sponsor', 'program']) edit_url = reverse('edit_gci_profile', kwargs=kwargs) if role == 'student': check.canApplyStudent(edit_url) else: check.isLoggedIn() check.canApplyNonStudent(role, edit_url) else: check.isProfileActive()
def checkAccess(self): self.check.isLoggedIn() self.check.isProgramVisible() if 'role' in self.data.kwargs: role = self.data.kwargs['role'] kwargs = dicts.filter(self.data.kwargs, ['sponsor', 'program']) edit_url = reverse('edit_gsoc_profile', kwargs=kwargs) if role == 'student': self.check.canApplyStudent(edit_url) else: self.check.canApplyNonStudent(role, edit_url) else: self.check.isProfileActive() self.check.isProgramRunning()
def _bulkReview(self, request, params, from_status, to_status, program_keyname): """Returns a HTTP Response containing JSON information needed to bulk-review organization applications. Args: request: Standard Django HTTP Request object params: Params for this view from_status: The status for the applications which should be reviewed (can be a list) to_status: The status to which all applications should be changed to program_keyname: The keyname for the program to which the application belongs """ # get the program entity from the keyname program_entity = program_logic.logic.getFromKeyName(program_keyname) # get all the organization applications for the # given program and from_status filter = {'scope': program_entity, 'status': from_status} org_app_entities = params['logic'].getForFields(filter=filter) # convert each application into a dictionary containing only the fields # given by the dict_filter dict_filter = ['link_id', 'name'] org_apps = [ dicts.filter(i.toDict(), dict_filter) for i in org_app_entities ] to_json = { 'program': program_entity.name, 'nr_applications': len(org_apps), 'application_type': params['name_plural'], 'applications': org_apps, 'link': '/%s/review/%s/(link_id)?status=%s' % (params['url_name'], program_entity.key().id_or_name(), to_status), } return self.json(request, to_json)
def _bulkReview(self, request, params, from_status, to_status, program_keyname): """Returns a HTTP Response containing JSON information needed to bulk-review organization applications. Args: request: Standard Django HTTP Request object params: Params for this view from_status: The status for the applications which should be reviewed (can be a list) to_status: The status to which all applications should be changed to program_keyname: The keyname for the program to which the application belongs """ # get the program entity from the keyname program_entity = program_logic.logic.getFromKeyName(program_keyname) # get all the organization applications for the # given program and from_status filter = {'scope': program_entity, 'status': from_status} org_app_entities = params['logic'].getForFields(filter=filter) # convert each application into a dictionary containing only the fields # given by the dict_filter dict_filter = ['link_id', 'name'] org_apps = [dicts.filter(i.toDict(), dict_filter) for i in org_app_entities] to_json = { 'program' : program_entity.name, 'nr_applications' : len(org_apps), 'application_type' : params['name_plural'], 'applications': org_apps, 'link' : '/%s/review/%s/(link_id)?status=%s' %( params['url_name'] ,program_entity.key().id_or_name(), to_status), } json = simplejson.dumps(to_json) # use the standard JSON template to return our response context = {'json': json} template = 'soc/json.html' return responses.respond(request, template, context)
def context(self, data, check, mutator): context = super(GCIProfilePage, self).context(data, check, mutator) if self.isCreateProfileRequest(data): if self.isStudentRequest(data): context['form_instructions'] = PARENTAL_CONSENT_ADVICE else: if data.is_student and \ not profile_logic.hasStudentFormsUploaded(data.student_info): kwargs = dicts.filter(data.kwargs, ['sponsor', 'program']) upload_forms_url = reverse( url_names.GCI_STUDENT_FORM_UPLOAD, kwargs=kwargs) context['form_instructions'] = UPLOAD_FORMS_REMINDER % upload_forms_url context['edit_profile'] = True return context
def context(self, data, check, mutator): context = super(GCIProfilePage, self).context(data, check, mutator) if self.isCreateProfileRequest(data): if self.isStudentRequest(data): context['form_instructions'] = PARENTAL_CONSENT_ADVICE else: if data.is_student and \ not profile_logic.hasStudentFormsUploaded(data.student_info): kwargs = dicts.filter(data.kwargs, ['sponsor', 'program']) upload_forms_url = reverse(url_names.GCI_STUDENT_FORM_UPLOAD, kwargs=kwargs) context[ 'form_instructions'] = UPLOAD_FORMS_REMINDER % upload_forms_url context['edit_profile'] = True return context
def getSendMailFromTemplateNameTxn(template_name, context, parent=None, transactional=True): """Returns a method that is safe to be run in a transaction to sent out an email using a Django template_name. See sendMailFromTemplate() for more information. Args: parent: The parent entity to use for the transaction. context: The context passed on to sendMail. parent: An optional parent entity of the to be created mail entity. transactional: Whether the task should be created transactionally. """ # render the template and put in context with 'html' as key context['html'] = loader.render_to_string(template_name, dictionary=context) # filter out the unneeded values in context to keep sendMail happy return sendMail(dicts.filter(context, mail.EmailMessage.PROPERTIES), parent=parent, run=False, transactional=transactional)
def getSendMailFromTemplateTxn(template, context, parent=None, transactional=True): """Returns a method that is safe to be run in a transaction to sent out an email using a Django Template instance. See sendMailFromTemplate() for more information. Args: parent: The parent entity to use for the transaction. context: The context passed on to sendMail. parent: An optional parent entity of the to be created mail entity. transactional: Whether the task should be created transactionally. """ context_instance = Context(context) context['html'] = template.render(context_instance) # filter out the unneeded values in context to keep sendMail happy return sendMail(dicts.filter(context, mail.EmailMessage.PROPERTIES), parent=parent, run=False, transactional=transactional)
def canApplyStudent(self, edit_url): """Checks if a user may apply as a student to the program.""" if self.data.ndb_profile: if self.data.ndb_profile.is_student: raise exception.Redirect(edit_url) else: raise exception.Forbidden( message=DEF_ALREADY_PARTICIPATING_AS_NON_STUDENT % ( self.data.program.name)) self.studentSignupActive() # custom pre-registration age check for GCI students age_check = self.data.request.COOKIES.get('age_check', None) if not age_check or age_check == '0': # no age check done or it failed kwargs = dicts.filter(self.data.kwargs, ['sponsor', 'program']) age_check_url = reverse('gci_age_check', kwargs=kwargs) raise exception.Redirect(age_check_url) else: self.isLoggedIn()
def sendMailFromTemplate(template, context): """Sends out an email using a Django template. If 'html' is present in context dictionary it is overwritten with template HTML output. Args: template: the template (or search list of templates) to use context: The context supplied to the template and email (dictionary) Raises: Error that corresponds with the first problem it finds iff the message is not properly initialized. List of all possible errors: http://code.google.com/appengine/docs/mail/exceptions.html """ # render the template and put in context with 'html' as key context['html'] = loader.render_to_string(template, dictionary=context) # filter out the unneeded values in context to keep sendMail happy sendMail(dicts.filter(context, mail.EmailMessage.PROPERTIES))
def newDynaField(field, base, passthrough): """Creates a new form DynaField class. The returned class extends base, but with the following additions: * It has a dynaproperties attribute as extracted from field. * It's __metaclass__ is set to DynaFieldMetaclass (which inherits from the default type class). See DynaFieldMetaclass for an explanation on how the dynaproperties property is used to construct the DynaForm class. """ # pass only known accepted arguments to super init_args = dicts.filter(field, passthrough) properties = field.copy() # all pass through arguments are handled by super for key in passthrough: if key in properties: del properties[key] # pylint: disable-msg=E1002 class DynaField(base): """The dynamically created Field class. """ __metaclass__ = DynaFieldMetaclass dynaproperties = properties def __init__(self): """Pass through the init args to super. """ super(DynaField, self).__init__(**init_args) return DynaField
def newDynaField(field, base, passthrough): """Creates a new form DynaField class. The returned class extends base, but with the following additions: * It has a dynaproperties attribute as extracted from field. * It's __metaclass__ is set to DynaFieldMetaclass (which inherits from the default type class). See DynaFieldMetaclass for an explanation on how the dynaproperties property is used to construct the DynaForm class. """ # pass only known accepted arguments to super init_args = dicts.filter(field, passthrough) properties = field.copy() # all pass through arguments are handled by super for key in passthrough: if key in properties: del properties[key] # pylint: disable=E1002 class DynaField(base): """The dynamically created Field class. """ __metaclass__ = DynaFieldMetaclass dynaproperties = properties def __init__(self): """Pass through the init args to super. """ super(DynaField, self).__init__(**init_args) return DynaField
def testFilterKeysToFilterValid(self): """Tests if a dict is filtered correctly if some keys are given. """ keys_to_filter = ["a", "b", "c", "d"] expected_dict = {"a": "1", "b": "2", "c": "3", "d": "1"} self.assertEqual(dicts.filter(self.dummy_dict, keys_to_filter), expected_dict)