def _w(*args, **kwargs): page = int(kwargs.pop(own_parameters["page"], 1)) real_items_per_page = int( kwargs.pop(own_parameters['items_per_page'], items_per_page)) # Iterate over all of the named arguments expected by the function f # if any of those arguments have values present in the kwargs dict, # add the value to the positional args list, and remove it from the # kwargs dict argvars = inspect.getargspec(f)[0][1:] if argvars: args = list(args) for i, var in enumerate(args): if i >= len(argvars): break var = argvars[i] if var in kwargs: if i + 1 >= len(args): args.append(kwargs[var]) else: args[i + 1] = kwargs[var] del kwargs[var] res = f(*args, **kwargs) if isinstance(res, dict) and name in res: additional_parameters = MultiDict() for key, value in request.params.iteritems(): if key not in own_parameters: additional_parameters.add(key, value) collection = res[name] # Use CustomPage if our extra custom arg was provided if items_first_page is not None: page_class = CustomPage else: page_class = Page page = page_class(collection, page, items_per_page=real_items_per_page, items_first_page=items_first_page, **additional_parameters.dict_of_lists()) # wrap the pager so that it will render # the proper page-parameter page.pager = partial(page.pager, page_param=own_parameters["page"]) res[name] = page # this is a bit strange - it appears # as if c returns an empty # string for everything it dosen't know. # I didn't find that documented, so I # just put this in here and hope it works. if not hasattr(tmpl_context, 'paginators') or type( tmpl_context.paginators) == str: tmpl_context.paginators = Bunch() tmpl_context.paginators[name] = page return res
def _w(*args, **kwargs): page = int(kwargs.pop(own_parameters["page"], 1)) real_items_per_page = int(kwargs.pop(own_parameters["items_per_page"], items_per_page)) # Iterate over all of the named arguments expected by the function f # if any of those arguments have values present in the kwargs dict, # add the value to the positional args list, and remove it from the # kwargs dict argvars = inspect.getargspec(f)[0][1:] if argvars: args = list(args) for i, var in enumerate(args): if i >= len(argvars): break var = argvars[i] if var in kwargs: if i + 1 >= len(args): args.append(kwargs[var]) else: args[i + 1] = kwargs[var] del kwargs[var] res = f(*args, **kwargs) if isinstance(res, dict) and name in res: additional_parameters = MultiDict() for key, value in request.params.iteritems(): if key not in own_parameters: additional_parameters.add(key, value) collection = res[name] # Use CustomPage if our extra custom arg was provided if items_first_page is not None: page_class = CustomPage else: page_class = Page page = page_class( collection, page, items_per_page=real_items_per_page, items_first_page=items_first_page, **additional_parameters.dict_of_lists() ) # wrap the pager so that it will render # the proper page-parameter page.pager = partial(page.pager, page_param=own_parameters["page"]) res[name] = page # this is a bit strange - it appears # as if c returns an empty # string for everything it dosen't know. # I didn't find that documented, so I # just put this in here and hope it works. if not hasattr(tmpl_context, "paginators") or type(tmpl_context.paginators) == str: tmpl_context.paginators = Bunch() tmpl_context.paginators[name] = page return res
def test_multidict(): d = MultiDict(a=1, b=2) assert d['a'] == 1 assert d.getall('c') == [] d.add('a', 2) assert d['a'] == 2 assert d.getall('a') == [1, 2] d['b'] = 4 assert d.getall('b') == [4] assert list(d.keys()) == ['a', 'a', 'b'] assert list(d.items()) == [('a', 1), ('a', 2), ('b', 4)] assert d.mixed() == {'a': [1, 2], 'b': 4} # test getone # KeyError: "Multiple values match 'a': [1, 2]" with pytest.raises(KeyError): d.getone('a') assert d.getone('b') == 4 # KeyError: "Key not found: 'g'" with pytest.raises(KeyError): d.getone('g') assert d.dict_of_lists() == {'a': [1, 2], 'b': [4]} assert 'b' in d assert 'e' not in d d.clear() assert 'b' not in d d['a'] = 4 d.add('a', 5) e = d.copy() assert 'a' in e e.clear() e['f'] = 42 d.update(e) assert d == MultiDict([('a', 4), ('a', 5), ('f', 42)]) f = d.pop('a') assert f == 4 assert d['a'] == 5 assert d.pop('g', 42) == 42 with pytest.raises(KeyError): d.pop('n') # TypeError: pop expected at most 2 arguments, got 3 with pytest.raises(TypeError): d.pop(4, 2, 3) d.setdefault('g', []).append(4) assert d == MultiDict([('a', 5), ('f', 42), ('g', [4])])
def test_multidict(): d = MultiDict(a=1, b=2) eq(d['a'], 1) eq(d.getall('c'), []) d.add('a', 2) eq(d['a'], 2) eq(d.getall('a'), [1, 2]) d['b'] = 4 eq(d.getall('b'), [4]) eq(list(d.keys()), ['a', 'a', 'b']) eq(list(d.items()), [('a', 1), ('a', 2), ('b', 4)]) eq(d.mixed(), {'a': [1, 2], 'b': 4}) # test getone # KeyError: "Multiple values match 'a': [1, 2]" assert_raises(KeyError, d.getone, 'a') eq(d.getone('b'), 4) # KeyError: "Key not found: 'g'" assert_raises(KeyError, d.getone, 'g') eq(d.dict_of_lists(), {'a': [1, 2], 'b': [4]}) assert 'b' in d assert 'e' not in d d.clear() assert 'b' not in d d['a'] = 4 d.add('a', 5) e = d.copy() assert 'a' in e e.clear() e['f'] = 42 d.update(e) eq(d, MultiDict([('a', 4), ('a', 5), ('f', 42)])) f = d.pop('a') eq(f, 4) eq(d['a'], 5) eq(d.pop('g', 42), 42) assert_raises(KeyError, d.pop, 'n') # TypeError: pop expected at most 2 arguments, got 3 assert_raises(TypeError, d.pop, 4, 2, 3) d.setdefault('g', []).append(4) eq(d, MultiDict([('a', 5), ('f', 42), ('g', [4])]))
class Request(object): headers = {'content-type':'text/html'} def __init__(self, form_name='form', POST=None, GET=None, method='POST'): # Build GET and POST data self.GET = MultiDict(GET or {}) self.POST = MultiDict(POST or {}) # Add the form's name to the appropriate request data dict. getattr(self, method.upper())['__formish_form__'] = form_name # Set the method self.method = method def get_post(self): def container_factory(parent_key, item_key): if item_key.isdigit(): return [] return {} return unflatten(self.POST.dict_of_lists().iteritems(), container_factory=container_factory)
class Request(object): headers = {'content-type': 'text/html'} def __init__(self, form_name='form', POST=None, GET=None, method='POST'): # Build GET and POST data self.GET = MultiDict(GET or {}) self.POST = MultiDict(POST or {}) # Add the form's name to the appropriate request data dict. getattr(self, method.upper())['__formish_form__'] = form_name # Set the method self.method = method def get_post(self): def container_factory(parent_key, item_key): if item_key.isdigit(): return [] return {} return unflatten(self.POST.dict_of_lists().iteritems(), container_factory=container_factory)
def _w(*args, **kwargs): page = int(kwargs.pop(own_parameters["page"], 1)) real_items_per_page = int( kwargs.pop(own_parameters['items_per_page'], items_per_page)) argvars = inspect.getargspec(f)[0][1:] if argvars: args = list(args) for i, var in enumerate(args): if i >= len(argvars): break var = argvars[i] if var in kwargs: args[i] = kwargs[var] del kwargs[var] res = f(*args, **kwargs) if isinstance(res, dict) and name in res: additional_parameters = MultiDict() for key, value in request.str_params.iteritems(): if key not in own_parameters: additional_parameters.add(key, value) collection = res[name] page = Page(collection, page, items_per_page=real_items_per_page, **additional_parameters.dict_of_lists()) # wrap the pager so that it will render # the proper page-parameter page.pager = partial(page.pager, page_param=own_parameters["page"]) res[name] = page # this is a bit strange - it appears # as if c returns an empty # string for everything it dosen't know. # I didn't find that documented, so I # just put this in here and hope it works. if not hasattr(c, 'paginators') or type(c.paginators) == str: c.paginators = Bunch() c.paginators[name] = page return res
def panel_object(request): # задаём базовые переменные slug = request.matchdict['slug'] otype = request.matchdict['type'] types = { 'mes': Message, 'frst': FirstLevel, 'scnd': SecondLevel, 'offrs': Offer, } new_message = { 'mes': 'Create new Message', 'frst': 'Create new First Level Category', 'scnd': 'Create new Second Level Category', 'offrs': 'Create new Offer', } edit_message = { 'mes': 'Edit Message', 'frst': 'Edit First Level Category', 'scnd': 'Edit Second Level Category', 'offrs': 'Edit Offer', } model = types[otype] if slug == 'new': message = new_message[otype] if otype == 'mes': form = MessageFields(request.POST) elif otype == 'frst': form = standartFields(request.POST) elif otype == 'scnd': form = SecondLevelFields(request.POST) #получаем список категорий 1 уровня #message = request.dbsession.query(FirstLevel).all() try: form.parent.choices = [ (c.cmd, c.name) for c in request.dbsession.query(FirstLevel).all() ] except: form.parent.choices = [('none', 'None')] elif otype == 'offrs': form = OfferFields(request.POST) #получаем список категорий 2 уровня try: form.parent.choices = [ (c.cmd, c.name) for c in request.dbsession.query(SecondLevel).all() ] except: form.parent.choices = [('none', 'None')] #попытка записи в БД if request.method == 'POST' and form.validate(): #проверка на уникальность if request.dbsession.query(model).filter_by( cmd=request.params['cmd']).one_or_none(): form.cmd.errors.append('Cmd is not unique') return dict(view_name=message, form=form, slug=slug, otype=otype) inst = model() #начинаем писать в БД try: #общие параметры для всех inst.cmd = request.params['cmd'] inst.text = request.params['text'] except: form.cmd.errors.append('You cant add this command') return dict(view_name=message, form=form, slug=slug, otype=otype) if otype == 'frst': #Если пишем первый уровень - добавляем параметр Имя inst.name = request.params['name'] elif otype == 'scnd': #Если пишем 2 уровень - добавляем ещё параметры inst.name = request.params['name'] if request.params['parent']: try: inst.f_lvl = request.dbsession.query(FirstLevel).get( request.params['parent']) except: form.parent.errors.append('Append Error') return dict(view_name=message, form=form, slug=slug, otype=otype) elif otype == 'offrs': inst.name = request.params['name'] inst.link = request.params['link'] inst.image = request.params['image'] try: if request.params['active']: inst.active = True except: inst.active = False try: inst.date_expired = request.params['date_expired'] except: form.date_expired.errors.append( 'incorrect date format:_' + request.params['date_expired']) try: if request.params['parent']: params = md.dict_of_lists(request.POST) inst.s_lvl.clear() for p in params['parent']: inst.s_lvl.append( request.dbsession.query(SecondLevel).get(p)) except: form.parent.errors.append('Append Error') return dict(view_name=message, form=form, slug=slug, otype=otype) request.dbsession.add(inst) return HTTPFound( location=request.route_url('panel_list', type=otype)) return dict(view_name=message, form=form, slug=slug, otype=otype) else: ############################## ### редактирование Объекта ### ############################## message = edit_message[otype] #TODO Здесь может быть не соотв ссылок и первичных ключей entry = request.dbsession.query(model).get(slug) if not entry: raise HTTPNotFound() #создаем формы для каждого объекта if otype == 'mes': form = MessageFields(request.POST, entry) elif otype == 'frst': form = standartFields(request.POST, entry) elif otype == 'scnd': form = SecondLevelFields(request.POST, entry) try: #создаем список возможных связей c первым уровнем: form.parent.choices = [ (c.cmd, c.name) for c in request.dbsession.query(FirstLevel).all() ] #отмечаем выбранные form.parent.data = entry.f_lvl.cmd except: form.parent.choices = [('none', 'None')] elif otype == 'offrs': form = OfferFields(request.POST, entry) try: #получаем список категорий 2 уровня form.parent.choices = [ (c.cmd, c.name) for c in request.dbsession.query(SecondLevel).all() ] #отмечаем выбранные form.parent.data = [e.cmd for e in entry.s_lvl] except: form.parent.choices = [('none', 'None')] ### запись в БД ### if request.method == 'POST' and form.validate(): try: entry.cmd = request.params['cmd'] entry.text = request.params['text'] except: form.cmd.errors.append('You cant add this command') return dict(view_name=message, form=form, slug=slug, otype=otype) if otype == 'frst': #Если пишем первый уровень - добавляем параметр Имя entry.name = request.params['name'] elif otype == 'scnd': #Если пишем 2 уровень - добавляем ещё параметры entry.name = request.params['name'] if request.params['parent']: try: entry.f_lvl = request.dbsession.query(FirstLevel).get( request.params['parent']) except: form.parent.errors.append('Append Error') return dict(view_name=message, form=form, slug=slug, otype=otype) elif otype == 'offrs': entry.name = request.params['name'] entry.link = request.params['link'] entry.image = request.params['image'] try: if request.params['active']: entry.active = True except: entry.active = False try: entry.date_expired = request.params['date_expired'] except: form.date_expired.errors.append( 'incorrect date format:_' + request.params['date_expired']) try: if request.params['parent']: params = md.dict_of_lists(request.POST) entry.s_lvl.clear() for p in params['parent']: entry.s_lvl.append( request.dbsession.query(SecondLevel).get(p)) except: form.parent.errors.append('Append Error') return dict(view_name=message, form=form, slug=slug, otype=otype) return HTTPFound( location=request.route_url('panel_list', type=otype)) return dict(view_name=message, form=form, slug=slug, otype=otype)