def testClass(self): values = {"a": 2, "b": 3, "c": 5} class c(object): a = 3 def __call__(self, b, c=4): return "%d%d%d" % (self.a, b, c) compute = __call__ cc = c() v = mapply(cc, (), values) self.assertEqual(v, "335") del values["c"] v = mapply(cc.compute, (), values) self.assertEqual(v, "334") class c2: """Must be a classic class.""" c2inst = c2() c2inst.__call__ = cc v = mapply(c2inst, (), values) self.assertEqual(v, "334")
def testClass(self): values = {'a': 2, 'b': 3, 'c': 5} class c(object): a = 3 def __call__(self, b, c=4): return '%d%d%d' % (self.a, b, c) compute = __call__ cc = c() v = mapply(cc, (), values) self.assertEqual(v, '335') del values['c'] v = mapply(cc.compute, (), values) self.assertEqual(v, '334') class c2: """Must be a classic class.""" c2inst = c2() c2inst.__call__ = cc v = mapply(c2inst, (), values) self.assertEqual(v, '334')
def test_mapply(self): from ZPublisher.mapply import mapply em1 = ExternalMethod('em', 'test method', 'Test', 'testf') self.assertEqual(mapply(em1, (), {'arg1': 4}), math.sqrt(4)) state = em1.__getstate__() em2 = ExternalMethod.__basicnew__() em2.__setstate__(state) self.assertEqual(mapply(em1, (), {'arg1': 9}), math.sqrt(9))
def updatePredicate(self, predicate_id, predicate, typeObjectName): """ Update a predicate in this element. """ if not predicate_id in self.predicate_ids: raise ValueError, "Unknown predicate: %s" % predicate_id predObj = self.predicates[predicate_id][0] mapply(predObj.edit, (), predicate.__dict__) self.assignTypeName(predicate_id, typeObjectName)
def testMethod(self): def compute(a, b, c=4): return '%d%d%d' % (a, b, c) values = {'a': 2, 'b': 3, 'c': 5} v = mapply(compute, (), values) self.assertEqual(v, '235') v = mapply(compute, (7, ), values) self.assertEqual(v, '735')
def updatePredicate( self, predicate_id, predicate, typeObjectName ): """ Update a predicate in this element. """ if not predicate_id in self.predicate_ids: raise ValueError, "Unknown predicate: %s" % predicate_id predObj = self.predicates[ predicate_id ][0] mapply( predObj.edit, (), predicate.__dict__ ) self.assignTypeName( predicate_id, typeObjectName )
def testMethod(self): def compute(a, b, c=4): return "%d%d%d" % (a, b, c) values = {"a": 2, "b": 3, "c": 5} v = mapply(compute, (), values) self.assertEqual(v, "235") v = mapply(compute, (7,), values) self.assertEqual(v, "735")
def testMethod(self): def compute(a, b, c=4): return '%d%d%d' % (a, b, c) values = {'a': 2, 'b': 3, 'c': 5} v = mapply(compute, (), values) self.assertEqual(v, '235') v = mapply(compute, (7,), values) self.assertEqual(v, '735')
def __call__(self, controller_state): url = self.getArg(controller_state) # see if this is a relative url or an absolute if len(urlparse.urlparse(url)[1]) != 0: # host specified, so url is absolute. No good for traversal. raise ValueError, 'Can\'t traverse to absolute url %s' % str(url) url_path = urlparse.urlparse(url)[2] # combine args from query string with args from the controller state # (args in the state supercede those in the query string) args = self.combineArgs(url, controller_state.kwargs) # put the args in the REQUEST REQUEST = controller_state.getContext().REQUEST for (key, value) in args.items(): REQUEST.set(key, value) # make sure target exists context = controller_state.getContext() obj = context.restrictedTraverse(url_path, default=None) if obj is None: raise ValueError, 'Unable to find %s\n' % str(url_path) return mapply(obj, REQUEST.args, REQUEST, call_object, 1, missing_name, dont_publish_class, REQUEST, bind=1)
def publish(self): """Publish the request into the response. """ self.start() # First check for "cancel" redirect ZMI-o-hardcoded thing: submit = self.request.get('SUBMIT', None) if submit is not None: if submit.strip().lower() == 'cancel': cancel = self.request.get('CANCEL_ACTION','') if cancel: raise zExceptions.Redirect(cancel) # Get the path, method and root root = self.get_application_root() method, path = self.get_path_and_method(root) # Do some optional virtual hosting vhm = self.request.query_plugin( root, interfaces.IVirtualHosting) root, method, path = vhm(method, path) # Zope 2 style post traverser hooks self.request._post_traverse = post_traverse = [] # Get object to publish/render traverser = self.request.query_plugin(root, interfaces.ITraverser) content = traverser(method, path) __traceback_supplement__ = (ErrorSupplement, content) # Zope 2 style post traverser hooks del self.request._post_traverse # Run authentication authenticator = self.request.query_plugin( content, interfaces.IAuthenticator) authenticator(Zope2.zpublisher_validated_hook) # Run Zope 2 style post traversal hooks if post_traverse: result = exec_callables(post_traverse) if result is not None: content = result notify(interfaces.PublicationAfterTraversal(self.request, content)) # Render the content into the response self.app.transaction.recordMetaData(content, self.request) result = mapply( content, self.request.args, self.request, call_object, 1, missing_name, dont_publish_class, self.request, bind=1) if result is not None: self.response.setBody(result) notify(interfaces.PublicationAfterRender(self.request, content)) return self.result()
def handleSubmit(self, action): unsorted_data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return unsorted_data = self.updateServerSideData(unsorted_data) errors = self.processActions(unsorted_data) if errors: return self.setErrorsMessage(errors) data = OrderedDict( [x for x in getFieldsInOrder(self.schema) if x[0] in unsorted_data] ) data.update(unsorted_data) thanksPageOverride = self.context.thanksPageOverride if thanksPageOverride: thanksPageOverrideAction = self.context.thanksPageOverrideAction thanksPage = get_expression(self.context, thanksPageOverride) if thanksPageOverrideAction == 'redirect_to': self.request.response.redirect(thanksPage) elif thanksPageOverrideAction == 'traverse_to': thanksPage = self.context.restrictedTraverse( thanksPage.encode('utf-8')) thanksPage = mapply( thanksPage, self.request.args, self.request ).encode('utf-8') self.request.response.write(thanksPage) else: # we come back to the form itself. # the thanks page is handled in the __call__ method pass
def createInObjectManager(self, id, REQUEST, RESPONSE=None): """ Create Z instance. If called with a RESPONSE, the RESPONSE will be redirected to the management screen of the new instance's parent Folder. Otherwise, the instance will be returned. """ i=mapply(self._zclass_, (), REQUEST) try: i._setId(id) except AttributeError: i.id=id folder=durl=None if hasattr(self, 'Destination'): d=self.Destination if d.im_self.__class__ is FactoryDispatcher: folder=d() if folder is None: folder=self.aq_parent if not hasattr(folder,'_setObject'): folder=folder.aq_parent folder._setObject(id, i) if RESPONSE is not None: try: durl=self.DestinationURL() except: durl=REQUEST['URL3'] RESPONSE.redirect(durl+'/manage_workspace') else: # An object is not guarenteed to have the id we passed in. id = i.getId() return folder._getOb(id)
def __call__(self, controller_state): url = self.getArg(controller_state) # see if this is a relative url or an absolute if len(urlparse(url)[1]) != 0: # host specified, so url is absolute. No good for traversal. raise ValueError('Can\'t traverse to absolute url %s' % str(url)) url_path = urlparse(url)[2] # combine args from query string with args from the controller state # (args in the state supercede those in the query string) args = self.combineArgs(url, controller_state.kwargs) # put the args in the REQUEST REQUEST = controller_state.getContext().REQUEST for (key, value) in args.items(): REQUEST.set(key, value) # make sure target exists context = controller_state.getContext() obj = context.restrictedTraverse(url_path, default=None) if obj is None: raise ValueError('Unable to find %s\n' % str(url_path)) return mapply(obj, REQUEST.args, REQUEST, call_object, 1, missing_name, dont_publish_class, REQUEST, bind=1)
def __call__(self, *args, **kwargs): """call method""" self._fixRequest() factory_info = self.REQUEST.get(FACTORY_INFO, {}) stack = factory_info["stack"] type_name = stack[0] id = stack[1] # do a passthrough if parent contains the id if id in aq_parent(self): return aq_parent(self).restrictedTraverse("/".join(stack[1:]))(*args, **kwargs) tempFolder = self._getTempFolder(type_name) # Mysterious hack that fixes some problematic interactions with # SpeedPack: # Get the first item in the stack by explicitly calling __getitem__ temp_obj = tempFolder.__getitem__(id) stack = stack[2:] if stack: try: obj = temp_obj.restrictedTraverse("/".join(stack)) except AttributeError: raise NotFound # Mimic URL traversal, sort of if getattr(aq_base(obj), "index_html", None): obj = obj.restrictedTraverse("index_html") else: obj = getattr(obj, "GET", obj) else: obj = temp_obj return mapply( obj, self.REQUEST.args, self.REQUEST, call_object, 1, missing_name, dont_publish_class, self.REQUEST, bind=1 )
def handleSubmit(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return data = self.updateServerSideData(data) errors = self.processActions(data) if errors: return self.setErrorsMessage(errors) thanksPageOverride = self.context.thanksPageOverride if thanksPageOverride: thanksPageOverrideAction = self.context.thanksPageOverrideAction thanksPage = get_expression(self.context, thanksPageOverride) if thanksPageOverrideAction == 'redirect_to': self.request.response.redirect(thanksPage) elif thanksPageOverrideAction == 'traverse_to': thanksPage = self.context.restrictedTraverse( thanksPage.encode('utf-8')) thanksPage = mapply( thanksPage, self.request.args, self.request).encode('utf-8') self.request.response.write(thanksPage) else: self.thanksPage = True replacer = DollarVarReplacer(data).sub self.thanksPrologue = self.context.thanksPrologue and replacer( self.context.thanksPrologue.output) self.thanksEpilogue = self.context.thanksEpilogue and replacer( self.context.thanksEpilogue.output) if not self.context.showAll: self.fields = self.setThanksFields(self.base_fields) for group in self.groups: group.fields = self.setThanksFields( self.base_groups.get(group.label)) self.setDisplayMode(DISPLAY_MODE) self.updateActions()
def publish(request, module_name, _get_module_info=get_module_info, # only for testing ): (bobo_before, bobo_after, object, realm, debug_mode, err_hook, validated_hook, transactions_manager, ) = _get_module_info(module_name) notify(PubStart(request)) newInteraction() try: request.processInputs() response = request.response if bobo_after is not None: response.after_list += (bobo_after,) if debug_mode: response.debug_mode = debug_mode if realm and not request.get('REMOTE_USER', None): response.realm = realm if bobo_before is not None: bobo_before() # Get the path list. # According to RFC1738 a trailing space in the path is valid. path = request.get('PATH_INFO') request['PARENTS'] = [object] object = request.traverse(path, validated_hook=validated_hook) notify(PubAfterTraversal(request)) if transactions_manager: transactions_manager.recordMetaData(object, request) result = mapply(object, request.args, request, call_object, 1, missing_name, dont_publish_class, request, bind=1, ) if result is not response: response.setBody(result) finally: endInteraction() notify(PubBeforeCommit(request)) return response
def publish( request, module_name, _get_module_info=get_module_info, # only for testing ): ( bobo_before, bobo_after, object, realm, debug_mode, err_hook, validated_hook, transactions_manager, ) = _get_module_info(module_name) notify(PubStart(request)) request.processInputs() response = request.response if bobo_after is not None: response.after_list += (bobo_after, ) if debug_mode: response.debug_mode = debug_mode if realm and not request.get('REMOTE_USER', None): response.realm = realm if bobo_before is not None: bobo_before() # Get the path list. # According to RFC1738 a trailing space in the path is valid. path = request.get('PATH_INFO') request['PARENTS'] = [object] object = request.traverse(path, validated_hook=validated_hook) notify(PubAfterTraversal(request)) if transactions_manager: transactions_manager.recordMetaData(object, request) result = mapply( object, request.args, request, call_object, 1, missing_name, dont_publish_class, request, bind=1, ) if result is not response: response.setBody(result) notify(PubBeforeCommit(request)) return response
def handleSubmit(self, action): unsorted_data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return unsorted_data = self.updateServerSideData(unsorted_data) errors = self.processActions(unsorted_data) if errors: return self.setErrorsMessage(errors) data = OrderedDict( [x for x in getFieldsInOrder(self.schema) if x[0] in unsorted_data] ) data.update(unsorted_data) thanksPageOverride = self.context.thanksPageOverride if not thanksPageOverride: # we come back to the form itself. # the thanks page is handled in the __call__ method return thanksPageOverrideAction = self.context.thanksPageOverrideAction thanksPage = get_expression(self.context, thanksPageOverride) if six.PY2 and isinstance(thanksPage, six.text_type): thanksPage = thanksPage.encode("utf-8") if thanksPageOverrideAction == "redirect_to": self.request.response.redirect(thanksPage) return if thanksPageOverrideAction == "traverse_to": thanksPage = self.context.restrictedTraverse(thanksPage) thanksPage = mapply(thanksPage, self.request.args, self.request) self.request.response.write(safe_encode(thanksPage))
def handleSubmit(self, action): unsorted_data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return unsorted_data = self.updateServerSideData(unsorted_data) errors = self.processActions(unsorted_data) if errors: return self.setErrorsMessage(errors) data = OrderedDict([ x for x in getFieldsInOrder(self.schema) if x[0] in unsorted_data ]) data.update(unsorted_data) thanksPageOverride = self.context.thanksPageOverride if thanksPageOverride: thanksPageOverrideAction = self.context.thanksPageOverrideAction thanksPage = get_expression(self.context, thanksPageOverride) if thanksPageOverrideAction == 'redirect_to': self.request.response.redirect(thanksPage) elif thanksPageOverrideAction == 'traverse_to': thanksPage = self.context.restrictedTraverse( thanksPage.encode('utf-8')) thanksPage = mapply(thanksPage, self.request.args, self.request).encode('utf-8') self.request.response.write(thanksPage) else: # we come back to the form itself. # the thanks page is handled in the __call__ method pass
def render_object(obj, path, where, append_html=True, output_root='', raise_errors=False): path = path.strip('/') assert '..' not in path outputfile = os.path.join(where, path) outputdir = os.path.dirname(outputfile) environ = {'SERVER_NAME': 'localhost', 'SERVER_PORT': '80'} stdin = StringIO() response = Response(stdout=sys.stdout, stderr=sys.stderr) request = Request(stdin, environ, response) if output_root: request['SERVER_URL'] = relpath(output_root, outputdir) setDefaultSkin(request) app = Application().__of__(RequestContainer(REQUEST=request)) obj = obj.__of__(app) request.other['VirtualRootPhysicalPath'] = obj.getPhysicalPath() obj = obj.unrestrictedTraverse(path) if getattr(obj, 'index_html', None) is not None: obj = obj.index_html try: result = mapply(obj, request.args, request) except Exception, e: print >> sys.stderr, "cannot render %s: %s: %s" % (path, e.__class__.__name__, e) if raise_errors: raise
def render_object(obj, path, where, append_html=True, output_root='', raise_errors=False): path = path.strip('/') assert '..' not in path outputfile = os.path.join(where, path) outputdir = os.path.dirname(outputfile) environ = {'SERVER_NAME': 'localhost', 'SERVER_PORT': '80'} stdin = StringIO() response = Response(stdout=sys.stdout, stderr=sys.stderr) request = Request(stdin, environ, response) if output_root: request['SERVER_URL'] = relpath(output_root, outputdir) setDefaultSkin(request) app = Application().__of__(RequestContainer(REQUEST=request)) obj = obj.__of__(app) request.other['VirtualRootPhysicalPath'] = obj.getPhysicalPath() obj = obj.unrestrictedTraverse(path) if getattr(obj, 'index_html', None) is not None: obj = obj.index_html try: result = mapply(obj, request.args, request) except Exception, e: print >> sys.stderr, "cannot render %s: %s: %s" % ( path, e.__class__.__name__, e) if raise_errors: raise
def testUncallableObject(self): # Normally, mapply will raise a TypeError if it encounters an # uncallable object (e.g. an interger ;)) self.assertRaises(TypeError, mapply, 2, (), {}) # Unless you enable the 'maybe' flag, in which case it will # only maybe call the object self.assertEqual(mapply(2, (), {}, maybe=True), 2)
def testClass(self): values = {'a': 2, 'b': 3, 'c': 5} class c(object): a = 3 def __call__(self, b, c=4): return '%d%d%d' % (self.a, b, c) compute = __call__ cc = c() v = mapply(cc, (), values) self.assertEqual(v, '335') del values['c'] v = mapply(cc.compute, (), values) self.assertEqual(v, '334')
def testClass(self): values = {'a': 2, 'b': 3, 'c': 5} class c: a = 3 def __call__(self, b, c=4): return '%d%d%d' % (self.a, b, c) compute = __call__ cc = c() v = mapply(cc, (), values) self.assertEqual(v, '335') del values['c'] v = mapply(cc.compute, (), values) self.assertEqual(v, '334')
def validate(self, controller_state, REQUEST, validators, argdict=None): if argdict is None: args = REQUEST.args kwargs = REQUEST else: args = () if REQUEST is None: kwargs = argdict else: kwargs = {} for k in REQUEST.keys(): if k in ('SESSION',): continue kwargs[k] = REQUEST[k] kwargs.update(argdict) context = controller_state.getContext() if validators is None: REQUEST.set('controller_state', controller_state) return controller_state for v in validators: REQUEST.set('controller_state', controller_state) if controller_state.hasValidated(v): continue try: # make sure validator exists obj = context.restrictedTraverse(v, default=None) if obj is None: raise ValueError('Unable to find validator %s\n' % str(v)) if not getattr(obj, 'is_validator', 1): raise ValueError('%s is not a CMFFormController validator' % str(v)) REQUEST = controller_state.getContext().REQUEST controller_state = mapply(obj, args, kwargs, call_object, 1, missing_name, dont_publish_class, REQUEST, bind=1) if controller_state is None or getattr(controller_state, '__class__', None) != ControllerState: raise ValueError('Validator %s did not return the state object' % str(v)) controller_state._addValidator(v) except ValidationError as e: # if a validator raises a ValidatorException, execution of # validators is halted and the controller_state is set to # the controller_state embedded in the exception controller_state = e.controller_state state_class = getattr(controller_state, '__class__', None) if state_class != ControllerState: raise Exception('Bad ValidationError state (type = %s)' % str(state_class)) break state_class = getattr(controller_state, '__class__', None) if state_class != ControllerState: raise Exception('Bad validator return type from validator %s (%s)' % (str(v), str(state_class))) REQUEST.set('controller_state', controller_state) REQUEST.set('controller_state', controller_state) return controller_state
def callObject(self, request, ob): def missing_name(name, context): if name == 'self': return ob #XXX what to do here? #raise TypeError('XXX') return mapply(ob, request.getPositionalArguments(), request, missing_name=missing_name, context=request)
def publish(request, module_info): obj, realm, debug_mode = module_info request.processInputs() response = request.response response.debug_exceptions = get_debug_exceptions() if debug_mode: response.debug_mode = debug_mode if realm and not request.get('REMOTE_USER', None): response.realm = realm noSecurityManager() # Get the path list. # According to RFC1738 a trailing space in the path is valid. path = request.get('PATH_INFO') request['PARENTS'] = [obj] obj = request.traverse(path, validated_hook=validate_user) # Set debug information from the active request on the open connection # Used to be done in ZApplicationWrapper.__bobo_traverse__ for ZServer try: # Grab the connection from the last (root application) object, # which usually has a connection available. request['PARENTS'][-1]._p_jar.setDebugInfo(request.environ, request.other) except AttributeError: # If there is no connection don't worry pass notify(pubevents.PubAfterTraversal(request)) recordMetaData(obj, request) result = mapply(obj, request.args, request, call_object, 1, missing_name, dont_publish_class, request, bind=1) if result is not response: response.setBody(result) return response
def fromRequest(self, id=None, REQUEST={}): if self._zclass_.__init__ is object.__init__: # there is no user defined __init__, avoid calling # mapply then, as it would fail while trying # to figure out the function properties i = self._zclass_() else: i = mapply(self._zclass_, (), REQUEST) if id is not None: try: i._setId(id) except AttributeError: i.id = id return i
def testObjectWithCall(self): # Make sure that the __call__ of an object can also be another # callable object. mapply will do the right thing and # recursive look for __call__ attributes until it finds an # actual method: class CallableObject(object): def __call__(self, a, b): return '%s%s' % (a, b) class Container(object): __call__ = CallableObject() v = mapply(Container(), (8, 3), {}) self.assertEqual(v, '83')
def action(self, *args, **kwargs): if self.state != "active": raise ValueError( "Can't perform an action on a work item that isn't active.") if self.REQUEST is None: kw = kwargs else: kw = self.REQUEST.form.copy() kw.update(kwargs) try: message = mapply(method, (self, ) + args, kw) except CannotComplete: message = u'Could not complete.' self.notifyAssigneesChange() self._update_ui_after_action(message, self.REQUEST)
def testObjectWithCall(self): # Make sure that the __call__ of an object can also be another # callable object. mapply will do the right thing and # recursive look for __call__ attributes until it finds an # actual method: class CallableObject: def __call__(self, a, b): return f'{a}{b}' class Container: __call__ = CallableObject() v = mapply(Container(), (8, 3), {}) self.assertEqual(v, '83')
def publish(app, debug_mode, request, response): """ Used in place of :: from ZPublisher.Publish import publish_module publish_module('Zope2', debug=not handle_errors, request=request, response=response) Warning: some calls made by ``publish_module`` have been removed (maybe wrongly). """ from ZPublisher.mapply import mapply from ZPublisher.Publish import call_object from ZPublisher.Publish import missing_name from ZPublisher.Publish import dont_publish_class from zope.publisher.interfaces import ISkinnable from zope.publisher.skinnable import setDefaultSkin if ISkinnable.providedBy(request): setDefaultSkin(request) request.processInputs() if debug_mode: response.debug_mode = debug_mode if not request.get('REMOTE_USER', None): response.realm = 'Zope2' # Get the path list. # According to RFC1738 a trailing space in the path is valid. path = request.get('PATH_INFO') request['PARENTS'] = [app] from Zope2.App.startup import validated_hook object = request.traverse(path, validated_hook=validated_hook) result = mapply(object, request.args, request, call_object, 1, missing_name, dont_publish_class, request, bind=1) if result is not response: response.setBody(result)
def __call__(self, *args, **kwargs): """call method""" self._fixRequest() factory_info = self.REQUEST.get(FACTORY_INFO, {}) stack = factory_info['stack'] type_name = stack[0] id = stack[1] # do a passthrough if parent contains the id if id in aq_parent(self): return aq_parent(self).restrictedTraverse('/'.join(stack[1:]))( *args, **kwargs) tempFolder = self._getTempFolder(type_name) # Mysterious hack that fixes some problematic interactions with # SpeedPack: # Get the first item in the stack by explicitly calling __getitem__ temp_obj = tempFolder.__getitem__(id) stack = stack[2:] if stack: try: obj = temp_obj.restrictedTraverse('/'.join(stack)) except AttributeError: raise NotFound # Mimic URL traversal, sort of if getattr(aq_base(obj), 'index_html', None): obj = obj.restrictedTraverse('index_html') else: obj = getattr(obj, 'GET', obj) else: obj = temp_obj return mapply(obj, self.REQUEST.args, self.REQUEST, call_object, 1, missing_name, dont_publish_class, self.REQUEST, bind=1)
def testOldStyleClass(self): # Testing old-style class behavior. values = {'a': 2, 'b': 3, 'c': 5} class c(object): a = 3 def __call__(self, b, c=4): return '%d%d%d' % (self.a, b, c) compute = __call__ cc = c() class c2: """Must be a classic class.""" c2inst = c2() c2inst.__call__ = cc v = mapply(c2inst, (), values) self.assertEqual(v, '335')
def publish(request, module_info): obj, realm, debug_mode = module_info request.processInputs() response = request.response response.debug_exceptions = get_debug_exceptions() if debug_mode: response.debug_mode = debug_mode if realm and not request.get('REMOTE_USER', None): response.realm = realm noSecurityManager() # Get the path list. # According to RFC1738 a trailing space in the path is valid. path = request.get('PATH_INFO') request['PARENTS'] = [obj] obj = request.traverse(path, validated_hook=validate_user) notify(pubevents.PubAfterTraversal(request)) recordMetaData(obj, request) result = mapply(obj, request.args, request, call_object, 1, missing_name, dont_publish_class, request, bind=1) if result is not response: response.setBody(result) return response
def __call__(self, *args, **kwargs): """call method""" self._fixRequest() factory_info = self.REQUEST.get(FACTORY_INFO, {}) stack = factory_info['stack'] type_name = stack[0] id = stack[1] # do a passthrough if parent contains the id if id in aq_parent(self).objectIds(): return aq_parent(self).restrictedTraverse('/'.join(stack[1:]))(*args, **kwargs) tempFolder = self._getTempFolder(type_name) # Mysterious hack that fixes some problematic interactions with SpeedPack: # Get the first item in the stack by explicitly calling __getitem__ temp_obj = tempFolder.__getitem__(id) stack = stack[2:] if stack: obj = temp_obj.restrictedTraverse('/'.join(stack)) else: obj = temp_obj return mapply(obj, self.REQUEST.args, self.REQUEST, call_object, 1, missing_name, dont_publish_class, self.REQUEST, bind=1)
def publish( request, module_name, after_list, debug=0, # Optimize: call_object=call_object, missing_name=missing_name, dont_publish_class=dont_publish_class, mapply=mapply, ): (bobo_before, bobo_after, object, realm, debug_mode, err_hook, validated_hook, transactions_manager) = get_module_info(module_name) parents = None response = None try: notify(pubevents.PubStart(request)) # TODO pass request here once BaseRequest implements IParticipation newInteraction() request.processInputs() request_get = request.get response = request.response # First check for "cancel" redirect: if request_get('SUBMIT', '').strip().lower() == 'cancel': cancel = request_get('CANCEL_ACTION', '') if cancel: # Relative URLs aren't part of the spec, but are accepted by # some browsers. for part, base in zip( urlparse(cancel)[:3], urlparse(request['BASE1'])[:3]): if not part: continue if not part.startswith(base): cancel = '' break if cancel: raise Redirect(cancel) after_list[0] = bobo_after if debug_mode: response.debug_mode = debug_mode if realm and not request.get('REMOTE_USER', None): response.realm = realm noSecurityManager() if bobo_before is not None: bobo_before() # Get the path list. # According to RFC1738 a trailing space in the path is valid. path = request_get('PATH_INFO') request['PARENTS'] = parents = [object] if transactions_manager: transactions_manager.begin() object = request.traverse(path, validated_hook=validated_hook) if IBrowserPage.providedBy(object): request.postProcessInputs() notify(pubevents.PubAfterTraversal(request)) if transactions_manager: recordMetaData(object, request) result = mapply(object, request.args, request, call_object, 1, missing_name, dont_publish_class, request, bind=1) if result is not response: response.setBody(result) notify(pubevents.PubBeforeCommit(request)) if transactions_manager: transactions_manager.commit() notify(pubevents.PubSuccess(request)) endInteraction() return response except: # save in order to give 'PubFailure' the original exception info exc_info = sys.exc_info() # DM: provide nicer error message for FTP sm = None if response is not None: sm = getattr(response, "setMessage", None) if sm is not None: from asyncore import compact_traceback cl, val = sys.exc_info()[:2] sm('%s: %s %s' % (getattr(cl, '__name__', cl), val, debug_mode and compact_traceback()[-1] or '')) # debug is just used by tests (has nothing to do with debug_mode!) if not debug and err_hook is not None: retry = False if parents: parents = parents[0] try: try: return err_hook( parents, request, sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], ) except Retry: if not request.supports_retry(): return err_hook( parents, request, sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], ) retry = True finally: # Note: 'abort's can fail. # Nevertheless, we want end request handling. try: try: notify( pubevents.PubBeforeAbort(request, exc_info, retry)) finally: if transactions_manager: transactions_manager.abort() finally: endInteraction() notify(pubevents.PubFailure(request, exc_info, retry)) # Only reachable if Retry is raised and request supports retry. newrequest = request.retry() request.close() # Free resources held by the request. # Set the default layer/skin on the newly generated request if ISkinnable.providedBy(newrequest): setDefaultSkin(newrequest) try: return publish(newrequest, module_name, after_list, debug) finally: newrequest.close() else: # Note: 'abort's can fail. # Nevertheless, we want end request handling. try: try: notify(pubevents.PubBeforeAbort(request, exc_info, False)) finally: if transactions_manager: transactions_manager.abort() finally: endInteraction() notify(pubevents.PubFailure(request, exc_info, False)) raise
def mapply(self, obj, **kw): return mapply.mapply( obj, self.request.args, kw, Publish.call_object, 1, Publish.missing_name, Publish.dont_publish_class, self.request, bind=1)
def subrequest(url, root=None, stdout=None): assert url is not None, "You must pass a url" if isinstance(url, unicode): url = url.encode('utf-8') _, _, path, query, _ = urlsplit(url) parent_request = getRequest() assert parent_request is not None, "Unable to get request, perhaps zope.globalrequest is not configured." parent_site = getSite() parent_app = parent_request.PARENTS[-1] if path.startswith('/'): path = normpath(path) vurl_parts = parent_request.get('VIRTUAL_URL_PARTS') if vurl_parts is not None: # Use the virtual host root path_past_root = unquote(vurl_parts[-1]) root_path = normpath(parent_request['PATH_INFO']).rstrip('/')[:-len(path_past_root) or None] if root is None: path = root_path + path else: path = '%s/%s%s' % (root_path, root.virtual_url_path(), path) elif root is not None: path = '/%s%s' % (root.virtual_url_path(), path) else: try: parent_url = parent_request['URL'] if isinstance(parent_url, unicode): parent_url = parent_url.encode('utf-8') # extra is the hidden part of the url, e.g. a default view extra = unquote(parent_url[len(parent_request['ACTUAL_URL']):]) except KeyError: extra = '' here = parent_request['PATH_INFO'] + extra path = urljoin(here, path) path = normpath(path) request = parent_request.clone() for name, parent_value in parent_request.other.items(): if name in OTHER_IGNORE or OTHER_IGNORE_RE.match(name) or name.startswith('_'): continue request.other[name] = parent_value request['PARENT_REQUEST'] = parent_request alsoProvides(request, ISubRequest) try: setRequest(request) request_container = RequestContainer(REQUEST=request) app = aq_base(parent_app).__of__(request_container) request['PARENTS'] = [app] response = request.response response.__class__ = SubResponse response.stderr = None # only used on retry it seems if stdout is None: stdout = StringIO() # It might be possible to optimize this response.stdout = stdout environ = request.environ environ['PATH_INFO'] = path environ['QUERY_STRING'] = query # Clean up the request. for header in CONDITIONAL_HEADERS: environ.pop(header, None) try: request.processInputs() traversed = request.traverse(path) result = mapply(traversed, positional=request.args, keyword=request, debug=None, maybe=1, missing_name=missing_name, handle_class=dont_publish_class, context=request, bind=1) if result is not response: response.setBody(result) for key, value in request.response.cookies.items(): parent_request.response.cookies[key] = value except: logger.exception("Error handling subrequest to %s" % url) response.exception() return response finally: request.clear() setRequest(parent_request) setSite(parent_site)
def subrequest(url, root=None, stdout=None, exception_handler=None): assert url is not None, 'You must pass a url' if isinstance(url, six.text_type): url = url.encode('utf-8') _, _, path, query, _ = urlsplit(url) parent_request = getRequest() assert parent_request is not None, \ 'Unable to get request, perhaps zope.globalrequest is not configured.' parent_site = getSite() security_manager = getSecurityManager() parent_app = parent_request.PARENTS[-1] if path.startswith('/'): path = normpath(path) vurl_parts = parent_request.get('VIRTUAL_URL_PARTS') if vurl_parts is not None: # Use the virtual host root path_past_root = unquote(vurl_parts[-1]) root_path = normpath(parent_request['PATH_INFO']).rstrip( '/')[:-len(path_past_root) or None] if root is None: path = root_path + path else: path = '{0}/{1}{2}'.format(root_path, root.virtual_url_path(), path) elif root is not None: path = '/{0}{1}'.format(root.virtual_url_path(), path) else: try: parent_url = parent_request['URL'] if isinstance(parent_url, six.text_type): parent_url = parent_url.encode('utf-8') # extra is the hidden part of the url, e.g. a default view extra = unquote(parent_url[len(parent_request['ACTUAL_URL']):]) except KeyError: extra = '' here = parent_request['PATH_INFO'] + extra path = urljoin(here, path) path = normpath(path) request = parent_request.clone() for name, parent_value in parent_request.other.items(): if name in OTHER_IGNORE \ or OTHER_IGNORE_RE.match(name) \ or name.startswith('_'): continue request.other[name] = parent_value for key, value in parent_request.response.cookies.items(): request.cookies[key] = value['value'] request['PARENT_REQUEST'] = parent_request alsoProvides(request, ISubRequest) try: setRequest(request) request_container = RequestContainer(REQUEST=request) app = aq_base(parent_app).__of__(request_container) request['PARENTS'] = [app] response = request.response response.__class__ = SubResponse response.stderr = None # only used on retry it seems if stdout is None: stdout = StringIO() # It might be possible to optimize this response.stdout = stdout environ = request.environ environ['PATH_INFO'] = path environ['QUERY_STRING'] = query # Clean up the request. for header in CONDITIONAL_HEADERS: environ.pop(header, None) try: request.processInputs() traversed = request.traverse(path) result = mapply(traversed, positional=request.args, keyword=request, debug=None, maybe=1, missing_name=missing_name, handle_class=dont_publish_class, context=request, bind=1) if result is not response: response.setBody(result) for key, value in request.response.cookies.items(): parent_request.response.cookies[key] = value except Exception as e: logger.exception('Error handling subrequest to {0}'.format(url)) if exception_handler is not None: exception_handler(response, e) else: view = queryMultiAdapter((e, request), name=u'index.html') if view is not None: v = view() response.setBody(v) else: response.exception() return response finally: if SAFE_WRITE_KEY in request.environ: # append this list of safe oids to parent request if SAFE_WRITE_KEY not in parent_request.environ: parent_request.environ[SAFE_WRITE_KEY] = [] new_keys = (set(request.environ[SAFE_WRITE_KEY]) - set(parent_request.environ[SAFE_WRITE_KEY])) parent_request.environ[SAFE_WRITE_KEY].extend(new_keys) if IDisableCSRFProtection.providedBy(request): alsoProvides(parent_request, IDisableCSRFProtection) request.clear() setRequest(parent_request) setSite(parent_site) setSecurityManager(security_manager)
def subrequest(url, root=None, stdout=None, exception_handler=None): assert url is not None, 'You must pass a url' if six.PY2 and isinstance(url, six.text_type): url = url.encode('utf-8') _, _, path, query, _ = urlsplit(url) parent_request = getRequest() assert parent_request is not None, \ 'Unable to get request, perhaps zope.globalrequest is not configured.' parent_site = getSite() security_manager = getSecurityManager() parent_app = parent_request.PARENTS[-1] if path.startswith('/'): path = normpath(path) vurl_parts = parent_request.get('VIRTUAL_URL_PARTS') if vurl_parts is not None: # Use the virtual host root path_past_root = unquote(vurl_parts[-1]) root_path = normpath( parent_request['PATH_INFO'] ).rstrip('/')[:-len(path_past_root) or None] if root is None: path = root_path + path else: path = '{0}/{1}{2}'.format( root_path, root.virtual_url_path(), path ) elif root is not None: path = '/{0}{1}'.format(root.virtual_url_path(), path) else: try: parent_url = parent_request['URL'] if isinstance(parent_url, six.binary_type): parent_url = parent_url.encode('utf-8') # extra is the hidden part of the url, e.g. a default view extra = unquote( parent_url[len(parent_request['ACTUAL_URL']):] ) except KeyError: extra = '' here = parent_request['PATH_INFO'] + extra path = urljoin(here, path) path = normpath(path) request = parent_request.clone() for name, parent_value in parent_request.other.items(): if name in OTHER_IGNORE \ or OTHER_IGNORE_RE.match(name) \ or name.startswith('_'): continue request.other[name] = parent_value for key, value in parent_request.response.cookies.items(): request.cookies[key] = value['value'] request['PARENT_REQUEST'] = parent_request alsoProvides(request, ISubRequest) try: setRequest(request) request_container = RequestContainer(REQUEST=request) app = aq_base(parent_app).__of__(request_container) request['PARENTS'] = [app] response = request.response response.__class__ = SubResponse response.stderr = None # only used on retry it seems if stdout is None: stdout = StringIO() # It might be possible to optimize this response.stdout = stdout environ = request.environ environ['PATH_INFO'] = path environ['QUERY_STRING'] = query # Clean up the request. for header in CONDITIONAL_HEADERS: environ.pop(header, None) try: request.processInputs() traversed = request.traverse(path) result = mapply( traversed, positional=request.args, keyword=request, debug=None, maybe=1, missing_name=missing_name, handle_class=dont_publish_class, context=request, bind=1 ) if result is not response: response.setBody(result) for key, value in request.response.cookies.items(): parent_request.response.cookies[key] = value except Exception as e: logger.exception(u'Error handling subrequest to {0}'.format(url)) if exception_handler is not None: exception_handler(response, e) else: view = queryMultiAdapter((e, request), name=u'index.html') if view is not None: v = view() response.setBody(v) else: response.exception() return response finally: if SAFE_WRITE_KEY in request.environ: # append this list of safe oids to parent request if SAFE_WRITE_KEY not in parent_request.environ: parent_request.environ[SAFE_WRITE_KEY] = [] new_keys = ( set(request.environ[SAFE_WRITE_KEY]) - set(parent_request.environ[SAFE_WRITE_KEY]) ) parent_request.environ[SAFE_WRITE_KEY].extend(new_keys) if IDisableCSRFProtection.providedBy(request): alsoProvides(parent_request, IDisableCSRFProtection) request.clear() setRequest(parent_request) setSite(parent_site) setSecurityManager(security_manager)
def fromRequest(self, id=None, REQUEST={}): i=mapply(self._zclass_, (), REQUEST) if id is not None and (not hasattr(i, 'id') or not i.id): i.id=id return i
def validate(self, controller_state, REQUEST, validators, argdict=None): if argdict is None: args = REQUEST.args kwargs = REQUEST else: args = () if REQUEST is None: kwargs = argdict else: kwargs = {} for k in REQUEST.keys(): if k in ('SESSION', ): continue kwargs[k] = REQUEST[k] kwargs.update(argdict) context = controller_state.getContext() if validators is None: REQUEST.set('controller_state', controller_state) return controller_state for v in validators: REQUEST.set('controller_state', controller_state) if controller_state.hasValidated(v): continue try: # make sure validator exists obj = context.restrictedTraverse(v, default=None) if obj is None: raise ValueError, 'Unable to find validator %s\n' % str(v) if not getattr(obj, 'is_validator', 1): raise ValueError, '%s is not a CMFFormController validator' % str( v) REQUEST = controller_state.getContext().REQUEST controller_state = mapply(obj, args, kwargs, call_object, 1, missing_name, dont_publish_class, REQUEST, bind=1) if controller_state is None or getattr( controller_state, '__class__', None) != ControllerState: raise ValueError, 'Validator %s did not return the state object' % str( v) controller_state._addValidator(v) except ValidationError, e: # if a validator raises a ValidatorException, execution of # validators is halted and the controller_state is set to # the controller_state embedded in the exception controller_state = e.controller_state state_class = getattr(controller_state, '__class__', None) if state_class != ControllerState: raise Exception, 'Bad ValidationError state (type = %s)' % str( state_class) break state_class = getattr(controller_state, '__class__', None) if state_class != ControllerState: raise Exception, 'Bad validator return type from validator %s (%s)' % ( str(v), str(state_class)) REQUEST.set('controller_state', controller_state)
def publish(request, module_name, after_list, debug=0, # Optimize: call_object=call_object, missing_name=missing_name, dont_publish_class=dont_publish_class, mapply=mapply, ): (bobo_before, bobo_after, object, realm, debug_mode, err_hook, validated_hook, transactions_manager) = get_module_info(module_name) parents = None response = None try: notify(pubevents.PubStart(request)) # TODO pass request here once BaseRequest implements IParticipation newInteraction() request.processInputs() request_get = request.get response = request.response # First check for "cancel" redirect: if request_get('SUBMIT', '').strip().lower() == 'cancel': cancel = request_get('CANCEL_ACTION', '') if cancel: # Relative URLs aren't part of the spec, but are accepted by # some browsers. for part, base in zip(urlparse(cancel)[:3], urlparse(request['BASE1'])[:3]): if not part: continue if not part.startswith(base): cancel = '' break if cancel: raise Redirect(cancel) after_list[0] = bobo_after if debug_mode: response.debug_mode = debug_mode if realm and not request.get('REMOTE_USER', None): response.realm = realm noSecurityManager() if bobo_before is not None: bobo_before() # Get the path list. # According to RFC1738 a trailing space in the path is valid. path = request_get('PATH_INFO') request['PARENTS'] = parents = [object] if transactions_manager: transactions_manager.begin() object = request.traverse(path, validated_hook=validated_hook) if IBrowserPage.providedBy(object): request.postProcessInputs() notify(pubevents.PubAfterTraversal(request)) if transactions_manager: recordMetaData(object, request) result = mapply(object, request.args, request, call_object, 1, missing_name, dont_publish_class, request, bind=1) if result is not response: response.setBody(result) notify(pubevents.PubBeforeCommit(request)) if transactions_manager: transactions_manager.commit() notify(pubevents.PubSuccess(request)) endInteraction() return response except: # save in order to give 'PubFailure' the original exception info exc_info = sys.exc_info() # DM: provide nicer error message for FTP sm = None if response is not None: sm = getattr(response, "setMessage", None) if sm is not None: from asyncore import compact_traceback cl, val = sys.exc_info()[:2] sm('%s: %s %s' % ( getattr(cl, '__name__', cl), val, debug_mode and compact_traceback()[-1] or '')) # debug is just used by tests (has nothing to do with debug_mode!) if not debug and err_hook is not None: retry = False if parents: parents = parents[0] try: try: return err_hook(parents, request, sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], ) except Retry: if not request.supports_retry(): return err_hook(parents, request, sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], ) retry = True finally: # Note: 'abort's can fail. # Nevertheless, we want end request handling. try: try: notify(pubevents.PubBeforeAbort( request, exc_info, retry)) finally: if transactions_manager: transactions_manager.abort() finally: endInteraction() notify(pubevents.PubFailure(request, exc_info, retry)) # Only reachable if Retry is raised and request supports retry. newrequest = request.retry() request.close() # Free resources held by the request. # Set the default layer/skin on the newly generated request if ISkinnable.providedBy(newrequest): setDefaultSkin(newrequest) try: return publish(newrequest, module_name, after_list, debug) finally: newrequest.close() else: # Note: 'abort's can fail. # Nevertheless, we want end request handling. try: try: notify(pubevents.PubBeforeAbort(request, exc_info, False)) finally: if transactions_manager: transactions_manager.abort() finally: endInteraction() notify(pubevents.PubFailure(request, exc_info, False)) raise