def processInput(self, ctx, key, args): namer = self._namer(key) type = args.get(namer('type'), [''])[0].decode(util.getPOSTCharset(ctx)) content = args.get(namer('content'), [''])[0].decode(util.getPOSTCharset(ctx)) value = IFormalRichTextConvertible(self.original).toType(RichTextData(type, content)) return self.original.validate(value)
def process(self, ctx): request = inevow.IRequest(ctx) charset = getPOSTCharset(ctx) # Get the request args and decode the arg names args = dict([(k.decode(charset),v) for k,v in request.args.items()]) # Find the callback to use, defaulting to the form default callback, validate = self.callback, True if self.actions is not None: for action in self.actions: if action.name in args: # Remove it from the data args.pop(action.name) # Remember the callback and whether to validate callback, validate = action.callback, action.validate break # IE does not send a button name in the POST args for forms containing # a single field when the user presses <enter> to submit the form. If # we only have one possible action then we can safely assume that's the # action to take. # # If there are 0 or 2+ actions then we can't assume anything because we # have no idea what order the buttons are on the page (someone might # have altered the DOM using JavaScript for instance). In that case # throw an error and make it a problem for the developer. if callback is None: if self.actions is None or len(self.actions) != 1: raise Exception('The form has no callback and no action was found.') else: callback, validate = self.actions[0].callback, \ self.actions[0].validate # Remember the args in case validation fails. self.errors.data = args def _cbProcessingDone(_): if self.errors and validate: return self.errors def _clearUpResources( r ): if not self.errors: self.resourceManager.clearUpResources() return r d = defer.maybeDeferred(callback, ctx, self, self.data) d.addCallback( _clearUpResources ) d.addErrback(self._cbFormProcessingFailed, ctx) return d # Iterate the items and collect the form data and/or errors. dl = [] for item in self.items: dl.append(defer.maybeDeferred(item.process, ctx, self, args, self.errors)) d = defer.gatherResults(dl) d.addCallback(_cbProcessingDone) return d
def process(self, context, boundTo, data): """data is a list of strings at this point """ typed = self.original val = data[0] if typed.unicode: try: val = val.decode(getPOSTCharset(context), "replace") except LookupError: val = val.decode("utf-8", "replace") if typed.strip: val = val.strip() if val == "" or val is None: if typed.required: raise formless.InputError(typed.requiredFailMessage) else: return typed.null try: return typed.coerce(val, boundTo) except TypeError, e: warnings.warn( "Typed.coerce takes two values now, the value to coerce and the configurable in whose context the coerce is taking place. %s %s" % (typed.__class__, typed) ) return typed.coerce(val)
def processInput(self, ctx, key, args): fileitem = inevow.IRequest(ctx).fields[key] name = fileitem.filename.decode(util.getPOSTCharset(ctx)) value = (name, fileitem.file) value = iformal.IFileConvertible(self.original).fromType(value) return self.original.validate(value)
def processInput(self, ctx, key, args): """ Process the request, storing any uploaded file in the resource manager. """ resourceManager = iformal.IForm( ctx ).resourceManager # Ping the resource manager with any resource ids that I know self._registerWithResourceManager( key, args, resourceManager ) fileitem = inevow.IRequest(ctx).fields[key] name = fileitem.filename.decode(util.getPOSTCharset(ctx)) if name: # Store the uploaded file in the resource manager resourceManager.setResource( key, fileitem.file, name ) # Validating against an uploaded file. Should the fact that there is # original file meet a required field validation? value = resourceManager.getResourceForWidget( key ) value = self.convertibleFactory(self.original).toType( value ) # check to see if we should remove this if self.removeable is True: remove = args.get('%s_remove'%key, [None])[0] if remove is not None: value = (None,None,None) return self.original.validate( value )
def process(self, context, boundTo, data): """Password needs to look at two passwords in the data, """ typed = self.original pw1 = data[0] args = context.locate(inevow.IRequest).args binding = context.locate(iformless.IBinding) pw2 = args.get("%s____2" % binding.name, [''])[0] if typed.strip: pw1 = pw1.strip() pw2 = pw2.strip() if pw1 != pw2: raise formless.InputError("Passwords do not match. Please reenter.") elif pw1 == '': if typed.required: raise formless.InputError(typed.requiredFailMessage) else: return typed.null val = data[0] if typed.unicode: try: val = val.decode(getPOSTCharset(context), 'replace') except LookupError: val = val.decode('utf-8', 'replace') try: return typed.coerce(val, boundTo) except TypeError: warnings.warn('Typed.coerce takes two values now, the value to coerce and the configurable in whose context the coerce is taking place. %s %s' % (typed.__class__, typed)) return typed.coerce(data[0])
def processInput(self, ctx, key, args): charset = util.getPOSTCharset(ctx) value = self._valueFromRequestArgs(charset, key, args) value = iformal.IStringConvertible(self.original).toType(value) if self.noneOption is not None and value == iformal.IKey(self.noneOption).key(): value = None return self.original.validate(value)
def _render(self, ctx, key, args, errors, immutable): charset = util.getPOSTCharset(ctx) converter = iformal.IStringConvertible(self.original) if errors: value = self._valueFromRequestArgs(charset, key, args) else: value = converter.fromType(args.get(key)) if value is None: value = iformal.IKey(self.noneOption).key() if immutable: template = inevow.IQ(self.template).onePattern('immutable') else: template = inevow.IQ(self.template).onePattern('editable') optionGen = template.patternGenerator('option') selectedOptionGen = template.patternGenerator('selectedOption') optionTags = [] selectOther = True if self.noneOption is not None: noneValue = iformal.IKey(self.noneOption).key() if value == noneValue: tag = selectedOptionGen() selectOther = False else: tag = optionGen() tag.fillSlots('value', noneValue) tag.fillSlots('label', iformal.ILabel(self.noneOption).label()) optionTags.append(tag) if self.options is not None: for item in self.options: if value == item: tag = selectedOptionGen() selectOther = False else: tag = optionGen() tag.fillSlots('value', item) tag.fillSlots('label', item) optionTags.append(tag) if selectOther: tag = selectedOptionGen() otherValue = value else: tag = optionGen() otherValue = '' tag.fillSlots('value', self.otherOption[0]) tag.fillSlots('label', self.otherOption[1]) optionTags.append(tag) tag = template tag.fillSlots('key', key) tag.fillSlots('id', render_cssid(key)) tag.fillSlots('options', optionTags) tag.fillSlots('otherValue', otherValue) return tag
def processInput(self, ctx, key, args): charset = util.getPOSTCharset(ctx) value = args.get(key, [''])[0].decode(charset) value = iformal.IStringConvertible(self.original).toType(value) if self.noneOption is not None and \ value == iformal.IKey(self.noneOption).key(): value = None return self.original.validate(value)
def processInput(self, ctx, key, args): values = args.get(key, [""]) decodedValues = [] for value in values: value = value.decode(nevowutil.getPOSTCharset(ctx)) decodedValues.append(value) decodedValues = iformal.ISequenceConvertible(self.original).toType(decodedValues) return self.original.validate(decodedValues)
def process(self, ctx): # Get the request args requestArgs = inevow.IRequest(ctx).args # Decode the request arg names charset = getPOSTCharset(ctx) args = dict([(k.decode(charset),v) for k,v in requestArgs.iteritems()]) # Find the callback to use, defaulting to the form default callback, validate = self.callback, True if self.actions is not None: for action in self.actions: if action.name in args: # Remove it from the data args.pop(action.name) # Remember the callback and whether to validate callback, validate = action.callback, action.validate break # IE does not send a button name in the POST args for forms containing # a single field when the user presses <enter> to submit the form. If # we only have one possible action then we can safely assume that's the # action to take. # # If there are 0 or 2+ actions then we can't assume anything because we # have no idea what order the buttons are on the page (someone might # have altered the DOM using JavaScript for instance). In that case # throw an error and make it a problem for the developer. if callback is None: if self.actions is None or len(self.actions) != 1: raise Exception('The form has no callback and no action was found.') else: callback, validate = self.actions[0].callback, \ self.actions[0].validate # Store an errors object in the context errors = FormErrors(self.name) errors.data = args ctx.remember(errors, iformal.IFormErrors) # Iterate the items and collect the form data and/or errors. for item in self.items: item.process(ctx, self, args, errors) if errors and validate: return errors def _clearUpResources( r ): if not errors: self.resourceManager.clearUpResources() return r d = defer.maybeDeferred(callback, ctx, self, self.data) d.addCallback( _clearUpResources ) d.addErrback(self._cbFormProcessingFailed, ctx) return d
def processInput(self, ctx, key, args, default=None): # default is ignored here namer = self._namer(key) value = [ args.get(namer(part), [''])[0].strip().decode(util.getPOSTCharset(ctx)) for part in ('tparser', 'tvalue') ] return self.original.validate(types.RichText(*value))
def render(self, ctx, key, args, errors): charset = util.getPOSTCharset(ctx) converter = iformal.IStringConvertible(self.original) if errors: value = self._valueFromRequestArgs(charset, key, args) else: value = converter.fromType(args.get(key)) if value is None: value = iformal.IKey(self.noneOption).key() optionGen = inevow.IQ(self.template).patternGenerator('option') selectedOptionGen = inevow.IQ(self.template).patternGenerator('selectedOption') optionTags = [] selectOther = True if self.noneOption is not None: noneValue = iformal.IKey(self.noneOption).key() if value == noneValue: tag = selectedOptionGen() selectOther = False else: tag = optionGen() tag.fillSlots('value', noneValue) tag.fillSlots('label', iformal.ILabel(self.noneOption).label()) optionTags.append(tag) if self.options is not None: for item in self.options: if value == item: tag = selectedOptionGen() selectOther = False else: tag = optionGen() tag.fillSlots('value', item) tag.fillSlots('label', item) optionTags.append(tag) if selectOther: tag = selectedOptionGen() otherValue = value else: tag = optionGen() otherValue = '' tag.fillSlots('value', self.otherOption[0]) tag.fillSlots('label', self.otherOption[1]) optionTags.append(tag) tag = T.invisible[self.template.load(ctx)] tag.fillSlots('key', key) tag.fillSlots('id', render_cssid(key)) tag.fillSlots('options', optionTags) tag.fillSlots('otherValue', otherValue) return tag
def processInput(self, ctx, key, args): # Get the whole string value = args.get(key, [''])[0].decode(util.getPOSTCharset(ctx)) # Split into lines, discarding empty lines values = [line for line in value.splitlines() if line.strip()] # Convert values to correct type converter = iformal.IStringConvertible(self.original.type) values = [converter.toType(v) for v in values] # Validate and return return self.original.validate(values)
def processInput(self, ctx, key, args): namer = self._namer(key) values = [] for i in range(self.count): value = args.get(namer(i), [''])[0] value = value.decode(nevowutil.getPOSTCharset(ctx)) values.append( value ) values = iformal.ISequenceConvertible(self.original).toType(values) return self.original.validate( values )
def processInput(self, ctx, key, args): charset = util.getPOSTCharset(ctx) pwds = [pwd.decode(charset) for pwd in args.get(key, [])] if len(pwds) == 0: pwd = '' elif len(pwds) == 1: raise validation.FieldValidationError('Please enter the password twice for confirmation.') else: if pwds[0] != pwds[1]: raise validation.FieldValidationError('Passwords do not match.') return self.original.validate(pwds[0])
def processInput(self, ctx, key, args): fileitem = inevow.IRequest(ctx).fields[key] name = fileitem.filename.decode(util.getPOSTCharset(ctx)) if name: value = self.fileHandler.storeFile( fileitem.file, name ) else: namer = self._namer(key) value = args.get(namer('value'))[0] value = iformal.IStringConvertible(self.original).fromType(value) return self.original.validate(value)
def processInput(self, ctx, key, args): fileitem = inevow.IRequest(ctx).fields[key] name = fileitem.filename.decode(util.getPOSTCharset(ctx)) if name: value = self.fileHandler.storeFile(fileitem.file, name) else: namer = self._namer(key) value = args.get(namer('value'))[0] value = iformal.IStringConvertible(self.original).fromType(value) return self.original.validate(value)
def processInput(self, ctx, key, args): # Get the whole string value = args.get(key, [''])[0].decode(util.getPOSTCharset(ctx)) # Split into lines values = value.splitlines() # Strip each line values = [v.strip() for v in values] # Discard empty lines values = [v for v in values if v] # Convert values to correct type converter = iformal.IStringConvertible(self.original.type) values = [converter.toType(v) for v in values] # Validate and return return self.original.validate(values)
def render(self, ctx, key, args, errors): namer = self._namer(key) if errors: fileitem = inevow.IRequest(ctx).fields[key] name = fileitem.filename.decode(util.getPOSTCharset(ctx)) if name: value = name else: namer = self._namer(key) value = args.get(namer('value'))[0] else: value = iformal.IStringConvertible(self.original).fromType(args.get(key)) return self._renderTag(ctx, key, value, namer, False)
def command_add(self, ctx, args): """ Add a product to the basket. Args contains: id -- the ID of the product to add. quantity -- optional number of the product to add, default to 1 """ # Decode the args productID = args['id'][0].decode(n_util.getPOSTCharset(ctx)) quantity = args.get('quantity', [1])[0] # Lookup the product def gotProduct(product): if product is not None: self.basket.addItem(product, quantity) return self.basketURL d = self.itemFromId(productID) d.addCallback(gotProduct) return d
def renderHTTP(self, ctx): """ Render new paste, render the document page, or process a form post. """ req = IRequest(ctx) # accept form post when 'convert' was clicked. if 'convert' in req.args: # spammers can f**k right off antispam = re.sub(r'(\s|[.,;-])', '', req.args.get('antispam')[0].lower()) if antispam not in ANTISPAM_ANSWERS: return url.here docID = None if 'docID' in req.args and req.args['docID'][0] != '': docID = int(req.args['docID'][0]) doc = self.store.find(Document, Document.id==docID).one() else: doc = Document() charset = nevowutil.getPOSTCharset(ctx) doc.text = req.args['text'][0].decode(charset) _, _title = doc.convertParts() doc.title = _title.decode(charset) doc.who = req.args['who'][0].decode(charset) doc.date14 = int(datetime.datetime.now().strftime('%Y%m%d%H%M%S')) self.store.add(doc) self.store.commit() if docID: return url.here else: return url.here.child('doc').child('%s' % (doc.id,)) elif req.args.get('delete', None) == ['delete']: if 'docID' not in req.args or req.args['docID'][0] == '': pass else: docID = int(req.args['docID'][0]) doc = self.store.find(Document, Document.id==docID).one() self.store.remove(doc) self.store.commit() return url.here.up().up().up() return rend.Page.renderHTTP(self, ctx)
def process(self, context, boundTo, data): """data is a list of strings at this point """ typed = self.original val = data[0] if typed.unicode: try: val = val.decode(getPOSTCharset(context), 'replace') except LookupError: val = val.decode('utf-8', 'replace') if typed.strip: val = val.strip() if val == '' or val is None: if typed.required: raise formless.InputError(typed.requiredFailMessage) else: return typed.null try: return typed.coerce(val, boundTo) except TypeError, e: warnings.warn('Typed.coerce takes two values now, the value to coerce and the configurable in whose context the coerce is taking place. %s %s' % (typed.__class__, typed)) return typed.coerce(val)
def processInput(self, ctx, key, args, default=''): value = args.get(key, [default])[0].decode(util.getPOSTCharset(ctx)) value = iformal.IStringConvertible(self.original).toType(value) return self.original.validate(value)
def processInput(self, ctx, key, args): charset = util.getPOSTCharset(ctx) values = [v.decode(charset) for v in args.get(key, [])] converter = iformal.IStringConvertible(self.original.type) values = [converter.toType(v) for v in values] return self.original.validate(values)
def processInput(self, ctx, key, args): value = args.get(key, [''])[0].decode(util.getPOSTCharset(ctx)) value = iformal.IStringConvertible(self.original).toType(value) return self.original.validate(value)
def processInput(self, ctx, key, args): namer = self._namer(key) value = [args.get(namer(part), [''])[0].strip().decode(util.getPOSTCharset(ctx)) for part in ('tparser', 'tvalue')] return self.original.validate(types.RichText(*value))
def processInput(self, ctx, key, args, default=None): # default is ignored here value = args.get(key, [''])[0].decode(util.getPOSTCharset(ctx)) value = iformal.IStringConvertible(self.original).fromType(value) return self.original.validate(value)