def _to_python(self, value, state): session = DBSession() value = value.lower() if session.query(User).filter_by(user_name=value).count(): if not state or state.user_id != value: raise formencode.Invalid(u'Ein Benutzer mit diesem Namen existiert bereits.', value, state) return value
def gained_competences(student): """ Returns a list of project, competences and indicator in the following form: [ { 'project' : project, 'competences' : [ 'competence' : competence, 'indicators' : [indicator, ...]] } ] """ session = DBSession() query = session.query(Project, Competence, Indicator) query = query.filter(Student.id == student.id) query = query.join(Student.journal_entries) query = query.join(JournalEntry.indicators) query = query.join(JournalEntry.project) query = query.join(Indicator.indicator_set) query = query.join(IndicatorSet.competence) query = query.order_by(Project.title) data = [] current_project = None current_competence = None for project, competence, indicator in query.all(): if project != current_project: current_project = project data.append(dict(project=project, competences=[])) if competence != current_competence: current_competence = competence data[-1]['competences'].append( dict(competence=competence, indicators=[])) data[-1]['competences'][-1]['indicators'].append(indicator) return data
def view_pw_reset(context, request): # Second step: User is visiting reset url if 'key' in request.params: key = request.params['key'] if 'form.submitted' in request.params: try: # FormEncode validation schema = PWResetSchema() form_result = schema.to_python(request.params) except formencode.validators.Invalid, why: form = render_template('templates/password_reset.pt', request=request, api=TemplateAPI(request)) # FormEncode fills template with error messages form = htmlfill.render(form, defaults=request.params, errors=why.error_dict) return Response(form) else: session = DBSession() user = session.query(User).filter_by(email=form_result['email']).one() if key == user.password_reset_key(): user.password = '******' % sha.new(form_result['password'].encode('utf-8')).hexdigest() # Login directly headers = [] plugins = request.environ.get('repoze.who.plugins', {}) identifier = plugins.get('auth_tkt') if identifier: identity = {'repoze.who.userid': form_result['email']} headers = identifier.remember(request.environ, identity) request.environ['repoze.who.userid'] = form_result['email'] return HTTPFound(location = model_url(context, request), headers=headers) else: statusmessage.show(request, u"Retrieve request not valid.", u"error") return render_template_to_response('templates/password_reset.pt', request=request, api=TemplateAPI(request))
def gained_competences(student): """ Returns a list of project, competences and indicator in the following form: [ { 'project' : project, 'competences' : [ 'competence' : competence, 'indicators' : [indicator, ...]] } ] """ session = DBSession() query = session.query(Project, Competence, Indicator) query = query.filter(Student.id == student.id) query = query.join(Student.journal_entries) query = query.join(JournalEntry.indicators) query = query.join(JournalEntry.project) query = query.join(Indicator.indicator_set) query = query.join(IndicatorSet.competence) query = query.order_by(Project.title) data = [] current_project = None current_competence = None for project, competence, indicator in query.all(): if project != current_project: current_project = project data.append(dict(project=project, competences=[])) if competence != current_competence: current_competence = competence data[-1]['competences'].append(dict(competence=competence, indicators=[])) data[-1]['competences'][-1]['indicators'].append(indicator) return data
def meta_competence_edit_view(context, request): if IMetaCompetence.providedBy(context): add_form = False meta_competence = context context = meta_competence.__parent__ else: meta_competence = MetaCompetence() add_form = True errors = {} defaults = {} if 'form.submitted' in request.POST: try: # FormEncode validation defaults = dict(request.POST) form_result = meta_competence_schema.to_python(request.POST) except formencode.validators.Invalid, why: errors=why.error_dict else: # Apply schema fields to the project object field_names = [ p.key for p in class_mapper(MetaCompetence).iterate_properties ] changed = False for field_name in field_names: if field_name in form_result.keys(): if form_result[field_name] != getattr(meta_competence, field_name): setattr(meta_competence, field_name, form_result[field_name]) changed = True # Add onjective if this is the add form if add_form: session = DBSession() session.add(meta_competence) return HTTPFound(location = model_url(context, request))
def journal_add_view(context, request): if IJournalEntry.providedBy(context): entry = context project = context.__parent__.__parent__ add_form = False else: entry = JournalEntry() project = context add_form = True errors = {} defaults = {} if 'form.submitted' in request.POST: try: # FormEncode validation defaults = dict(request.POST) defaults['indicators'] = request.POST.get('indicators') form_result = entry_schema.to_python(request.POST) except formencode.validators.Invalid, why: errors = why.error_dict else: session = DBSession() # Handle image upload if form_result['image'] is not None: entry.image = File('image.jpg', form_result['image'].read()) elif form_result['image_action'] == 'delete' and entry.image: session.delete(entry.image) entry.date = datetime.now() entry.text = form_result['text'] entry.user = authenticated_user(request) # Check whether indicator belongs to this project. indicator_query = session.query(Indicator) indicator_query = indicator_query.filter(Project.id == project.id) indicator_query = indicator_query.join(Project.objectives) indicator_query = indicator_query.join(Objective.competences) indicator_query = indicator_query.join(Competence.indicator_sets) indicator_query = indicator_query.join(IndicatorSet.indicators) if form_result['indicators']: indicator_query = indicator_query.filter( Indicator.id.in_(form_result['indicators'])) indicators = indicator_query.all() entry.indicators = indicators if add_form: project.journal_entries.append(entry) if ITeacher.providedBy(authenticated_user(request)): return HTTPFound(location=model_url( get_root(request)['projects'][project.id], request)) return HTTPFound( location=model_url(authenticated_user(request), request))
def _add_meta_competence(self, title=u'Meta competence', description=u'Meta competence'): from eportfolio.models.meta_competence import MetaCompetence from eportfolio.models import DBSession session = DBSession() meta_competence = MetaCompetence(title=title, description=description) session.add(meta_competence) session.flush() return meta_competence
def _populate_db(self): session = DBSession() # Add a teacher ############### Change user name and email here ############### if not session.query(Teacher).filter(Teacher.email == u"*****@*****.**").all(): admin = Teacher(first_name=u'Admin', last_name=u'User', email=u"*****@*****.**", password=u'password') session.add(admin)
def groupfinder(identity, request): groups = [] user_id = identity['repoze.who.userid'].decode('UTF-8') session = DBSession() user = session.query(User).filter_by(email = user_id).first() if user: groups.extend(user.groups) return groups
def authenticated_user(request): user_id = authenticated_userid(request) try: session = DBSession() user = session.query(User).filter_by(user_name=user_id).one() user.__parent__ = request.root['users'] return user except NoResultFound: return None
def groupfinder(identity, request): groups = [] user_id = identity['repoze.who.userid'].decode('UTF-8') session = DBSession() user = session.query(User).filter_by(email=user_id).first() if user: groups.extend(user.groups) return groups
def journal_add_view(context, request): if IJournalEntry.providedBy(context): entry = context project = context.__parent__.__parent__ add_form = False else: entry = JournalEntry() project = context add_form = True errors = {} defaults = {} if 'form.submitted' in request.POST: try: # FormEncode validation defaults = dict(request.POST) defaults['indicators'] = request.POST.get('indicators') form_result = entry_schema.to_python(request.POST) except formencode.validators.Invalid, why: errors=why.error_dict else: session = DBSession() # Handle image upload if form_result['image'] is not None: entry.image = File('image.jpg', form_result['image'].read()) elif form_result['image_action'] == 'delete' and entry.image: session.delete(entry.image) entry.date = datetime.now() entry.text = form_result['text'] entry.user = authenticated_user(request) # Check whether indicator belongs to this project. indicator_query = session.query(Indicator) indicator_query = indicator_query.filter(Project.id == project.id) indicator_query = indicator_query.join(Project.objectives) indicator_query = indicator_query.join(Objective.competences) indicator_query = indicator_query.join(Competence.indicator_sets) indicator_query = indicator_query.join(IndicatorSet.indicators) if form_result['indicators']: indicator_query = indicator_query.filter(Indicator.id.in_(form_result['indicators'])) indicators = indicator_query.all() entry.indicators = indicators if add_form: project.journal_entries.append(entry) if ITeacher.providedBy(authenticated_user(request)): return HTTPFound(location = model_url(get_root(request)['projects'][project.id], request)) return HTTPFound(location = model_url(authenticated_user(request), request))
def _add_indicator(self, title=u'Indicator', description=u'Indicator', indicator_set=None): from eportfolio.models.indicator import Indicator from eportfolio.models import DBSession if not indicator_set: indicator_set = self._add_indicator_set() session = DBSession() indicator = Indicator(title=title, description=description, indicator_set=indicator_set) session.add(indicator) session.flush() return indicator
def members_view(context, request): session = DBSession() all_students = session.query(Student).all() all_students = [student for student in all_students if not student in context.students] all_teachers = session.query(Teacher).all() all_teachers = [teacher for teacher in all_teachers if not teacher in context.teachers] if 'form.submitted' in request.POST: student_id = request.POST.get('student_id', None) if student_id: student = session.query(Student).filter_by(id=student_id).first() if student: context.students.append(student) teacher_id = request.POST.get('teacher_id', None) if teacher_id: teacher = session.query(Teacher).filter_by(id=teacher_id).first() if teacher: context.teachers.append(teacher) return HTTPFound(location = model_url(context, request, 'members.html')) # This should be a post request, but it has to be finished today ... elif 'remove_student' in request.GET: student_id = request.GET.get('remove_student', None) if student_id: student = context.students.filter_by(id=student_id).first() if student: context.students.remove(student) return HTTPFound(location = model_url(context, request, 'members.html')) elif 'remove_teacher' in request.GET: teacher_id = request.GET.get('remove_teacher', None) if teacher_id: teacher = context.teachers.filter_by(id=teacher_id).first() if teacher: context.teachers.remove(teacher) return HTTPFound(location = model_url(context, request, 'members.html')) root = get_root(request) students = [] for student in context.students: students.append(root['users'][student.id]) teachers = [] for teacher in context.teachers: teachers.append(root['users'][teacher.id]) return dict(api=TemplateAPI(request), context=context, students=students, all_students=all_students, teachers=teachers, all_teachers=all_teachers)
def _add_indicator_set(self, title=u'Indicator set', description=u'Indicator set', competence=None): from eportfolio.models.indicator_set import IndicatorSet from eportfolio.models import DBSession if not competence: competence = self._add_competence() session = DBSession() indicator_set = IndicatorSet(title=title, description=description, competence=competence) session.add(indicator_set) session.flush() return indicator_set
def _add_objective(self, title=u'Objective', description=u'Objective', project=None): from eportfolio.models.objective import Objective from eportfolio.models import DBSession if not project: project = self._add_project() session = DBSession() objective = Objective(title=title, description=description, project=project) session.add(objective) session.flush() return objective
def _add_competence(self, title=u'Competence', description=u'Competence', meta_competence=None): from eportfolio.models.competence import Competence from eportfolio.models import DBSession if not meta_competence: meta_competence = self._add_meta_competence() session = DBSession() competence = Competence(title=title, description=description, meta_competence=meta_competence) session.add(competence) session.flush() return competence
def _populate_db(self): session = DBSession() # Add a teacher ############### Change user name and email here ############### if not session.query(Teacher).filter( Teacher.email == u"*****@*****.**").all(): admin = Teacher(first_name=u'Admin', last_name=u'User', email=u"*****@*****.**", password=u'password') session.add(admin)
def _add_student(self, first_name=u"Buck", last_name=u"Mulligan", email=u"*****@*****.**", password=u'123456'): from eportfolio.models.student import Student from eportfolio.models import DBSession session = DBSession() student = Student() student.first_name = first_name student.last_name = last_name student.email = email student.password = u'{SHA}%s' % sha.new(password).hexdigest() session.add(student) session.flush() return student
def _add_teacher(self, first_name=u'Leopold', last_name=u'Bloom', email=u'*****@*****.**', password=u'12345'): from eportfolio.models.teacher import Teacher from eportfolio.models import DBSession session = DBSession() teacher = Teacher() teacher.first_name = first_name teacher.last_name = last_name teacher.email = email teacher.password = u'{SHA}%s' % sha.new(password).hexdigest() session.add(teacher) session.flush() return teacher
def __getitem__(self, key): if key == 'projects': session = DBSession() projects_container = Container(session.query(Project), IProjects) projects_container.__parent__ = self projects_container.__name__ = key return projects_container if key == 'users': session = DBSession() container = Container(session.query(User), IUsers) container.__parent__ = self container.__name__ = key return container if key == 'meta_competences': session = DBSession() container = Container(session.query(MetaCompetence), IMetaCompetences) container.__parent__ = self container.__name__ = key return container if key == 'competences': session = DBSession() container = Container(session.query(Competence), ICompetences) container.__parent__ = self container.__name__ = u'competences' return container raise KeyError(key)
def users_view(context, request): session = DBSession() students = session.query(Student).order_by(Student.last_name, Student.first_name).all() for student in students: student.__parent__ = context teachers = session.query(Teacher).order_by(Teacher.last_name, Teacher.first_name).all() for teacher in teachers: teacher.__parent__ = context return dict(context=context, students=students, teachers=teachers, api=TemplateAPI(request))
def __getitem__(self, key): if key == 'projects': session = DBSession() container = Container(self.projects) container.__parent__ = self container.__name__ = u'projects' return container if key == 'files': session = DBSession() container = Container(session.query(File), IFiles) container.__parent__ = self container.__name__ = u'files' return container raise KeyError(key)
def projects_view(context, request): session = DBSession() projects = session.query(Project) today = datetime.date.today() # Projects need to be traversal wrapped to make the links work. current_projects = [] for project in projects.filter(Project.end_date >= today).order_by(Project.end_date.desc()): current_projects.append(context[project.id]) past_projects = [] for project in projects.filter(Project.end_date < today).order_by(Project.end_date.desc()): past_projects.append(context[project.id]) api = TemplateAPI(request) return dict(context=context, api=api,current_projects=current_projects,past_projects=past_projects)
def view_pw_reset(context, request): # Second step: User is visiting reset url if 'key' in request.params: key = request.params['key'] if 'form.submitted' in request.params: try: # FormEncode validation schema = PWResetSchema() form_result = schema.to_python(request.params) except formencode.validators.Invalid, why: form = render_template('templates/password_reset.pt', request=request, api=TemplateAPI(request)) # FormEncode fills template with error messages form = htmlfill.render(form, defaults=request.params, errors=why.error_dict) return Response(form) else: session = DBSession() user = session.query(User).filter_by( email=form_result['email']).one() if key == user.password_reset_key(): user.password = '******' % sha.new( form_result['password'].encode('utf-8')).hexdigest() # Login directly headers = [] plugins = request.environ.get('repoze.who.plugins', {}) identifier = plugins.get('auth_tkt') if identifier: identity = {'repoze.who.userid': form_result['email']} headers = identifier.remember(request.environ, identity) request.environ['repoze.who.userid'] = form_result['email'] return HTTPFound(location=model_url(context, request), headers=headers) else: statusmessage.show(request, u"Retrieve request not valid.", u"error") return render_template_to_response('templates/password_reset.pt', request=request, api=TemplateAPI(request))
def _add_project(self, title=u"Project", start_date=None, end_date=None): from eportfolio.models.project import Project from eportfolio.models import DBSession if not start_date: start_date = datetime.date.today() - datetime.timedelta(days=10) if not end_date: end_date = datetime.date.today() + datetime.timedelta(days=10) session = DBSession() project = Project() project.title = title project.start_date = start_date project.end_date = end_date session.add(project) session.flush() return project
def objective_edit_view(context, request): session = DBSession() competences = session.query(Competence).all() if IObjective.providedBy(context): add_form = False objective = context project = context.project context = objective.__parent__ else: objective = Objective() add_form = True project = context.__parent__ errors = {} defaults = {} if 'form.submitted' in request.POST: try: # FormEncode validation defaults = dict(request.POST) form_result = objective_schema.to_python(request.POST) except formencode.validators.Invalid, why: errors=why.error_dict else: # Apply schema fields to the project object changed = False competences = [] for competence_id in form_result['competences']: competence = session.query(Competence).filter_by(id=competence_id).first() if competence: competences.append(competence) form_result['competences'] = competences for field_name in objective_schema.fields.keys(): if form_result[field_name] != getattr(objective, field_name): setattr(objective, field_name, form_result[field_name]) changed = True # Add onjective if this is the add form if add_form: objective.project = project session.add(objective) return HTTPFound(location = model_url(context, request))
def indicator_edit_view(context, request): if IIndicator.providedBy(context): indicator = context indicator_set = indicator.indicator_set add_form = False else: indicator = Indicator() indicator_set = context.__parent__ add_form = True competences_container = find_interface(context, ICompetences) errors = {} defaults = {} if 'form.submitted' in request.POST: try: # FormEncode validation defaults = dict(request.POST) form_result = indicator_schema.to_python(request.POST) except formencode.validators.Invalid, why: errors = why.error_dict else: # Apply schema fields to the project object field_names = [ p.key for p in class_mapper(Indicator).iterate_properties ] changed = False for field_name in field_names: if field_name in form_result.keys(): if form_result[field_name] != getattr( indicator, field_name): setattr(indicator, field_name, form_result[field_name]) changed = True # Add project if this is the add form if add_form: session = DBSession() indicator.indicator_set = indicator_set indicator.index = indicator_set.indicators.count() - 1 session.add(indicator) return HTTPFound( location=model_url(competences_container, request))
def competence_edit_view(context, request): session = DBSession() meta_competences = session.query(MetaCompetence).all() if ICompetence.providedBy(context): competence = context context = competence.__parent__ add_form = False else: competence = Competence() add_form = True errors = {} defaults = {} if 'form.submitted' in request.POST: try: # FormEncode validation defaults = dict(request.POST) form_result = competence_schema.to_python(request.POST) except formencode.validators.Invalid, why: errors = why.error_dict else: # Apply schema fields to the project object field_names = [ p.key for p in class_mapper(Competence).iterate_properties ] changed = False for field_name in field_names: if field_name in form_result.keys(): if form_result[field_name] != getattr( competence, field_name): setattr(competence, field_name, form_result[field_name]) changed = True # Add project if this is the add form if add_form: session.add(competence) return HTTPFound(location=model_url(context, request))
def indicator_edit_view(context, request): if IIndicator.providedBy(context): indicator = context indicator_set = indicator.indicator_set add_form = False else: indicator = Indicator() indicator_set = context.__parent__ add_form = True competences_container = find_interface(context, ICompetences) errors = {} defaults = {} if 'form.submitted' in request.POST: try: # FormEncode validation defaults = dict(request.POST) form_result = indicator_schema.to_python(request.POST) except formencode.validators.Invalid, why: errors=why.error_dict else: # Apply schema fields to the project object field_names = [ p.key for p in class_mapper(Indicator).iterate_properties ] changed = False for field_name in field_names: if field_name in form_result.keys(): if form_result[field_name] != getattr(indicator, field_name): setattr(indicator, field_name, form_result[field_name]) changed = True # Add project if this is the add form if add_form: session = DBSession() indicator.indicator_set = indicator_set indicator.index = indicator_set.indicators.count() - 1 session.add(indicator) return HTTPFound(location = model_url(competences_container, request))
def student_competence_cloud_view(context, request): session = DBSession() query = session.query(Competence.title, func.count(Competence.id)) query = query.filter(Student.id == context.id) query = query.join(Student.journal_entries) query = query.join(JournalEntry.indicators) query = query.join(Indicator.indicator_set) query = query.join(IndicatorSet.competence) query = query.group_by(Competence.id, Competence.title) tags = query.all() if tags is not None: cloud = [{'name': x[0], 'count': x[1]} for x in tags] limited = list(reversed(sorted(cloud, key=lambda x: x['count'])))[:100] entries = sorted(_calculateTagWeights(limited), key=lambda x: x['name']) else: entries = () return render_template( 'templates/competence_cloud.pt', api=TemplateAPI(request), entries=entries, )
def project_edit_view(context, request): if IProject.providedBy(context): project = context context = project.__parent__ add_form = False else: project = Project() add_form = True errors = {} defaults = {} if 'form.submitted' in request.POST: try: # FormEncode validation defaults = dict(request.POST) form_result = project_schema.to_python(request.POST) except formencode.validators.Invalid, why: errors = why.error_dict else: # Apply schema fields to the project object changed = False for field_name in project_schema.fields.keys(): if form_result[field_name] != getattr(project, field_name): setattr(project, field_name, form_result[field_name]) changed = True # Add project if this is the add form if add_form: session = DBSession() # Add the teacher that created the project to the project. user = authenticated_user(request) if ITeacher.providedBy(user): project.teachers.append(user) session.add(project) return HTTPFound(location=model_url(context, request))
def project_edit_view(context, request): if IProject.providedBy(context): project = context context = project.__parent__ add_form = False else: project = Project() add_form = True errors = {} defaults = {} if 'form.submitted' in request.POST: try: # FormEncode validation defaults = dict(request.POST) form_result = project_schema.to_python(request.POST) except formencode.validators.Invalid, why: errors=why.error_dict else: # Apply schema fields to the project object changed = False for field_name in project_schema.fields.keys(): if form_result[field_name] != getattr(project, field_name): setattr(project, field_name, form_result[field_name]) changed = True # Add project if this is the add form if add_form: session = DBSession() # Add the teacher that created the project to the project. user = authenticated_user(request) if ITeacher.providedBy(user): project.teachers.append(user) session.add(project) return HTTPFound(location = model_url(context, request))
def members_view(context, request): session = DBSession() all_students = session.query(Student).all() all_students = [ student for student in all_students if not student in context.students ] all_teachers = session.query(Teacher).all() all_teachers = [ teacher for teacher in all_teachers if not teacher in context.teachers ] if 'form.submitted' in request.POST: student_id = request.POST.get('student_id', None) if student_id: student = session.query(Student).filter_by(id=student_id).first() if student: context.students.append(student) teacher_id = request.POST.get('teacher_id', None) if teacher_id: teacher = session.query(Teacher).filter_by(id=teacher_id).first() if teacher: context.teachers.append(teacher) return HTTPFound(location=model_url(context, request, 'members.html')) # This should be a post request, but it has to be finished today ... elif 'remove_student' in request.GET: student_id = request.GET.get('remove_student', None) if student_id: student = context.students.filter_by(id=student_id).first() if student: context.students.remove(student) return HTTPFound(location=model_url(context, request, 'members.html')) elif 'remove_teacher' in request.GET: teacher_id = request.GET.get('remove_teacher', None) if teacher_id: teacher = context.teachers.filter_by(id=teacher_id).first() if teacher: context.teachers.remove(teacher) return HTTPFound(location=model_url(context, request, 'members.html')) root = get_root(request) students = [] for student in context.students: students.append(root['users'][student.id]) teachers = [] for teacher in context.teachers: teachers.append(root['users'][teacher.id]) return dict(api=TemplateAPI(request), context=context, students=students, all_students=all_students, teachers=teachers, all_teachers=all_teachers)
def objective_edit_view(context, request): session = DBSession() competences = session.query(Competence).all() if IObjective.providedBy(context): add_form = False objective = context project = context.project context = objective.__parent__ else: objective = Objective() add_form = True project = context.__parent__ errors = {} defaults = {} if 'form.submitted' in request.POST: try: # FormEncode validation defaults = dict(request.POST) form_result = objective_schema.to_python(request.POST) except formencode.validators.Invalid, why: errors = why.error_dict else: # Apply schema fields to the project object changed = False competences = [] for competence_id in form_result['competences']: competence = session.query(Competence).filter_by( id=competence_id).first() if competence: competences.append(competence) form_result['competences'] = competences for field_name in objective_schema.fields.keys(): if form_result[field_name] != getattr(objective, field_name): setattr(objective, field_name, form_result[field_name]) changed = True # Add onjective if this is the add form if add_form: objective.project = project session.add(objective) return HTTPFound(location=model_url(context, request))
def student_stats_view(context, request): session = DBSession() # Achievable competences query = session.query(Competence.id, Competence.title, func.count(Competence.id)) query = query.filter(Student.id == context.id) query = query.join(Student.projects) query = query.join(Project.objectives) query = query.join(Objective.competences) query = query.join(Competence.indicator_sets) query = query.join(IndicatorSet.indicators) query = query.group_by(Competence.id, Competence.title) achiveable = query.order_by(Competence.title).all() # Subquery in order to count each indicator only once subquery = session.query(Indicator.id.label('indicator_id')) subquery = subquery.filter(Student.id == context.id) subquery = subquery.join(Student.journal_entries) subquery = subquery.join(JournalEntry.indicators) subquery = subquery.distinct().subquery() # Achieved competences query = session.query(Competence.id, Competence.title, func.count(Competence.id)) query = query.filter(subquery.c.indicator_id == Indicator.id) query = query.join(Indicator.indicator_set) query = query.join(IndicatorSet.competence) query = query.group_by(Competence.id, Competence.title) achieved = query.order_by(Competence.title).all() # Combine the two lists into one numbers = [] for element in achiveable: number = {'label': element[1], 'achievable': element[2], 'achieved': 0} if len(achieved) and achieved[0][0] == element[0]: number['achieved'] = achieved.pop(0)[2] numbers.append(number) localizer = get_localizer(request) graph_axis = [] graph_data = [] graph_data.append({ 'label': ' %s ' % localizer.translate(_('Achieved')), 'data': [] }) graph_data.append({ 'label': ' %s ' % localizer.translate(_('Achievable')), 'data': [] }) for index, number in enumerate(numbers): graph_axis.append([index, number['label']]) graph_data[0]['data'].append([index, number['achieved']]) graph_data[1]['data'].append( [index, number['achievable'] - number['achieved']]) projects = [] for project in context['projects']: project_data = {'title': project.title} # Collect all competences for the project competences = [] for objective in project.objectives: for competence in objective.competences: achieved = False if not competence in competences: competence_data = { 'title': competence.title, 'indicator_sets': [], 'achieved': False } for indicator_set in competence.indicator_sets: indicator_set_data = { 'title': indicator_set.title, 'achieved': False } indicators = [] for indicator in indicator_set.indicators: indicator_data = { 'title': indicator.title, 'achieved': False } # Check whether indicator has been achieved query = session.query(Indicator) query = query.filter( JournalEntry.user_id == context.id) query = query.filter(Indicator.id == indicator.id) query = query.join(JournalEntry.indicators) if query.first(): achieved = True indicator_data['achieved'] = True indicators.append(indicator_data) indicator_set_data['indicators'] = indicators if achieved: indicator_set_data['achieved'] = True competence_data['indicator_sets'].append( indicator_set_data) if achieved: competence_data['achieved'] = True competences.append(competence_data) project_data['competences'] = competences projects.append(project_data) return dict(api=TemplateAPI(request), projects=projects, graph_axis=simplejson.dumps(graph_axis), graph_data=simplejson.dumps(graph_data))
location=model_url(authenticated_user(request), request)) else: if not add_form: for field_name in entry_schema.fields.keys(): if hasattr(entry, field_name): defaults[field_name] = getattr(entry, field_name) defaults['indicators'] = [ indicator.id for indicator in entry.indicators ] if entry.image: defaults['image_action'] = 'nochange' defaults['image'] = '' session = DBSession() user = authenticated_user(request) query = session.query(Indicator) query = query.filter(JournalEntry.user == user) query = query.filter(JournalEntry.project == project) query = query.filter(JournalEntry.id != entry.id) query = query.join(Indicator.journal_entries) already_tagged = query.all() query = session.query(IndicatorSet) query = query.filter(Project.id == project.id) query = query.join(Project.objectives) query = query.join(Objective.competences) query = query.join(Competence.indicator_sets) indicator_sets = [] for indicator_set in query.all():
if 'form.submitted' in request.params: try: # FormEncode validation schema = PWResetRequestSchema() form_result = schema.to_python(request.params) except formencode.validators.Invalid, why: form = render_template( 'templates/password_retrieve.pt', request=request, api=TemplateAPI(request), ) # FormEncode fills template with error messages form = htmlfill.render(form, defaults=request.params, errors=why.error_dict) return Response(form) else: session = DBSession() user = session.query(User).filter_by( email=form_result['email']).one() reset_url = model_url(get_root(request), request, 'retrieve_password.html') user.send_password_reset(reset_url) statusmessage.show(request, u'Password retrieval e-mail sent.') return HTTPFound(location=model_url(context, request)) return render_template_to_response('templates/password_retrieve.pt', request=request, api=TemplateAPI(request))
def tearDown(self): from eportfolio.models import DBSession import transaction DBSession.remove() transaction.abort() self.config.end()
def _to_python(self, value, state): session = DBSession() if not session.query(User).filter_by(email=value).all(): raise formencode.Invalid('Username not found.', value, state) return value
def teacher_edit_view(context, request): if ITeacher.providedBy(context): teacher = context context = teacher.__parent__ add_form = False else: teacher = Teacher(id=uuid.uuid4()) add_form = True errors = {} defaults = {} if 'form.submitted' in request.POST: try: # FormEncode validation defaults = dict(request.POST) state = FormencodeState() state.user_id = teacher.user_name if add_form: form_result = teacher_add_schema.to_python(request.POST, state) else: form_result = teacher_schema.to_python(request.POST, state) except formencode.validators.Invalid, why: errors=why.error_dict else: changed = False # Convert password to SHA hash if form_result.get('password', None): form_result['password'] = '******' % sha.new(form_result['password']).hexdigest() changed = True # Handle portrait upload if form_result['portrait'] is not None: # Scale image and convert to JPEG im = Image.open(form_result['portrait'].file) im.thumbnail((128, 128),Image.ANTIALIAS) # Convert to RGB if neccessary if im.mode != "RGB": im = im.convert("RGB") outfile = StringIO() im.save(outfile, "JPEG") outfile.seek(0) teacher.portrait = File('portrait.jpg', outfile.read()) changed = True del form_result['portrait'] # Apply schema fields to the student object field_names = [ p.key for p in class_mapper(Teacher).iterate_properties ] for field_name in field_names: if field_name in form_result.keys(): if form_result[field_name] != getattr(teacher, field_name): setattr(teacher, field_name, form_result[field_name]) changed = True # Add student if this is the add form if add_form: session = DBSession() session.add(teacher) if not form_result['password']: reset_url = model_url(get_root(request), request, 'retrieve_password.html') teacher.send_password_reset(reset_url) return HTTPFound(location = model_url(context, request))
def student_stats_view(context, request): session = DBSession() # Achievable competences query = session.query(Competence.id, Competence.title, func.count(Competence.id)) query = query.filter(Student.id == context.id) query = query.join(Student.projects) query = query.join(Project.objectives) query = query.join(Objective.competences) query = query.join(Competence.indicator_sets) query = query.join(IndicatorSet.indicators) query = query.group_by(Competence.id, Competence.title) achiveable = query.order_by(Competence.title).all() # Subquery in order to count each indicator only once subquery = session.query(Indicator.id.label('indicator_id')) subquery = subquery.filter(Student.id == context.id) subquery = subquery.join(Student.journal_entries) subquery = subquery.join(JournalEntry.indicators) subquery = subquery.distinct().subquery() # Achieved competences query = session.query(Competence.id, Competence.title, func.count(Competence.id)) query = query.filter(subquery.c.indicator_id == Indicator.id) query = query.join(Indicator.indicator_set) query = query.join(IndicatorSet.competence) query = query.group_by(Competence.id, Competence.title) achieved = query.order_by(Competence.title).all() # Combine the two lists into one numbers = [] for element in achiveable: number = {'label' : element[1], 'achievable' : element[2], 'achieved' : 0} if len(achieved) and achieved[0][0] == element[0]: number['achieved'] = achieved.pop(0)[2] numbers.append(number) localizer = get_localizer(request) graph_axis = [] graph_data = [] graph_data.append({ 'label' : ' %s ' % localizer.translate(_('Achieved')), 'data' : [] }) graph_data.append({ 'label' : ' %s ' % localizer.translate(_('Achievable')), 'data' : [] }) for index, number in enumerate(numbers): graph_axis.append([index, number['label']]) graph_data[0]['data'].append([index, number['achieved']]) graph_data[1]['data'].append([index, number['achievable'] - number['achieved']]) projects = [] for project in context['projects']: project_data = {'title' : project.title} # Collect all competences for the project competences = [] for objective in project.objectives: for competence in objective.competences: achieved = False if not competence in competences: competence_data = {'title' : competence.title, 'indicator_sets' : [], 'achieved' : False} for indicator_set in competence.indicator_sets: indicator_set_data = {'title' : indicator_set.title, 'achieved' : False} indicators = [] for indicator in indicator_set.indicators: indicator_data = {'title' : indicator.title, 'achieved' : False} # Check whether indicator has been achieved query = session.query(Indicator) query = query.filter(JournalEntry.user_id == context.id) query = query.filter(Indicator.id == indicator.id) query = query.join(JournalEntry.indicators) if query.first(): achieved = True indicator_data['achieved'] = True indicators.append(indicator_data) indicator_set_data['indicators'] = indicators if achieved: indicator_set_data['achieved'] = True competence_data['indicator_sets'].append(indicator_set_data) if achieved: competence_data['achieved'] = True competences.append(competence_data) project_data['competences'] = competences projects.append(project_data) return dict(api=TemplateAPI(request), projects=projects, graph_axis=simplejson.dumps(graph_axis), graph_data=simplejson.dumps(graph_data))
if ITeacher.providedBy(authenticated_user(request)): return HTTPFound(location = model_url(get_root(request)['projects'][project.id], request)) return HTTPFound(location = model_url(authenticated_user(request), request)) else: if not add_form: for field_name in entry_schema.fields.keys(): if hasattr(entry, field_name): defaults[field_name] = getattr(entry, field_name) defaults['indicators'] = [indicator.id for indicator in entry.indicators] if entry.image: defaults['image_action'] = 'nochange' defaults['image'] = '' session = DBSession() user = authenticated_user(request) query = session.query(Indicator) query = query.filter(JournalEntry.user == user) query = query.filter(JournalEntry.project == project) query = query.filter(JournalEntry.id != entry.id) query = query.join(Indicator.journal_entries) already_tagged = query.all() query = session.query(IndicatorSet) query = query.filter(Project.id == project.id) query = query.join(Project.objectives) query = query.join(Objective.competences) query = query.join(Competence.indicator_sets) indicator_sets = [] for indicator_set in query.all():
def teacher_edit_view(context, request): if ITeacher.providedBy(context): teacher = context context = teacher.__parent__ add_form = False else: teacher = Teacher(id=uuid.uuid4()) add_form = True errors = {} defaults = {} if "form.submitted" in request.POST: try: # FormEncode validation defaults = dict(request.POST) state = FormencodeState() state.user_id = teacher.user_name if add_form: form_result = teacher_add_schema.to_python(request.POST, state) else: form_result = teacher_schema.to_python(request.POST, state) except formencode.validators.Invalid, why: errors = why.error_dict else: changed = False # Convert password to SHA hash if form_result.get("password", None): form_result["password"] = "******" % sha.new(form_result["password"]).hexdigest() changed = True # Handle portrait upload if form_result["portrait"] is not None: # Scale image and convert to JPEG im = Image.open(form_result["portrait"].file) im.thumbnail((128, 128), Image.ANTIALIAS) # Convert to RGB if neccessary if im.mode != "RGB": im = im.convert("RGB") outfile = StringIO() im.save(outfile, "JPEG") outfile.seek(0) teacher.portrait = File("portrait.jpg", outfile.read()) changed = True del form_result["portrait"] # Apply schema fields to the student object field_names = [p.key for p in class_mapper(Teacher).iterate_properties] for field_name in field_names: if field_name in form_result.keys(): if form_result[field_name] != getattr(teacher, field_name): setattr(teacher, field_name, form_result[field_name]) changed = True # Add student if this is the add form if add_form: session = DBSession() session.add(teacher) if not form_result["password"]: reset_url = model_url(get_root(request), request, "retrieve_password.html") teacher.send_password_reset(reset_url) return HTTPFound(location=model_url(context, request))