def test_variable_decode(): from formencode.variabledecode import variable_encode obj = dict(a=["1", "2", "3"], b=dict(c=[dict(d="1")])) params = variable_encode(dict(obj=obj), add_repetitions=False) resp = app.get("/test_vardec", params=params) assert resp.json["obj"] == obj, (resp.json["obj"], obj)
def save(self): """Updates existing BLD File. This is the action referenced by the HTML form rendered by the update action. """ dateFormat = session.get('userSettings').get('dateFormat') if dateFormat == 'DD/MM/YYYY': schema = UpdateFileFormDM() else: schema = UpdateFileForm() values = dict(request.params) try: result = schema.to_python(dict(request.params), c) except Invalid, e: id = int(values['ID']) file_q = meta.Session.query(model.File) file = file_q.filter_by(id=id).first() c.file = file return renderAddFile( values=values, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False ), addUpdate='update' )
def _api_call(self, method, path, wrap_args=None, user='******', status=None, **params): ''' If you need to use one of the method kwargs as a URL parameter, pass params={...} as a dict instead of **kwargs ''' if 'params' in params: params = params['params'] if wrap_args: params = {wrap_args: params} if status is None: status = [200, 201, 301, 302] params = variabledecode.variable_encode(params, add_repetitions=False) token = self.token(user).api_key headers = {'Authorization': 'Bearer {}'.format(token)} fn = getattr(self.app, method.lower()) response = fn(str(path), params=params, headers=headers, status=status) if response.status_int in [301, 302]: return response.follow() else: return response
def search(self,id=None,page=1): identity = request.environ.get('repoze.who.identity') c.menu_items = h.top_menu(self.menu_items,_('Shop online')) action = request.params.getone('action') values = dict(request.params) del values['action'] if is_met(in_group('customer')): schema = InvoiceSearchCustomer() try: result = schema.to_python(dict(request.params), c) except Invalid, e: html = render('/derived/invoice/customer/index.html') return htmlfill.render(html, defaults=values, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False )) querystr = "Session.query(Invoice).filter_by(deleted=False).join(Invoice.customer).filter(User.user_name == '%s')"%identity['user'].user_name products = result['contains_product'] if products : querystr += ".join(Invoice.invoice_items).join(Invoice_item.product)" if len(products)>1: querystr += ".filter(and_(" for item in products: querystr += "," querystr += "Product.name.like('%%%s%%')"%item querystr += "))" else: querystr += ".filter(Product.name.like('%%%s%%'))"%products[0]
def test_import_custom_field(self): params = dict( custom_fields=[ dict(name='_resolution', label='Resolution', type='select', options='oné "one and á half" two'), ], open_status_names='aa bb', closed_status_names='cc', ) self.app.post( '/admin/bugs/set_custom_fields', params=variable_encode(params)) here_dir = os.path.dirname(__file__) api_ticket = M.ApiTicket(user_id=c.user._id, capabilities={'import': ['Projects','test']}, expires=datetime.utcnow() + timedelta(days=1)) ming.orm.session(api_ticket).flush() self.set_api_token(api_ticket) doc_text = open(here_dir + '/data/sf.json').read() doc_json = json.loads(doc_text) ticket_json = doc_json['trackers']['default']['artifacts'][0] r = self.api_post('/rest/p/test/bugs/perform_import', doc=doc_text, options='{"user_map": {"hinojosa4": "test-admin", "ma_boehm": "test-user"}}') assert r.json['status'], r.json ming.orm.ThreadLocalORMSession.flush_all() M.MonQTask.run_ready() ming.orm.ThreadLocalORMSession.flush_all() r = self.app.get('/p/test/bugs/204/') assert '<option selected value="fixed">fixed</option>' in r assert '<option value="one and á half">one and á half</option>' in r
def _api_getpost(self, method, path, api_key=None, api_timestamp=None, api_signature=None, wrap_args=None, **params): if wrap_args: params = {wrap_args: params} params = variabledecode.variable_encode(params, add_repetitions=False) if api_key: params['api_key'] = api_key if api_timestamp: params['api_timestamp'] = api_timestamp if api_signature: params['api_signature'] = api_signature params = self.token.sign_request(path, params) fn = self.app.post if method == 'POST' else self.app.get response = fn(str(path), params=params, status=[200, 302, 400, 403, 404]) if response.status_int == 302: return response.follow() else: return response
def _api_getpost(self, method, path, api_key=None, api_timestamp=None, api_signature=None, wrap_args=None, user='******', status=None, **params): ''' If you need to use one of the method kwargs as a URL parameter, pass params={...} as a dict instead of **kwargs ''' if 'params' in params: params = params['params'] if wrap_args: params = {wrap_args: params} if status is None: status = [200, 201, 301, 302, 400, 403, 404] params = variabledecode.variable_encode(params, add_repetitions=False) if api_key: params['api_key'] = api_key if api_timestamp: params['api_timestamp'] = api_timestamp if api_signature: params['api_signature'] = api_signature params = self.token(user).sign_request(path, params) fn = self.app.post if method == 'POST' else self.app.get response = fn(str(path), params=params, status=status) if response.status_int in [301, 302]: return response.follow() else: return response
def save(self): """Save the changed application settings. This action both saves the application settings to the model and updates app_globals with the application settings info. """ c.colorsCSSOptions = os.listdir(os.path.join( config['pylons.paths']['root'], 'public', 'css', 'colors' )) schema = AlterSettingsForm() values = dict(request.params) try: self.form_result = schema.to_python(dict(request.params), c) except Invalid, e: return renderEditSettings( values=values, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False ) ) return render('/derived/settings/index.html')
def _api_getpost(self, method, path, api_key=None, api_timestamp=None, api_signature=None, wrap_args=None, user='******', status=None, **params): ''' If you need to use one of the method kwargs as a URL parameter, pass params={...} as a dict instead of **kwargs ''' if 'params' in params: params = params['params'] if wrap_args: params = {wrap_args: params} if status is None: status = [200, 201, 301, 302, 400, 403, 404] params = variabledecode.variable_encode(params, add_repetitions=False) if api_key: params['api_key'] = api_key if api_timestamp: params['api_timestamp'] = api_timestamp if api_signature: params['api_signature'] = api_signature params = self.token(user).sign_request(path, params) fn = self.app.post if method=='POST' else self.app.get response = fn( str(path), params=params, status=status) if response.status_int in [301, 302]: return response.follow() else: return response
def _setUp(self): self.app.get('/wiki/') self.app.get('/bugs/') self.app.post( '/bugs/save_ticket', params=variable_encode(dict( ticket_form=dict( ticket_num='', labels='', assigned_to='', milestone='', summary='This is a ticket', status='open', description='This is a description'))), status=302) title = u'Descri\xe7\xe3o e Arquitetura'.encode('utf-8') self.app.post( '/wiki/%s/update' % title, params=dict( title=title, text="Nothing much", labels='', ), status=302) self.app.get('/wiki/%s/' % title)
def test_milestone_names(self): params = { 'open_status_names': 'aa bb', 'closed_status_names': 'cc', 'custom_fields': [dict( label='Milestone', show_in_search='on', type='milestone', milestones=[ dict(name='aaaé'), dict(name='bbb'), dict(name='ccc')])] } self.app.post('/admin/bugs/set_custom_fields', variable_encode(params), status=302) self.new_ticket(summary='test milestone names') self.app.post('/bugs/1/update_ticket',{ 'summary':'zzz', 'description':'bbb', 'status':'ccc', '_milestone':'aaaé', 'assigned_to':'', 'labels':'', 'labels_old':'', 'comment': '' }) ticket_view = self.app.get('/p/test/bugs/1/') assert 'Milestone' in ticket_view assert 'aaaé' in ticket_view
def save(self): """Updates existing BLD File. This is the action referenced by the HTML form rendered by the update action. """ dateFormat = session.get('userSettings').get('dateFormat') if dateFormat == 'DD/MM/YYYY': schema = UpdateFileFormDM() else: schema = UpdateFileForm() values = dict(request.params) try: result = schema.to_python(dict(request.params), c) except Invalid, e: id = int(values['ID']) file_q = meta.Session.query(model.File) file = file_q.filter_by(id=id).first() c.file = file return renderAddFile(values=values, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False), addUpdate='update')
def _api_call(self, method, path, wrap_args=None, user='******', status=None, **params): ''' If you need to use one of the method kwargs as a URL parameter, pass params={...} as a dict instead of **kwargs ''' if 'params' in params: params = params['params'] if wrap_args: params = {wrap_args: params} if status is None: status = [200, 201, 301, 302] params = variabledecode.variable_encode(params, add_repetitions=False) token = self.token(user).api_key headers = { 'Authorization': 'Bearer {}'.format(token) } fn = getattr(self.app, method.lower()) response = fn( str(path), params=params, headers=headers, status=status) if response.status_int in [301, 302]: return response.follow() else: return response
def test_variable_decode(self): if PY3: raise SkipTest() from formencode.variabledecode import variable_encode obj = dict(a=['1', '2', '3'], b=dict(c=[dict(d='1')])) params = variable_encode(dict(obj=obj), add_repetitions=False) resp = self.app.get('/test_vardec', params=params) assert resp.json['obj'] == obj, (resp.json['obj'], obj)
def test_variable_decode(): from formencode.variabledecode import variable_encode obj = dict( a=['1','2','3'], b=dict(c=[dict(d='1')])) params = variable_encode(dict(obj=obj), add_repetitions=False) resp = app.get('/test_vardec', params=params) assert resp.json['obj'] == obj, (resp.json['obj'], obj)
def dumps(data): dotted_dict = variabledecode.variable_encode(data) # Convert all the keys to utf-8 because urllib can't handle # unicode without puking on non-ascii chars utf8_dict = dict((utf8_encode(k), utf8_encode(v)) for k, v in data.iteritems()) # urllib always creates ASCII, it is its nature return urllib.urlencode(utf8_dict)
def variable_encode_except(formvars, *exclude_vars, **kwargs): formvars_copy = dict(formvars) formvars_keep = dict() for var in exclude_vars: if var in formvars_copy: formvars_keep[var] = formvars_copy.pop(var) encoded = variabledecode.variable_encode(formvars_copy, **kwargs) encoded.update(formvars_keep) return encoded
def __init__(self, method, path, params=None, **kwargs): if params is None: params = {} params = variabledecode.variable_encode(params, add_repetitions=False) params = client.sign_request(path, params) self._method = method.upper() if self._method == 'GET': url = urljoin(client.base_uri, path) + '?' + urlencode(params) data=None else: url = urljoin(client.base_uri, path) data=urlencode(params) urllib2.Request.__init__(self, url, data=data, **kwargs)
def setUp(self): super(TestCustomUserField, self).setUp() params = dict( custom_fields=[ dict(name='_code_review', label='Code Review', type='user', show_in_search='on')], open_status_names='aa bb', closed_status_names='cc', ) self.app.post( '/admin/bugs/set_custom_fields', params=variable_encode(params))
def save2(self): values = dict(request.params) photos_inform=[] for item in values: if item.startswith('product_id'): product_id = item.split('.')[-1] if item.startswith('photo-'): photos_inform.append(int(item.split('-')[-1])) product = Session.query(Product).filter_by(id=product_id).one() action = request.params.getone('action') del values['action'] if action == 'Save': # we need a new schema to be on par with the new Ajax form schema = EditProductForm() try: result = schema.to_python(dict(request.params), c) except Invalid, e: return render_edit2_form( self.menu_items, values=values, id=product.id, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False ), number_of_photos=number_of_photos(values), photos = product.photos ) else: # Move the save photo to photo controller photos = Session.query(Photo).filter(Photo.id.in_(photos_inform)).all() product.code = result['code'] product.name = result['name'] product.description = result['description'] product.quantity= result['quantity'] product.buy_price = result['buy_price'] product.sell_price = result['sell_price'] product.wholesale_price = result['wholesale_price'] product.buy_date = result['buy_date'] product.brand = result['brand'] product.photos = photos product.tags = result['tag'] Session.add(product) Session.commit() h.flash(_('Product edited successfully.')) redirect(url(controller='product',action='admin'))
def get(self): request = self.request user = request.user if not user.cic.SuperUser or not request.dboptions.UseOfflineTools: self._security_failure() edit_info = self._get_edit_info() request.model_state.form.data = variabledecode.variable_encode(edit_info.data) title = _('Manage Offline Machines', request) return self._create_response_namespace(title, title, edit_info._asdict(), no_index=True)
def query(self): """Query action validates the search input values; if valid, query stores the search input values in the session and redirects to results; if invalid, query redirect to search action (though I don't think it's possible to enter an invalid query...). Query is the action referenced by the HTML form rendered by the search action.""" schema = SearchFileForm() values = dict(request.params) try: result = schema.to_python(dict(request.params), c) except Invalid, e: return self.search(values=values, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False))
def resetpassEmailaction(self): values = dict(request.params) user = Session.query(User).filter_by(id=values["userid"]).one() schema = ResetpassEmail() try: resutl = schema.to_python(values, c) except Invalid, e: c.user = user c.confcode = values["confcode"] c.menu_items = h.top_menu(self.menu_items, _("Customers")) html = render("/derived/user/resetpass.html") return htmlfill.render( html, values, errors=variabledecode.variable_encode(e.unpack_errors() or {}, add_repetitions=False) )
def __init__(self, method, path, params=None, **kwargs): if params is None: params = {} params = variabledecode.variable_encode(params, add_repetitions=False) params = client.sign_request(path, params) self._method = method.upper() if self._method == 'GET': url = urljoin(client.base_uri, path) + '?' + urlencode(params) data = None else: url = urljoin(client.base_uri, path) data = urlencode(params) urllib2.Request.__init__(self, url, data=data, **kwargs)
def coerce_vars(self, vars): global variabledecode need_variable_encode = False for key, value in vars.items(): if isinstance(value, dict): need_variable_encode = True if key.endswith('_'): vars[key[:-1]] = vars[key] del vars[key] if need_variable_encode: if variabledecode is None: from formencode import variabledecode vars = variabledecode.variable_encode(vars) return vars
def grades(): dataDict = variable_encode(request.form) try: username = dataDict.get('username') password = dataDict.get('password') cookie = blackboard_authenticate(username, password) if not cookie: return err_json("authenticationFailure", 401) data = get_grades(cookie) # Wrap in a dict to preserve order of grades return my_jsonify({"grades":data}) except Exception, e: return err_json(GENERIC_ERROR)
def contact(): form = ContactForm(request.form) if request.method == "POST": # There are three differente responses: thanks, invalid, and error response = "thanks" # Use variable_encode to get form entries to a normal dict. dataDict = variable_encode(request.form) responseHeaders = request.headers # We use this checkbox state as an inverse state of spam # If this is checked, we assume a bot ignored the markup and # clicked it. # We then ignore the message, but present a false sense of # success. antispam = True if dataDict.has_key("antispam") else False # If "AJAX" variable was passed via POST, this was an ajax request. isAjax = "AJAX" in dataDict.keys() # Get all invalid field entries. invalid = validation.invalid_fields(dataDict) # If we have any invalid entries at on, we respond with an invalid # indicator. Otherwise, attempt to send the email. if invalid: response = "invalid" elif antispam: response == 'thanks' else: response = send_email(dataDict, responseHeaders) # Just return the response if this is AJAX: Do something with the response # with JavaScript instead of rendering the template. if isAjax: return response else: # Get information based on the response. info = render_template("%s.html"%response, invalid=invalid, page_title="Contact Us") # If the response was thanks, clear the form. if response == 'thanks' : form = ContactForm() return render_template("contact_t.html", form=form, info=info, page_title="Contact Us") else: return render_template("contact_t.html", form=form, page_title="Contact Us")
def _admin_update(self,request): identity = request.environ.get('repoze.who.identity') action = request.params.getone('action') values = dict(request.params) invoice_id = int(values['invoice_id']) del values['action'] schema = InvoiceEditAdmin() try: result = schema.to_python(values,c) except Invalid, e: return render_edit_form_admin( self.menu_items, values, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False), id=invoice_id)
def announcements(): dataDict = variable_encode(request.form) try: username = dataDict.get('username') password = dataDict.get('password') cookie = blackboard_authenticate(username, password) if not cookie: return err_json("authenticationFailure", 401) data = get_announcements(cookie) # Wrap in a dict since jsonify doesn't accept pure lists return my_jsonify({"announcements":data}) except Exception, e: return err_json(GENERIC_ERROR)
def myuttyler(): dataDict = variable_encode(request.form) try: username = dataDict.get('username') password = dataDict.get('password') cookie = myuttyler_authenticate(username, password) if not cookie: return err_json("authenticationFailure", 401) data = get_myutt_info(cookie) # Wrap in a dict since jsonify doesn't accept pure lists return my_jsonify({"myuttyler":data}) except Exception, e: return err_json(GENERIC_ERROR)
def search(self): identity = request.environ.get("repoze.who.identity") c.menu_items = h.top_menu(self.menu_items, _("Customers")) c.tags = Session.query(UserTag.tag).all() action = request.params.getone("action") values = dict(request.params) del values["action"] schema = UserSearch() try: result = schema.to_python(values) except Invalid, e: html = render(path.join(get_lang()[0], "/derived/user/staff/index.html")) return htmlfill.render( html, defaults=values, errors=variabledecode.variable_encode(e.unpack_errors() or {}, add_repetitions=False), )
def get(self): request = self.request user = request.user if not user.cic.SuperUser or not request.dboptions.UseOfflineTools: self._security_failure() edit_info = self._get_edit_info() request.model_state.form.data = variabledecode.variable_encode( edit_info.data) title = _("Manage Offline Machines", request) return self._create_response_namespace(title, title, edit_info._asdict(), no_index=True)
def query(self): """Query action validates the search input values; if valid, query stores the search input values in the session and redirects to results; if invalid, query redirect to search action (though I don't think it's possible to enter an invalid query...). Query is the action referenced by the HTML form rendered by the search action.""" schema = SearchFileForm() values = dict(request.params) try: result = schema.to_python(dict(request.params), c) except Invalid, e: return self.search( values=values, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False ) )
def render_control(self, name, **attrs): schema = self.schema field = schema.fields[name] if hasattr(field, 'options'): options = field.options else: options_attr = name + '_options' if hasattr(schema, options_attr): options = getattr(schema, options_attr) assert options # v2l = {v:l for (v,l) in options} v2l = {} for (v,l) in options: v2l[v] = l n2v = variabledecode.variable_encode(v2l.keys(), list_char=self.form.list_char, prepend=name, add_repetitions=False) checkboxes = [] class_ = 'checkbox-inline' if self.inline else 'checkbox' id = self.form_renderer.populate_input_id(name, **attrs) i = 0 checked_values = self._get_checked_values(name) for name, value in n2v.items(): label = v2l[value] check = u' checked="checked"' if value in checked_values else '' checkboxes.append(u""" <div class="%(class)s"> <label> <input type="checkbox" name="%(name)s" value="%(value)s" id="%(id)s"%(check)s> %(label)s </label> </div> """ % { 'id': '%s_%d' % (id, i), 'class': class_, 'name': name, 'value': escape(value), 'label': label, 'check': check, }) i += 1 return u"\n".join(checkboxes)
def test_profile_config(self): # Not fully implemented, just do coverage response = self.app.post('/u/test-admin/profile/update_configuration', params=variable_encode({ 'layout_class': 'something', 'divs': [{ 'name': 'foo', 'content': [{ 'widget': 'lotsa/content' }] }], 'new_div': { 'name': 'bar', 'new_widget': 'widg' } }))
def create(self): """Enter BLD File data into the database. This is the action referenced by the HTML form rendered by the add action. """ dateFormat = session.get('userSettings').get('dateFormat') if dateFormat == 'DD/MM/YYYY': schema = NewFileFormDM() else: schema = NewFileForm() values = dict(request.params) try: result = schema.to_python(dict(request.params), c) except Invalid, e: return renderAddFile(values=values, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False))
def process(self): """Process the OLD XML file to be imported. Processing involves: - saving the file - validating against oldxmlschema.rng - ... """ schema = NewUploadForm() values = dict(request.params) try: result = schema.to_python(dict(request.params), c) except Invalid, e: html = render("/derived/import/upload.html") errors = variabledecode.variable_encode(e.unpack_errors() or {}, add_repetitions=False) return htmlfill.render(html, defaults=values, errors=errors)
def create(self): action = request.params.getone("action") values = dict(request.params) # Don't use the values field for repopulation del values["action"] res = self._proccess_form(action, values, postto="create", renderer=render_form) if res is not False: return res schema = NewUserForm() try: result = schema.to_python(values, c) except Invalid, e: return render_form( self.menu_items, values, action="create", errors=variabledecode.variable_encode(e.unpack_errors() or {}, add_repetitions=False), )
def _api_getpost(self, method, path, api_key=None, api_timestamp=None, api_signature=None, wrap_args=None, **params): if wrap_args: params = {wrap_args: params} params = variabledecode.variable_encode(params, add_repetitions=False) if api_key: params['api_key'] = api_key if api_timestamp: params['api_timestamp'] = api_timestamp if api_signature: params['api_signature'] = api_signature params = self.token.sign_request(path, params) fn = self.app.post if method=='POST' else self.app.get response = fn( str(path), params=params, status=[200, 302, 400, 403, 404]) if response.status_int == 302: return response.follow() else: return response
def link(self, id): """Associate BLD File with id=id to a BLD Form. The ID of the Form is passed via a POST form. This "ID" may in fact be a comma-separated list of Form IDs. """ schema = AssociateFileFormForm() values = dict(request.params) try: result = schema.to_python(dict(request.params), c) except Invalid, e: c.file = meta.Session.query(model.File).filter_by(id=id).first() associateForm = render('/derived/file/associateForm.html') errors = variabledecode.variable_encode(e.unpack_errors() or {}, add_repetitions=False) c.associateForm = htmlfill.render(associateForm, defaults=values, errors=errors) return render('/derived/file/associate.html')
def test_custom_fields(self): params = dict( custom_fields=[ dict(name='_priority', label='Priority', type='select', options='normal urgent critical'), dict(name='_category', label='Category', type='string', options=''), dict(name='_code_review', label='Code Review', type='user')], open_status_names='aa bb', closed_status_names='cc', ) self.app.post( '/admin/bugs/set_custom_fields', params=variable_encode(params)) kw = {'custom_fields._priority':'normal', 'custom_fields._category':'helloworld', 'custom_fields._code_review':'test-admin'} ticket_view = self.new_ticket(summary='test custom fields', **kw).follow() assert 'Priority:' in ticket_view assert 'normal' in ticket_view assert 'Test Admin' in ticket_view
def _setUp(self): self.app.get('/wiki/') self.app.get('/bugs/') self.app.post( '/bugs/save_ticket', params=variable_encode( dict(ticket_form=dict(ticket_num='', labels='', assigned_to='', milestone='', summary='This is a ticket', status='open', description='This is a description'))), status=302) title = u'Descri\xe7\xe3o e Arquitetura'.encode('utf-8') self.app.post('/wiki/%s/update' % title, params=dict(title=title, text="Nothing much", labels='', labels_old=''), status=302) self.app.get('/wiki/%s/' % title)
def save(self): """Save the changed application settings. This action both saves the application settings to the model and updates app_globals with the application settings info. """ c.colorsCSSOptions = os.listdir( os.path.join(config['pylons.paths']['root'], 'public', 'css', 'colors')) schema = AlterSettingsForm() values = dict(request.params) try: self.form_result = schema.to_python(dict(request.params), c) except Invalid, e: return renderEditSettings(values=values, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False)) return render('/derived/settings/index.html')
def contact(): form = ContactForm(request.form) if request.method == "POST": # There are three differente responses: thanks, invalid, and error response = "thanks" # Use variable_encode to get form entries to a normal dict. dataDict = variable_encode(request.form) # If "AJAX" variable was passed via POST, this was an ajax request. isAjax = "AJAX" in dataDict.keys() # Get all invalid field entries. invalid = validation.invalid_fields(dataDict) # If we have any invalid entries at on, we respond with an invalid # indicator. Otherwise, attempt to send the email. if invalid: response = "invalid" else: response = send_email(dataDict) # Just return the response if this is AJAX: Do something with the response # with JavaScript instead of rendering the template. if isAjax: return response else: # Get information based on the response. info = render_template("form_response/%s.html" % response, invalid=invalid) # If the response was thanks, clear the form. if response == 'thanks': form = ContactForm() return render_template("contact.html", form=form, info=info) else: return render_template("contact.html", form=form, title="Contact Us")
def test_import_custom_field(self): params = dict( custom_fields=[ dict(name='_resolution', label='Resolution', type='select', options='oné "one and á half" two'), ], open_status_names='aa bb', closed_status_names='cc', ) self.app.post('/admin/bugs/set_custom_fields', params=variable_encode(params)) here_dir = os.path.dirname(__file__) api_ticket = M.ApiTicket(user_id=c.user._id, capabilities={'import': ['Projects', 'test']}, expires=datetime.utcnow() + timedelta(days=1)) ming.orm.session(api_ticket).flush() self.set_api_token(api_ticket) doc_text = open(here_dir + '/data/sf.json').read() doc_json = json.loads(doc_text) ticket_json = doc_json['trackers']['default']['artifacts'][0] r = self.api_post( '/rest/p/test/bugs/perform_import', doc=doc_text, options= '{"user_map": {"hinojosa4": "test-admin", "ma_boehm": "test-user"}}' ) assert r.json['status'], r.json ming.orm.ThreadLocalORMSession.flush_all() M.MonQTask.run_ready() ming.orm.ThreadLocalORMSession.flush_all() r = self.app.get('/p/test/bugs/204/') assert '<option selected value="fixed">fixed</option>' in r assert '<option value="one and á half">one and á half</option>' in r
def process(self): """Process the OLD XML file to be imported. Processing involves: - saving the file - validating against oldxmlschema.rng - ... """ schema = NewUploadForm() values = dict(request.params) try: result = schema.to_python(dict(request.params), c) except Invalid, e: html = render('/derived/import/upload.html') errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False ) return htmlfill.render(html, defaults=values, errors=errors)
def test_custom_field_update_comments(self): params = dict( custom_fields=[ dict(label='Number', type='number', options='')], open_status_names='aa bb', closed_status_names='cc', ) r = self.app.post('/admin/bugs/set_custom_fields', params=variable_encode(params)) kw = {'custom_fields._number':''} ticket_view = self.new_ticket(summary='test custom fields', **kw).follow() assert '<strong>number</strong>: -->' not in ticket_view ticket_view = self.app.post('/bugs/1/update_ticket',params={ 'summary':'zzz', 'description':'bbb', 'status':'ccc', '_milestone':'aaa', 'assigned_to':'', 'labels':'', 'labels_old':'', 'custom_fields._number':'', 'comment': '' }).follow() assert '<strong>number</strong>: -->' not in ticket_view ticket_view = self.app.post('/bugs/1/update_ticket',params={ 'summary':'zzz', 'description':'bbb', 'status':'ccc', '_milestone':'aaa', 'assigned_to':'', 'labels':'', 'labels_old':'', 'custom_fields._number':'4', 'comment': '' }).follow() assert '<strong>number</strong>: -->' in ticket_view
def decorated(func, *args, **kw): def kwpop(name, default=None): return kw.pop(var_name + '_tgp_' + name, kw.pop('tg_paginate_' + name, default)) page = kwpop('no') if page is None: page = 1 elif page == 'last': page = None else: try: page = int(page) if page < 1: raise ValueError except (TypeError, ValueError): page = 1 if get('paginate.redirect_on_out_of_range'): cherrypy.request.params[var_name + '_tgp_no'] = page redirect(cherrypy.request.path_info, cherrypy.request.params) try: limit_ = int(kwpop('limit')) if max_limit is not None and not (allow_limit_override and max_limit == 0): if max_limit <= 0: raise ValueError limit_ = min(limit_, max_limit) except (TypeError, ValueError): limit_ = limit order = kwpop('order') ordering = kwpop('ordering') log.debug("paginate params: page=%s, limit=%s, order=%s", page, limit_, order) # get the output from the decorated function output = func(*args, **kw) if not isinstance(output, dict): return output try: var_data = output[var_name] except KeyError: raise KeyError("paginate: var_name" " (%s) not found in output dict" % var_name) if not hasattr(var_data, '__getitem__') and callable(var_data): # e.g. SQLAlchemy query class var_data = var_data() if not hasattr(var_data, '__getitem__'): raise TypeError('Paginate variable is not a sequence') if dynamic_limit: try: dyn_limit = output[dynamic_limit] except KeyError: raise KeyError("paginate: dynamic_limit" " (%s) not found in output dict" % dynamic_limit) limit_ = dyn_limit if ordering: ordering = str(ordering).split(',') else: ordering = default_order or [] if isinstance(ordering, basestring): # adapt old style default_order to new style if default_reversed: ordering = "-" + ordering ordering = [ordering] elif default_reversed: raise ValueError( "paginate: default_reversed (deprecated)" " only allowed when default_order is a basestring") if order: order = str(order) log.debug('paginate: ordering was %s, sort is %s', ordering, order) sort_ordering(ordering, order) log.debug('paginate: ordering is %s', ordering) try: row_count = len(var_data) except TypeError: try: # SQL query row_count = var_data.count() or 0 except AttributeError: # other iterator var_data = list(var_data) row_count = len(var_data) if ordering: var_data = sort_data( var_data, ordering, max_sort is None or 0 < row_count <= max_sort) # If limit is zero then return all our rows if not limit_: limit_ = row_count or 1 page_count = int(ceil(float(row_count) / limit_)) if page is None: page = max(page_count, 1) if get('paginate.redirect_on_last_page'): cherrypy.request.params[var_name + '_tgp_no'] = page redirect(cherrypy.request.path_info, cherrypy.request.params) elif page > page_count: page = max(page_count, 1) if get('paginate.redirect_on_out_of_range'): cherrypy.request.params[var_name + '_tgp_no'] = page redirect(cherrypy.request.path_info, cherrypy.request.params) offset = (page - 1) * limit_ pages_to_show = _select_pages_to_show(page, page_count, max_pages) # remove pagination parameters from request input_values = variable_encode(cherrypy.request.params.copy()) input_values.pop('self', None) for input_key in input_values.keys(): if (input_key.startswith(var_name + '_tgp_') or input_key.startswith('tg_paginate_')): del input_values[input_key] paginate_instance = Paginate(current_page=page, limit=limit_, pages=pages_to_show, page_count=page_count, input_values=input_values, order=order, ordering=ordering, row_count=row_count, var_name=var_name) cherrypy.request.paginate = paginate_instance if not hasattr(cherrypy.request, 'paginates'): cherrypy.request.paginates = dict() cherrypy.request.paginates[var_name] = paginate_instance # we replace the var with the sliced one endpoint = offset + limit_ log.debug("paginate: slicing data between %d and %d", offset, endpoint) global _simulate_offset if _simulate_offset is None: _simulate_offset = get('paginate.simulate_offset', None) if _simulate_offset is None: _simulate_offset = False so_db = get('sqlobject.dburi', 'NOMATCH:').split(':', 1)[0] sa_db = get('sqlalchemy.dburi', 'NOMATCH:').split(':', 1)[0] if so_db in _so_no_offset or sa_db in _sa_no_offset: _simulate_offset = True log.warning( "paginate: simulating OFFSET," " paginate may be slow" " (disable with paginate.simulate_offset=False)") if _simulate_offset: var_data = iter(var_data[:endpoint]) # skip over the number of records specified by offset for i in xrange(offset): var_data.next() # return the records that remain output[var_name] = list(var_data) else: try: output[var_name] = var_data[offset:endpoint] except TypeError: for i in xrange(offset): var_data.next() output[var_name] = [ var_data.next() for i in xrange(offset, endpoint) ] return output
def _post(self, params, **kw): params['open_status_names'] = 'aa bb' params['closed_status_names'] = 'cc' self.app.post('/admin/bugs/set_custom_fields', params=variable_encode(params), **kw) return self.app.get('/admin/bugs/fields')
#!/usr/bin/env python """ Add merchant settings as encryped env vars to .travis.yml """ import os from django.core.management import setup_environ from example.settings import local setup_environ(local) from django.conf import settings from formencode.variabledecode import variable_encode env_dict = variable_encode(settings.MERCHANT_SETTINGS, prepend='MERCHANT', dict_char='__') for k, v in env_dict.iteritems(): print 'adding %s' % (k) os.system('travis encrypt %s="%s" --add env.global' % (k, v))
def test_dict_encode(self): src = {'a': {'a': 'a', 'b': 'b', 'c': 'c'}} expect = {'a.a': 'a', 'a.b': 'b', 'a.c': 'c'} self.assertEqual(expect, variable_encode(src))
def test_list_encode_non_int(self): src = {'a': ['a', 'c'], 'a-a': 'b'} expect = {'a--repetitions': '2', 'a-0': 'a', 'a-a': 'b', 'a-1': 'c'} self.assertEqual(expect, variable_encode(src))
def test_list_encode(self): src = {'a': ['a', 'b', 'c']} expect = {'a--repetitions': '3', 'a-0': 'a', 'a-1': 'b', 'a-2': 'c'} self.assertEqual(expect, variable_encode(src))