def test_get(self): from pyramid_simpleform import State obj = State(foo="bar") self.assert_(obj.get("foo") == "bar") self.assert_(obj.get("bar", "foo") == "foo")
def view_user_edit(self): """ View for editing a single user """ form = Form(self.request, schema=UserEditSchema, state=State(request=self.request)) self.error_message = None if form.validate(): password = self.request.params['password'] if self.context.validate_password(password): if self.request.params['new_password']: password = self.request.params['new_password'] self.message = 'Successfully saved' email = self.request.params['email'] self.context.edit(password, email) else: self.error_message = msg['password_invalid'] _dict = { 'username': self.context.username, 'form': FormRenderer(form), 'email': self.context.email, 'message': self.message, 'error_message': self.error_message } return dict(self.base_dict.items() + _dict.items())
def test_setitem(self): from pyramid_simpleform import State obj = State() obj['foo'] = "bar" self.assert_(obj['foo'] == 'bar') self.assert_(obj.foo == 'bar')
def view_blog_edit(self): form = Form(self.request, schema=BlogCreateSchema, state=State(request=self.request)) blogname = get_param(self.request, 'blogname', self.context.name) text = get_param(self.request, 'text', self.context.description) image_url = get_param(self.request, 'image_url', self.context.image_url) if form.validate(): self.context.name = blogname self.context.description = text self.context.image_url = image_url self.message = msg['saved'] cbs = [p for p in self.request.params.keys() if u'checkbox' in p] # check all the checkbox-parameters and # parse them for cb in cbs: item = self.request.params[cb] self.context.remove(item) self.message = msg['items_removed'] _dict = { 'form': FormRenderer(form), 'message': self.message, 'blogname': blogname, 'text': text, 'image_url': image_url } return dict(self.base_dict.items() + _dict.items())
def view_signup(self): """ Register view for new users that aren't signed up yet """ username = get_param(self.request, 'username') email = get_param(self.request, 'email') password = u'' # Create form by using schemas with validations form = Form(self.request, schema=SignUpSchema, state=State(request=self.request)) if form.validate(): username = self.request.params['username'] password = self.request.params['password'] email = self.request.params['email'] get_resource('users', self.request).add(username, password, email) get_resource('groups', self.request).add(username, group_names['member']) get_resource('groups', self.request).add(username, u'u:%s' % username) self.message = msg['succeed_add_user'] + " " + username _dict = { 'url': self.request.application_url + '/signup', 'username': username, 'email': email, 'password': password, 'form': FormRenderer(form), 'params': self.request.params, 'message': self.message } return dict(self.base_dict.items() + _dict.items())
def __init__(self, request): def formencode_translator(x): if not isinstance(x, TranslationString): x = fe_tsf(x) return gettext(x, request) self.form = Form(request, state=State(_=formencode_translator, request=request)) self.renderer = CiocFormRenderer(self.form) self._defaults = None
def api_user_change_password(request): """用户修改密码api """ form = Form(request, defaults={}, schema=ChangePasswordSchema(), state=State(request=request)) if form.validate(): conn = DBSession() request.user.password = md5(form.data['newpassword']) conn.flush() return {} return dict(code=101, error=FormRenderer(form).errorlist())
def create_note(request): user = get_current_user(request) form = Form( request, schema=NoteSchema(), state=State(user=user)) if form.validate(): note = form.bind(Note()) note.user = user DBSession.add(note) request.session.flash(u'Note is successfully created', 'success') return HTTPFound(location=request.route_url('notes')) return _response_dict( request, renderer=FormRenderer(form) )
def settings(request): user = get_current_user(request) form = Form( request, ChangePasswordSchema(), state=State(user=user) ) if form.validate(): user.password = form.data['password'] DBSession.add(user) request.session.flash(u'Password was successfully changed', 'success') return HTTPFound(location=request.route_url('settings')) return _response_dict( request, renderer=FormRenderer(form) )
def api_mentor_assignment_markupload(request): validators = dict(uploadid=formencode.validators.Int(not_empty=True), mark=formencode.validators.Number(not_empty=True)) form = Form(request, validators=validators, state=State(request=request)) if form.validate(): conn = DBSession() assignmentupload = conn.query(AssignmentUpload).filter( AssignmentUpload.id == form.data['uploadid']).first() if assignmentupload: assignmentupload.state = 1 assignmentupload.mark = form.data['mark'] conn.flush() return {} return dict(code=1401, error=u'作业已经不存在') return dict(code=101, error=form.errors)
def api_user_uploadfile(request): """用户上传文件,需要传入路径和 """ validators=dict(uploadfile=formencode.validators.FieldStorageUploadConverter(\ not_empty=True,messages=dict(empty=(u'文件不能为空' )))) form = Form(request, validators=validators, state=State(request=request)) if form.validate(): try: path = "frostcms/upload" if not os.path.exists(path): os.makedirs(path) extension = form.data['uploadfile'].filename.split('.')[-1:][0] uid = uuid.uuid1() filename = "%s.%s" % (uid, extension) filepath = os.path.join(path, filename).replace("\\", "/") myfile = open(filepath, 'wb') form.data['uploadfile'].file.seek(0) while 1: tmp = form.data['uploadfile'].file.read(2 << 16) if not tmp: break myfile.write(tmp) myfile.close() fsfile = Fsfile() fsfile.id = uid fsfile.userid = request.user.id fsfile.createtime = time.time() fsfile.filename = form.data['uploadfile'].filename fsfile.filepath = filepath conn = DBSession() conn.add(fsfile) conn.flush() returnStr = str( dict(fsfileid=str(uid), filename=str(fsfile.filename))) #returnStr="<body><pre>"+str(result)+"</pre></body>" response = request.response response.headers['Pragma'] = 'no-cache' response.headers['Cache-Control'] = 'no-cache' response.headers['Expires'] = '0' response.headers['Content-Type'] = "text/html" response.write(returnStr) return response except Exception, e: return dict(code=301, error=u'参数错误')
def test_errorlist_with_custom_localizer(self): from pyramid_simpleform import Form from pyramid_simpleform import State from pyramid_simpleform.renderers import FormRenderer request = testing.DummyRequest() request.method = "POST" state = State(_=lambda s: s.upper()) form = Form(request, SimpleFESchema, state=state) form.validate() renderer = FormRenderer(form) self.assertEqual(renderer.errorlist('name'), '<ul class="error"><li>MISSING VALUE</li></ul>')
def view_blogpost_edit(self): form = Form(self.request, schema=BlogPostSchema, state=State(request=self.request)) if form.validate(): self.message = msg['saved'] title = self.request.params[u'title'] text = self.request.params[u'text'] self.context.title = title self.context.text = text _dict = { 'project': '', 'title': self.context.title, 'text': self.context.text, 'form': FormRenderer(form), 'message': self.message } return dict(self.base_dict.items() + _dict.items())
def view_blog_remove(self): """ The Blog can be removed from this view """ form = Form(self.request, schema=BaseSchema, state=State(request=self.request)) self.message = "Edit %s" % self.context.name if form.validate(): return HTTPFound(location=resource_url(self.context.__parent__, self.request)) _dict = { 'page': self.context, 'blogname': self.context.name, 'message': self.message, 'form': FormRenderer(form) } return dict(self.base_dict.items() + _dict.items())
def view_edit(self): title = get_param(self.request, 'title', self.context.title) text = get_param(self.request, 'text', self.context.text) form = Form(self.request, schema=PageEditSchema, state=State(request=self.request)) if form.validate(): self.message = msg['saved'] self.context.text = text self.context.title = title _dict = { 'title': title, 'text': text, 'form': FormRenderer(form), 'message': self.message } return dict(self.base_dict.items() + _dict.items())
def api_mentor_assignment_overmark(request): validators = dict(assignmentid=formencode.validators.Int(not_empty=True)) form = Form(request, validators=validators, state=State(request=request)) if form.validate(): conn = DBSession() assignment = conn.query(Assignment).filter( Assignment.id == form.data['assignmentid']).first() if assignment: assignment.state = 2 assignmentuploads = conn.query(AssignmentUpload).filter( AssignmentUpload.assignmentid == form.data['assignmentid']).all() for assignmentupload in assignmentuploads: assignmentupload.state = 2 conn.flush() return dict(return_url="/mentor/assignment/list") return dict(code=1401, error=u'作业已经不存在') return dict(code=101, error=form.errors)
def view_login(self): """ Login view """ login_url = resource_url(self.request.context, self.request, 'login') referrer = self.request.url if referrer == login_url: # never use the login form itself as came_from referrer = '/' came_from = self.request.params.get('came_from', referrer) username = '' password = '' # Create form by using schemas with validations form = Form(self.request, schema=LoginSchema, state=State(request=self.request), defaults={'klass': 'class'}) if form.validate(): username = self.request.params['username'] password = self.request.params['password'] try: if self.context['users'][username].validate_password(password): headers = remember(self.request, username) return HTTPFound(location=came_from, headers=headers) except KeyError: pass self.message = msg['login_failed'] if self.logged_in: self.message = msg['logged_in_as'] + " " + self.logged_in + ". " if type(self.context) == HTTPForbidden: self.message += msg['content_forbidden'] _dict = { 'url': self.request.application_url + 'login', 'came_from': came_from, 'username': username, 'password': password, 'form': FormRenderer(form), 'message': self.message } return dict(self.base_dict.items() + _dict.items())
def api_mentor_courseware_add(request): conn = DBSession() validators=dict(fsfileid=formencode.validators.String(not_empty=True,min=16,messages=dict(empty=(u'文件不能为空' ))),\ title=formencode.validators.String(not_empty=True,messages=dict(empty=(u'标题不能为空'))),\ description=formencode.validators.String(not_empty=True,messages=dict(empty=(u'描述不能为空')))) form = Form(request, validators=validators, state=State(request=request)) if form.validate(): mentor = conn.query(Mentor).filter( Mentor.userid == request.user.id).first() courseware = Courseware() courseware.title = form.data['title'] courseware.description = form.data['description'] courseware.createtime = time.time() courseware.mentorid = mentor.id courseware.fsfileid = form.data['fsfileid'] conn.add(courseware) conn.flush() return dict(return_url='/mentor/courseware/list') return dict(code=101, error=form.errors)
def view_news_item_edit(self): form = Form(self.request, schema=NewsCreateSchema, state=State(request=self.request)) title = get_param(self.request, 'title', _return=self.context.title) text = get_param(self.request, 'text', _return=self.context.text) image_url = get_param(self.request, 'image_url', _return=self.context.image_url) if form.validate(): self.context.title = title self.context.text = text self.context.image_url = image_url self.message = msg['saved'] _dict = { 'title': title, 'content': text, 'image_url': image_url, 'form': FormRenderer(form), } return dict(self.base_dict.items() + _dict.items())
def view_news_edit(self): form = Form(self.request, schema=BaseSchema, state=State(request=self.request)) if form.validate(): # Filter checkbox-parameters from request cbs = [p for p in self.request.params.keys() if u'checkbox' in p] # check all the checkbox-parameters and # parse them for cb in cbs: item = self.request.params[cb] self.context.remove(item) self.message = msg['items_removed'] _dict = { 'context_url': resource_url(self.context, self.request), 'form': FormRenderer(form), 'message': self.message, } return dict(self.base_dict.items() + _dict.items())
def api_mentor_assignment_add(request): conn = DBSession() validators=dict(fsfileid=formencode.validators.String(not_empty=True,min=16,messages=dict(empty=(u'文件不能为空' ))),\ title=formencode.validators.String(not_empty=True,messages=dict(empty=(u'标题不能为空'))),\ description=formencode.validators.String(not_empty=True,messages=dict(empty=(u'描述不能为空'))),\ duedate=formencode.validators.String(not_empty=True,messages=dict(empty=(u'截止时间不能为空'))), lessonid=formencode.validators.Int(not_empty=True), assignmentid=formencode.validators.Int(not_empty=False)) form = Form(request, validators=validators, state=State(request=request)) if form.validate(): try: lesson=conn.query(Lesson).filter(Lesson.id==form.data['lessonid'],Lesson.courseid.in_(\ conn.query(Course.id).filter(Course.mentorid.in_(\ conn.query(Mentor.id).filter(Mentor.userid==request.user.id))))).first() if form.data['assignmentid'] and int(form.data['assignmentid']): assignment = conn.query(Assignment).filter( Assignment.id == lesson.assignmentid).first() assignment.title = form.data['title'] assignment.fsfileid = form.data['fsfileid'] assignment.duedate = time.mktime( time.strptime(form.data['duedate'], '%Y-%m-%d')) assignment.description = form.data['description'] conn.flush() else: assignment = Assignment() assignment.title = form.data['title'] assignment.fsfileid = form.data['fsfileid'] assignment.duedate = time.mktime( time.strptime(form.data['duedate'], '%Y-%m-%d')) assignment.description = form.data['description'] conn.add(assignment) conn.flush() lesson.assignmentid = assignment.id conn.flush() return dict(return_url='/mentor/lesson/listbycourse?courseid=' + str(lesson.courseid)) except Exception, e: log.debug(e) return dict(code=301, error=u'参数错误')
def view_news_create(self): form = Form(self.request, schema=NewsCreateSchema, state=State(request=self.request)) title = get_param(self.request, 'title') text = get_param(self.request, 'text') image_url = get_param(self.request, 'image_url') if form.validate(): item_context = self.context.add(title, text, image_url, self.logged_in) return HTTPFound(location=resource_url(item_context, self.request)) _dict = { 'page': self.context, 'context_url': resource_url(self.context, self.request), 'form': FormRenderer(form), 'title': title, 'content': text, 'image_url': image_url, } return dict(self.base_dict.items() + _dict.items())
def update_note(request): user = get_current_user(request) note_id = request.matchdict['note_id'] note = DBSession.query(Note).filter(Note.id == note_id).first() form = Form( request, schema=NoteSchema(), state=State(user=user), obj=note) if form.validate(): note = form.bind(note) DBSession.add(note) request.session.flash(u'Note is successfully updated', 'success') # build redirect url location = request.route_url('notes') if note.pad is not None: location = request.route_url('pad_notes', pad_id=note.pad.id) return HTTPFound(location=location) return _response_dict( request, note=note, renderer=FormRenderer(form) )
def view_blog_create(self): """ View for creating a single blog """ logged_in = authenticated_userid(self.request) form = Form(self.request, schema=BlogCreateSchema, state=State(request=self.request)) blogname = get_param(self.request, 'blogname') text = get_param(self.request, 'text') image_url = get_param(self.request, 'image_url') if form.validate(): blog = self.context.add(blogname, text, image_url, logged_in) return HTTPFound(location=resource_url(blog, self.request)) _dict = { 'form': FormRenderer(form), 'message': self.message, 'blogname': blogname, 'text': text, 'image_url': image_url } return dict(self.base_dict.items() + _dict.items())
def api_student_assignment_upload(request): conn = DBSession() validators=dict(fsfileid=formencode.validators.String(not_empty=True,min=16,messages=dict(empty=(u'文件不能为空' ))),\ title=formencode.validators.String(not_empty=True,messages=dict(empty=(u'标题不能为空'))),\ description=formencode.validators.String(not_empty=True,messages=dict(empty=(u'描述不能为空'))),\ uploadid=formencode.validators.Int(not_empty=False), assignmentid=formencode.validators.Int(not_empty=True)) form = Form(request, validators=validators, state=State(request=request)) student = conn.query(Student).filter( Student.userid == request.user.id).first() if form.validate(): try: assignment = conn.query(Assignment).filter( Assignment.id == form.data['assignmentid']).first() if form.data['uploadid'] and int(form.data['uploadid']): upload = conn.query(AssignmentUpload).filter( AssignmentUpload.id == int(form.data['uploadid'])).first() upload.title = form.data['title'] upload.fsfileid = form.data['fsfileid'] upload.description = form.data['description'] upload.updatetime = time.time() upload.studentid = student.id conn.flush() else: upload = AssignmentUpload() upload.assignmentid = form.data['assignmentid'] upload.title = form.data['title'] upload.fsfileid = form.data['fsfileid'] upload.createtime = time.time() upload.updatetime = time.time() upload.description = form.data['description'] upload.studentid = student.id conn.add(upload) conn.flush() return dict(return_url='/student/assignment/list') except Exception, e: log.debug(e) return dict(code=301, error=u'参数错误')
def view_blog_add_post(self): form = Form(self.request, schema=BlogPostSchema, state=State(request=self.request)) message = "" title = get_param(self.request, 'title') text = get_param(self.request, 'text') if form.validate(): post_context = self.context.add(title, text, self.logged_in) return HTTPFound(location=resource_url(post_context, self.request)) _dict = { 'page': self.context, 'blogname': self.context.name, 'text': text, 'title': title, 'message': message, 'form': FormRenderer(form), } return dict(self.base_dict.items() + _dict.items())
def test_get(self): from pyramid_simpleform import State obj = State(foo="bar") self.assert_(obj.get('foo') == 'bar') self.assert_(obj.get('bar', 'foo') == 'foo')
def view_users_edit(self): """ View for editing users. Includes permission handling. """ form = Form(self.request, schema=UsersEditSchema, state=State(request=self.request)) search_results = [] search = get_param(self.request, 'search') if form.validate(): # Loop through all the users and create dict of groups for user in self.context: if search.lower() in self.context[user].username.lower(): search_results.append(self.context[user]) if 'save' in self.request.params.keys() and \ self.request.params['save'] == 'Save': self.message = msg['saved'] # Filter checkbox-parameters from request cbs = [p for p in self.request.params.keys() if u'checkbox' in p] users = [self.request.params[p] for p in self.request.params.keys() if u'user' == p] # new policy for groups updated = {} # check all the checkbox-parameters and # parse them for cb in cbs: username = cb.split(':')[1] try: updated[username] except KeyError: updated[username] = [] updated[username] += [self.request.params[cb]] groups_tool = get_resource('groups', self.request) # Init users as empty first, then update with checkbox-data # TODO: add 'u:user' group? for user in users: groups_tool.flush(user) groups_tool.add_policy(updated) def has_group(group, user, request): """ Check if the user belongs to the group """ return group_names[group] in groupfinder(user.username, request) def sorted_gnames(): """ Sort list of keys to make sure they are in right order """ return sorted(group_names.keys()) _dict = { 'page': self.context, 'form': FormRenderer(form), 'search_results': search_results, 'message': self.message, 'group_names': group_names, 'has_group': has_group, 'sorted_gnames': sorted_gnames(), 'result_count': len(search_results), 'search_term': search } return dict(self.base_dict.items() + _dict.items())
def test_state_not_contains(self): from pyramid_simpleform import State obj = State(foo="bar") self.assert_("bar" not in obj)
def test_getitem(self): from pyramid_simpleform import State obj = State(foo="bar") self.assert_(obj['foo'] == 'bar')
def test_getitem_notfound(self): from pyramid_simpleform import State obj = State() self.assertRaises(KeyError, obj.__getitem__, 'foo')
def test_get(self): from pyramid_simpleform import State obj = State(foo="bar") self.assert_(obj.get('foo') == 'bar') self.assert_(obj.get('bar', 'foo') == 'foo')