def webFormPost(self, request, res, configurable, ctx, bindingName, args): def redirectAfterPost(aspects): redirectAfterPost = request.getComponent( iformless.IRedirectAfterPost, None) if redirectAfterPost is None: ref = request.getHeader('referer') or '' else: ## Use the redirectAfterPost url ref = str(redirectAfterPost) from nevow import url refpath = url.URL.fromString(ref) magicCookie = '%s%s%s' % (now(), request.getClientIP(), random.random()) refpath = refpath.replace('_nevow_carryover_', magicCookie) _CARRYOVER[magicCookie] = C = compy.Componentized(aspects) request.redirect(str(refpath)) from nevow import static return static.Data('You posted a form to %s' % bindingName, 'text/plain'), () return util.maybeDeferred( configurable.postForm, ctx, bindingName, args).addCallback( self.onPostSuccess, request, ctx, bindingName, redirectAfterPost).addErrback(self.onPostFailure, request, ctx, bindingName, redirectAfterPost)
def getResourceFor(self, root, url): r = testutil.FakeRequest() self.request = r r.postpath = url.split('/') deferred = util.maybeDeferred( appserver.NevowSite(root).getResourceFor, r) return util.deferredResult(deferred)
def onManualPost(self, ctx, method, bindingName, kwargs): # This is copied from rend.Page.onWebFormPost def redirectAfterPost(aspects): redirectAfterPost = request.getComponent( iformless.IRedirectAfterPost, None) if redirectAfterPost is None: ref = request.getHeader('referer') or '' else: ## Use the redirectAfterPost url ref = str(redirectAfterPost) from nevow import url refpath = url.URL.fromString(ref) magicCookie = str(now()) refpath = refpath.replace('_nevow_carryover_', magicCookie) _CARRYOVER[magicCookie] = C = tpc.Componentized() for k, v in aspects.items(): C.setComponent(k, v) request.redirect(str(refpath)) from nevow import static return static.Data('You posted a form to %s' % bindingName, 'text/plain'), () request = inevow.IRequest(ctx) return util.maybeDeferred(method, **kwargs).addCallback( self.onPostSuccess, request, ctx, bindingName, redirectAfterPost).addErrback(self.onPostFailure, request, ctx, bindingName, redirectAfterPost)
def getResourceFor(self, root, url): r = testutil.FakeRequest() self.request = r r.postpath = url.split('/') ctx = context.RequestContext(tag=self.request) return util.maybeDeferred( appserver.NevowSite(root).getPageContextForRequestContext, ctx)
def locateChild(self, ctx, segments): request = inevow.IRequest(ctx) ## The method or property name we are going to validate against/affect bindingName = None name = segments[0] if name.startswith('freeform_post!'): configurableName, bindingName = name.split('!')[1:3] elif name.startswith('freeform-action-post!'): configurableName, request.args['freeform-actee'] = name.split( '!')[1:3] bindingName = request.args['freeform-action'][0] if bindingName: ctx.remember(self, inevow.IResource) ctx.remember(request, inevow.IRequest) cf = iformless.IConfigurableFactory(self) def checkC(c): if c is not None: return self.webFormPost(request, self, c, ctx, bindingName, request.args) return util.maybeDeferred(cf.locateConfigurable, ctx, configurableName).addCallback(checkC) return NotFound
def _innerFormRenderIt(context, data): tag = context.tag context.remember(configurableKey, iformless.IConfigurableKey) if configurable is None: warnings.warn( "No configurable was found which provides enough type information for freeform to be able to render forms") yield '' return context.remember(configurable, iformless.IConfigurable) formDefaults = iformless.IFormDefaults(context) if bindingDefaults is None: available = configurable.getBindingNames(context) else: available = bindingDefaults.iterkeys() def _callback(binding): renderer = iformless.IBindingRenderer(binding, defaultBindingRenderer) try: binding_pattern = tag.patternGenerator( 'freeform-form!!%s' % name ) except NodeNotFound: try: binding_pattern = tag.patternGenerator( 'freeform-form' ) except NodeNotFound: binding_pattern = freeformDefaultForm if binding_pattern is freeformDefaultForm: renderer.needsSkin = True return binding_pattern(data=binding, render=renderer, key=name) for name in available: if bindingDefaults is not None: defs = formDefaults.getAllDefaults(name) defs.update(bindingDefaults[name]) d = util.maybeDeferred(configurable.getBinding, context, name) d.addCallback(_callback) yield d
def webFormPost(self, request, res, configurable, ctx, bindingName, args): """Accept a web form post, either redisplaying the original form (with errors) if validation fails, or redirecting to the appropriate location after the post succeeds. This hook exists specifically for formless. New in 0.5, _nevow_carryover_ is only used if an autocallable method returns a result that needs to be carried over. New in 0.5, autocallables may return a nevow.url.URL or URLOverlay instance rather than setting IRedirectAfterPost on the request. New in 0.5, autocallables may return a Page instance to have that Page instance rendered at the post target URL with no redirects at all. Useful for multi-step wizards. """ def redirectAfterPost(aspects): hand = aspects.get(inevow.IHand) refpath = None if hand is not None: if isinstance(hand, Page): refpath = url.here if 'freeform_hand' not in inevow.IRequest(ctx).prepath: refpath = refpath.child('freeform_hand') if isinstance(hand, (url.URL, url.URLOverlay)): refpath, hand = hand, None if refpath is None: redirectAfterPost = request.getComponent(iformless.IRedirectAfterPost, None) if redirectAfterPost is None: ref = request.getHeader('referer') if ref: refpath = url.URL.fromString(ref) else: refpath = url.here else: warnings.warn("[0.5] IRedirectAfterPost is deprecated. Return a URL instance from your autocallable instead.", DeprecationWarning, 2) ## Use the redirectAfterPost url ref = str(redirectAfterPost) refpath = url.URL.fromString(ref) if hand is not None or aspects.get(iformless.IFormErrors) is not None: magicCookie = '%s%s%s' % (now(),request.getClientIP(),random.random()) refpath = refpath.replace('_nevow_carryover_', magicCookie) _CARRYOVER[magicCookie] = C = tpc.Componentized() for k, v in aspects.iteritems(): C.setComponent(k, v) destination = flat.flatten(refpath, ctx) request.redirect(destination) from nevow import static return static.Data('You posted a form to %s' % bindingName, 'text/plain'), () return util.maybeDeferred( configurable.postForm, ctx, bindingName, args ).addCallback( self.onPostSuccess, request, ctx, bindingName, redirectAfterPost ).addErrback( self.onPostFailure, request, ctx, bindingName, redirectAfterPost )
def getResourceFor(self, root, url): r = testutil.FakeRequest() self.request = r r.postpath = url.split('/') deferred = util.maybeDeferred(appserver.NevowSite(root).getResourceFor, r) return util.deferredResult( deferred )
def locateConfigurable(self, context, name): """formless.webform.renderForms calls locateConfigurable on the IConfigurableFactory instance it retrieves from the context. It passes the "name" that was passed to it, so if renderForms() was placed in the DOM, locateConfigurable will be called with name = ''; if renderForms('foo') was placed in the DOM, locateConfigurable will be called with name = 'foo'. This default implementation of locateConfigurable looks for a configurable_* method corresponding to the name which was passed. """ return util.maybeDeferred(getattr(self, 'configurable_%s'%name), context).addCallback(iformless.IConfigurable)
def _mapQuery(self, curs, query, *args): curs.execute(query, *args) dx = u.maybeDeferred(curs.fetchall) def mapper(result, xcurs): columns = [d[0] for d in xcurs.description] return [dict(zip(columns, r)) for r in result] def _error(error): print error dx.addCallback(mapper, curs) dx.addErrback(_error) return dx
def deferredRender(res, req): d = util.maybeDeferred(res.renderHTTP, context.PageContext( tag=res, parent=context.RequestContext( tag=req))) def done(result): if isinstance(result, str): req.write(result) return req d.addCallback(done) return d
def locateConfigurable(self, context, name): """formless.webform.renderForms calls locateConfigurable on the IConfigurableFactory instance it retrieves from the context. It passes the "name" that was passed to it, so if renderForms() was placed in the DOM, locateConfigurable will be called with name = ''; if renderForms('foo') was placed in the DOM, locateConfigurable will be called with name = 'foo'. This default implementation of locateConfigurable looks for a configurable_* method corresponding to the name which was passed. """ return util.maybeDeferred(getattr(self, 'configurable_%s' % name), context).addCallback(iformless.IConfigurable)
def deferredRender(res): defres = req() d = util.maybeDeferred(res.renderHTTP, context.PageContext( tag=res, parent=context.RequestContext( tag=defres))) def done(result): if isinstance(result, str): defres.write(result) defres.d.callback(defres.accumulator) return result d.addCallback(done) return unittest.deferredResult(defres.d, 1)
def postForm(self, ctx, obj, bindingName, args): self.conf = obj ctx.remember(self, iformless.IConfigurableFactory) def trapValidate(f): f.trap(formless.ValidateError) e = f.value errors = ctx.locate(iformless.IFormErrors) errors.setError(bindingName, e.formErrorMessage) errors.updateErrors(bindingName, e.errors) ctx.locate(iformless.IFormDefaults).getAllDefaults(bindingName).update(e.partialForm) return util.maybeDeferred(self.locateConfigurable,obj).addCallback(lambda x: x.postForm( ctx, bindingName, args )).addErrback(trapValidate)
def mapQuery(self, curs, query, args): curs.execute(query, args) d = util.maybeDeferred(curs.fetchall) def printerror(error, curs, query, args): print error.printTraceback() print curs print query print args def finalize(result, curs): columns = [d[0] for d in curs.description] return [dict(zip(columns, r)) for r in result] d.addErrback(printerror, curs, query, args) d.addCallback(finalize, curs) d.addErrback(printerror, curs, query, args) return d
def deferredRender(res): defres = req() d = util.maybeDeferred( res.renderHTTP, context.PageContext(tag=res, parent=context.RequestContext(tag=defres))) def done(result): if isinstance(result, str): defres.write(result) defres.d.callback(defres.accumulator) return result d.addCallback(done) return unittest.deferredResult(defres.d, 1)
def postForm(self, ctx, obj, bindingName, args): self.conf = obj ctx.remember(self, iformless.IConfigurableFactory) def trapValidate(f): f.trap(formless.ValidateError) e = f.value errors = ctx.locate(iformless.IFormErrors) ## Set the overall error for this form errors.setError(bindingName, e.formErrorMessage) errors.updateErrors(bindingName, e.errors) ctx.locate(iformless.IFormDefaults).getAllDefaults(bindingName).update(e.partialForm) return util.maybeDeferred(self.locateConfigurable,obj).addCallback(lambda x: x.postForm( ctx, bindingName, args )).addErrback(trapValidate)
def _addTopic(self, curs, queries, args): add_topic = queries[0] add_post = queries[1] topic_args = args[0] post_args = args[1] curs.execute(add_topic, topic_args) d = u.maybeDeferred(curs.execute, "SELECT MAX(t.id) FROM thread t") d.addCallback(lambda _: curs.fetchone()) def insTopic(result): post_args['thread_id'] = result[0] curs.execute(add_post, post_args) return result[0] def _error(error): print error d.addCallback(insTopic) d.addErrback(_error) return d
def deferredRender(res, request=None): if request is None: request = testutil.AccumulatingFakeRequest() d = util.maybeDeferred( res.renderHTTP, context.PageContext(tag=res, parent=context.RequestContext(tag=request))) def done(result): if isinstance(result, str): request.write(result) request.d.callback(request.accumulator) return result d.addCallback(done) return request.d
def deferredRender(res, request=None): if request is None: request = testutil.FakeRequest() request.d = defer.Deferred() d = util.maybeDeferred(res.renderHTTP, context.PageContext( tag=res, parent=context.RequestContext( tag=request))) def done(result): if isinstance(result, str): request.write(result) request.d.callback(request.accumulator) return result d.addCallback(done) return request.d
def locateChild(self, ctx, segments): request = inevow.IRequest(ctx) bindingName = None name = segments[0] if name.startswith('freeform_post!'): configurableName, bindingName = name.split('!')[1:3] elif name.startswith('freeform-action-post!'): configurableName, request.args['freeform-actee'] = name.split('!')[1:3] bindingName = request.args['freeform-action'][0] if bindingName: ctx.remember(self, inevow.IResource) ctx.remember(request, inevow.IRequest) cf = iformless.IConfigurableFactory(self) def checkC(c): if c is not None: return self.webFormPost(request, self, c, ctx, bindingName, request.args) return util.maybeDeferred(cf.locateConfigurable, ctx, configurableName).addCallback(checkC) return NotFound
def getResourceFor(root, url): """ Perform traversal for C{url} beginning at C{root}. @param root: The L{nevow.inevow.IResource} at which to begin. @param url: The relative path string of the url of the resource to retrieve. @type url: L{bytes} @return: A L{Deferred} that fires with a L{PageContext} for the discovered resource. """ request = testutil.FakeRequest() request.postpath = url.split('/') ctx = context.RequestContext(tag=request) return util.maybeDeferred( appserver.NevowSite(root).getPageContextForRequestContext, ctx)
def postForm(self, ctx, bindingName, args): """Accept a form post to the given bindingName. The post arguments are given in args. This will invoke the IInputProcessor for the binding with the given name. If it succeeds, the property will be modified or the method will have been called. If it fails, a ValidateError exception will be raised. """ def _callback(binding): ctx.remember(binding, iformless.IBinding) ctx.remember(self, iformless.IConfigurable) rv = iformless.IInputProcessor(binding).process(ctx, self, args) ctx.remember(rv, inevow.IHand) ctx.remember('%r success.' % bindingName, inevow.IStatusMessage) return rv return util.maybeDeferred(self.getBinding, ctx, bindingName).addCallback(_callback)
def _innerFormRenderIt(context, data): tag = context.tag # Remember the key for when the form post URL is generated. context.remember(configurableKey, iformless.IConfigurableKey) if configurable is None: warnings.warn( "No configurable was found which provides enough type information for freeform to be able to render forms" ) yield '' return context.remember(configurable, iformless.IConfigurable) formDefaults = iformless.IFormDefaults(context) if bindingDefaults is None: available = configurable.getBindingNames(context) else: available = bindingDefaults.iterkeys() def _callback(binding): renderer = iformless.IBindingRenderer(binding, defaultBindingRenderer) try: binding_pattern = tag.patternGenerator( 'freeform-form!!%s' % name) except NodeNotFound: try: binding_pattern = tag.patternGenerator('freeform-form') except NodeNotFound: binding_pattern = freeformDefaultForm if binding_pattern is freeformDefaultForm: renderer.needsSkin = True return binding_pattern(data=binding, render=renderer, key=name) for name in available: if bindingDefaults is not None: defs = formDefaults.getAllDefaults(name) defs.update(bindingDefaults[name]) d = util.maybeDeferred(configurable.getBinding, context, name) d.addCallback(_callback) yield d
def onManualPost(self, ctx, method, bindingName, kwargs): # This is copied from rend.Page.onWebFormPost def redirectAfterPost(aspects): redirectAfterPost = request.getComponent(iformless.IRedirectAfterPost, None) if redirectAfterPost is None: ref = request.getHeader('referer') or '' else: ## Use the redirectAfterPost url ref = str(redirectAfterPost) from nevow import url refpath = url.URL.fromString(ref) magicCookie = str(now()) refpath = refpath.replace('_nevow_carryover_', magicCookie) _CARRYOVER[magicCookie] = C = compy.Componentized(aspects) request.redirect(str(refpath)) from nevow import static return static.Data('You posted a form to %s' % bindingName, 'text/plain'), () request = inevow.IRequest(ctx) return util.maybeDeferred(method, **kwargs ).addCallback(self.onPostSuccess, request, ctx, bindingName,redirectAfterPost ).addErrback(self.onPostFailure, request, ctx, bindingName,redirectAfterPost)
def webFormPost(self, request, res, configurable, ctx, bindingName, args): def redirectAfterPost(aspects): redirectAfterPost = request.getComponent(iformless.IRedirectAfterPost, None) if redirectAfterPost is None: ref = request.getHeader('referer') or '' else: ref = str(redirectAfterPost) from nevow import url refpath = url.URL.fromString(ref) magicCookie = '%s%s%s' % (now(),request.getClientIP(),random.random()) refpath = refpath.replace('_nevow_carryover_', magicCookie) _CARRYOVER[magicCookie] = C = compy.Componentized(aspects) request.redirect(str(refpath)) from nevow import static return static.Data('You posted a form to %s' % bindingName, 'text/plain'), () return util.maybeDeferred( configurable.postForm, ctx, bindingName, args ).addCallback( self.onPostSuccess, request, ctx, bindingName, redirectAfterPost ).addErrback( self.onPostFailure, request, ctx, bindingName, redirectAfterPost )
def getBinding(self, ctx, name): """Massage bind_* methods and attributes into an IBinding. The bind_* method or attribute can either already implement IBinding or be a list of twoples which will be massaged into a MethodBinding as described in the ConfigurableMixin class docstring. """ def _get_binding(binding): if callable(binding): binding = util.maybeDeferred(binding, ctx) return binding def _convert_list(binding): if isinstance(binding, list): binding = annotate.MethodBinding( name, annotate.Method(arguments=[ annotate.Argument(n, v, v.id) for (n, v) in binding])) return binding binding = util.maybeDeferred(getattr, self, 'bind_%s' % name) return binding.addCallback(_get_binding).addCallback(_convert_list)
def renderResource(self, u): request = FakeRequest() ctx = context.RequestContext(tag=request) return util.maybeDeferred(inevow.IResource(u).renderHTTP, ctx).addCallback( lambda r: (r, request.redirected_to))
def finisher(result): return util.maybeDeferred(finishRequest).addCallback(lambda r: result)
def finisher(result): request.write(io.getvalue()) return util.maybeDeferred(finishRequest).addCallback(lambda r: result)
def finishRequest(): carryover = request.args.get('_nevow_carryover_', [None])[0] if carryover is not None and _CARRYOVER.has_key(carryover): del _CARRYOVER[carryover] if self.afterRender is not None: return util.maybeDeferred(self.afterRender,ctx)
def renderHTTP(self, ctx): if self.beforeRender is not None: return util.maybeDeferred(self.beforeRender,ctx).addCallback( lambda result,ctx: self._renderHTTP(ctx),ctx) return self._renderHTTP(ctx)
def finisher(result): return util.maybeDeferred(finishRequest).addCallback( lambda r: result)
def finisher(result): request.write(io.getvalue()) return util.maybeDeferred(finishRequest).addCallback( lambda r: result)
def finishRequest(): carryover = request.args.get('_nevow_carryover_', [None])[0] if carryover is not None and carryover in _CARRYOVER: del _CARRYOVER[carryover] if self.afterRender is not None: return util.maybeDeferred(self.afterRender, ctx)
def formRenderer(ctx, data): cf = ctx.locate(iformless.IConfigurableFactory) return util.maybeDeferred(cf.locateConfigurable, ctx, configurableKey ).addCallback(_formRenderIt)
def _get_binding(binding): if callable(binding): binding = util.maybeDeferred(binding, ctx) return binding
def _get_binding(binding): if isinstance(binding, collections.Callable): binding = util.maybeDeferred(binding, ctx) return binding
def formRenderer(ctx, data): cf = ctx.locate(iformless.IConfigurableFactory) return util.maybeDeferred(cf.locateConfigurable, ctx, configurableKey).addCallback(_formRenderIt)
def renderHTTP(self, ctx): if self.beforeRender is not None: return util.maybeDeferred(self.beforeRender, ctx).addCallback( lambda result, ctx: self._renderHTTP(ctx), ctx) return self._renderHTTP(ctx)