use ._cw instead of req on appobject classes
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Wed, 23 Sep 2009 09:33:02 +0200
changeset 3378 2f25f701301d
parent 3377 dd9d292b6a6d
child 3379 9192ba07890d
use ._cw instead of req on appobject classes
entities/authobjs.py
entity.py
selectors.py
--- a/entities/authobjs.py	Wed Sep 23 09:29:39 2009 +0200
+++ b/entities/authobjs.py	Wed Sep 23 09:33:02 2009 +0200
@@ -91,12 +91,12 @@
         return self.groups == frozenset(('guests', ))
 
     def owns(self, eid):
-        if hasattr(self.req, 'unsafe_execute'):
+        if hasattr(self._cw, 'unsafe_execute'):
             # use unsafe_execute on the repository side, in case
             # session's user doesn't have access to CWUser
-            execute = self.req.unsafe_execute
+            execute = self._cw.unsafe_execute
         else:
-            execute = self.req.execute
+            execute = self._cw.execute
         try:
             return execute('Any X WHERE X eid %(x)s, X owned_by U, U eid %(u)s',
                            {'x': eid, 'u': self.eid}, 'x')
@@ -114,7 +114,7 @@
             kwargs['x'] = contexteid
             cachekey = 'x'
         try:
-            return self.req.execute(rql, kwargs, cachekey)
+            return self._cw.execute(rql, kwargs, cachekey)
         except Unauthorized:
             return False
 
@@ -124,7 +124,7 @@
         """construct a name using firstname / surname or login if not defined"""
 
         if self.firstname and self.surname:
-            return self.req._('%(firstname)s %(surname)s') % {
+            return self._cw._('%(firstname)s %(surname)s') % {
                 'firstname': self.firstname, 'surname' : self.surname}
         if self.firstname:
             return self.firstname
--- a/entity.py	Wed Sep 23 09:29:39 2009 +0200
+++ b/entity.py	Wed Sep 23 09:33:02 2009 +0200
@@ -166,7 +166,7 @@
                 # later information here, systematically add it.
                 restrictions[-1] += '?'
                 # XXX user.req.vreg iiiirk
-                destcls = user.req.vreg['etypes'].etype_class(desttype)
+                destcls = user._cw.vreg['etypes'].etype_class(desttype)
                 destcls._fetch_restrictions(var, varmaker, destcls.fetch_attrs,
                                             selection, orderby, restrictions,
                                             user, ordermethod, visited=visited)
@@ -247,24 +247,24 @@
 
     @cached
     def metainformation(self):
-        res = dict(zip(('type', 'source', 'extid'), self.req.describe(self.eid)))
-        res['source'] = self.req.source_defs()[res['source']]
+        res = dict(zip(('type', 'source', 'extid'), self._cw.describe(self.eid)))
+        res['source'] = self._cw.source_defs()[res['source']]
         return res
 
     def clear_local_perm_cache(self, action):
         for rqlexpr in self.e_schema.get_rqlexprs(action):
-            self.req.local_perm_cache.pop((rqlexpr.eid, (('x', self.eid),)), None)
+            self._cw.local_perm_cache.pop((rqlexpr.eid, (('x', self.eid),)), None)
 
     def check_perm(self, action):
-        self.e_schema.check_perm(self.req, action, self.eid)
+        self.e_schema.check_perm(self._cw, action, self.eid)
 
     def has_perm(self, action):
-        return self.e_schema.has_perm(self.req, action, self.eid)
+        return self.e_schema.has_perm(self._cw, action, self.eid)
 
     def view(self, vid, __registry='views', **kwargs):
         """shortcut to apply a view on this entity"""
-        return self.vreg[__registry].render(vid, self.req, rset=self.rset,
-                                            row=self.row, col=self.col, **kwargs)
+        return self._cw.vreg[__registry].render(
+            vid, self._cw, rset=self.rset, row=self.row, col=self.col, **kwargs)
 
     def absolute_url(self, *args, **kwargs):
         """return an absolute url to view this entity"""
@@ -278,7 +278,7 @@
         # in linksearch mode, we don't want external urls else selecting
         # the object for use in the relation is tricky
         # XXX search_state is web specific
-        if getattr(self.req, 'search_state', ('normal',))[0] == 'normal':
+        if getattr(self._cw, 'search_state', ('normal',))[0] == 'normal':
             kwargs['base_url'] = self.metainformation()['source'].get('base-url')
         if method in (None, 'view'):
             try:
@@ -289,7 +289,7 @@
                 kwargs['_restpath'] = self.rest_path()
         else:
             kwargs['rql'] = 'Any X WHERE X eid %s' % self.eid
-        return self.req.build_url(method, **kwargs)
+        return self._cw.build_url(method, **kwargs)
 
     def rest_path(self, use_ext_eid=False):
         """returns a REST-like (relative) path for this entity"""
@@ -305,7 +305,7 @@
                 # make sure url is not ambiguous
                 rql = 'Any COUNT(X) WHERE X is %s, X %s %%(value)s' % (
                     etype, mainattr)
-                nbresults = self.req.execute(rql, {'value' : value})[0][0]
+                nbresults = self._cw.execute(rql, {'value' : value})[0][0]
                 if nbresults != 1: # ambiguity?
                     mainattr = 'eid'
                     path += '/eid'
@@ -314,13 +314,13 @@
                 value = self.metainformation()['extid']
             else:
                 value = self.eid
-        return '%s/%s' % (path, self.req.url_quote(value))
+        return '%s/%s' % (path, self._cw.url_quote(value))
 
     def attr_metadata(self, attr, metadata):
         """return a metadata for an attribute (None if unspecified)"""
         value = getattr(self, '%s_%s' % (attr, metadata), None)
         if value is None and metadata == 'encoding':
-            value = self.vreg.property_value('ui.encoding')
+            value = self._cw.vreg.property_value('ui.encoding')
         return value
 
     def printable_value(self, attr, value=_marker, attrtype=None,
@@ -342,11 +342,11 @@
             # internalinalized *and* formatted string such as schema
             # description...
             if props.get('internationalizable'):
-                value = self.req._(value)
+                value = self._cw._(value)
             attrformat = self.attr_metadata(attr, 'format')
             if attrformat:
                 return self.mtc_transform(value, attrformat, format,
-                                          self.req.encoding)
+                                          self._cw.encoding)
         elif attrtype == 'Bytes':
             attrformat = self.attr_metadata(attr, 'format')
             if attrformat:
@@ -354,7 +354,7 @@
                 return self.mtc_transform(value.getvalue(), attrformat, format,
                                           encoding)
             return u''
-        value = printable_value(self.req, attrtype, value, props,
+        value = printable_value(self._cw, attrtype, value, props,
                                 displaytime=displaytime)
         if format == 'text/html':
             value = xml_escape(value)
@@ -365,7 +365,7 @@
         trdata = TransformData(data, format, encoding, appobject=self)
         data = _engine.convert(trdata, target_format).decode()
         if format == 'text/html':
-            data = soup2xhtml(data, self.req.encoding)
+            data = soup2xhtml(data, self._cw.encoding)
         return data
 
     # entity cloning ##########################################################
@@ -377,7 +377,7 @@
         Overrides this if you want another behaviour
         """
         assert self.has_eid()
-        execute = self.req.execute
+        execute = self._cw.execute
         for rschema in self.e_schema.subject_relations():
             if rschema.is_final() or rschema.meta:
                 continue
@@ -422,7 +422,7 @@
         """returns a resultset containing `self` information"""
         rset = ResultSet([(self.eid,)], 'Any X WHERE X eid %(x)s',
                          {'x': self.eid}, [(self.__regid__,)])
-        return self.req.decorate_rset(rset)
+        return self._cw.decorate_rset(rset)
 
     def to_complete_relations(self):
         """by default complete final relations to when calling .complete()"""
@@ -434,7 +434,7 @@
                 # outer join correctly in this case
                 continue
             if rschema.inlined:
-                matching_groups = self.req.user.matching_groups
+                matching_groups = self._cw.user.matching_groups
                 if matching_groups(rschema.get_groups('read')) and \
                    all(matching_groups(es.get_groups('read'))
                        for es in rschema.objects(self.e_schema)):
@@ -449,7 +449,7 @@
             if attr == 'eid':
                 continue
             # password retreival is blocked at the repository server level
-            if not self.req.user.matching_groups(rschema.get_groups('read')) \
+            if not self._cw.user.matching_groups(rschema.get_groups('read')) \
                    or attrschema.type == 'Password':
                 self[attr] = None
                 continue
@@ -509,7 +509,7 @@
             # if some outer join are included to fetch inlined relations
             rql = 'Any %s,%s %s' % (V, ','.join(var for attr, var in selected),
                                     ','.join(rql))
-            execute = getattr(self.req, 'unsafe_execute', self.req.execute)
+            execute = getattr(self._cw, 'unsafe_execute', self._cw.execute)
             rset = execute(rql, {'x': self.eid}, 'x', build_descr=False)[0]
             # handle attributes
             for i in xrange(1, lastattr):
@@ -520,9 +520,9 @@
                 value = rset[i]
                 if value is None:
                     rrset = ResultSet([], rql, {'x': self.eid})
-                    self.req.decorate_rset(rrset)
+                    self._cw.decorate_rset(rrset)
                 else:
-                    rrset = self.req.eid_rset(value)
+                    rrset = self._cw.eid_rset(value)
                 self.set_related_cache(rtype, role, rrset)
 
     def get_value(self, name):
@@ -540,7 +540,7 @@
             rql = "Any A WHERE X eid %%(x)s, X %s A" % name
             # XXX should we really use unsafe_execute here? I think so (syt),
             # see #344874
-            execute = getattr(self.req, 'unsafe_execute', self.req.execute)
+            execute = getattr(self._cw, 'unsafe_execute', self._cw.execute)
             try:
                 rset = execute(rql, {'x': self.eid}, 'x')
             except Unauthorized:
@@ -555,7 +555,7 @@
                                   name, self.eid)
                     if self.e_schema.destination(name) == 'String':
                         # XXX (syt) imo emtpy string is better
-                        self[name] = value = self.req._('unaccessible')
+                        self[name] = value = self._cw._('unaccessible')
                     else:
                         self[name] = value = None
         return value
@@ -575,13 +575,13 @@
         rql = self.related_rql(rtype, role)
         # XXX should we really use unsafe_execute here? I think so (syt),
         # see #344874
-        execute = getattr(self.req, 'unsafe_execute', self.req.execute)
+        execute = getattr(self._cw, 'unsafe_execute', self._cw.execute)
         rset = execute(rql, {'x': self.eid}, 'x')
         self.set_related_cache(rtype, role, rset)
         return self.related(rtype, role, limit, entities)
 
     def related_rql(self, rtype, role='subject', targettypes=None):
-        rschema = self.req.vreg.schema[rtype]
+        rschema = self._cw.vreg.schema[rtype]
         if role == 'subject':
             if targettypes is None:
                 targettypes = rschema.objects(self.e_schema)
@@ -595,14 +595,14 @@
         if len(targettypes) > 1:
             fetchattrs_list = []
             for ttype in targettypes:
-                etypecls = self.vreg['etypes'].etype_class(ttype)
+                etypecls = self._cw.vreg['etypes'].etype_class(ttype)
                 fetchattrs_list.append(set(etypecls.fetch_attrs))
             fetchattrs = reduce(set.intersection, fetchattrs_list)
-            rql = etypecls.fetch_rql(self.req.user, [restriction], fetchattrs,
+            rql = etypecls.fetch_rql(self._cw.user, [restriction], fetchattrs,
                                      settype=False)
         else:
-            etypecls = self.vreg['etypes'].etype_class(targettypes[0])
-            rql = etypecls.fetch_rql(self.req.user, [restriction], settype=False)
+            etypecls = self._cw.vreg['etypes'].etype_class(targettypes[0])
+            rql = etypecls.fetch_rql(self._cw.user, [restriction], settype=False)
         # optimisation: remove ORDERBY if cardinality is 1 or ? (though
         # greater_card return 1 for those both cases)
         if card == '1':
@@ -626,7 +626,7 @@
         """
         ordermethod = ordermethod or 'fetch_unrelated_order'
         if isinstance(rtype, basestring):
-            rtype = self.req.vreg.schema.rschema(rtype)
+            rtype = self._cw.vreg.schema.rschema(rtype)
         if role == 'subject':
             evar, searchedvar = 'S', 'O'
             subjtype, objtype = self.e_schema, targettype
@@ -645,7 +645,7 @@
             args = {}
             securitycheck_args = {}
         insertsecurity = (rtype.has_local_role('add') and not
-                          rtype.has_perm(self.req, 'add', **securitycheck_args))
+                          rtype.has_perm(self._cw, 'add', **securitycheck_args))
         constraints = rtype.rproperty(subjtype, objtype, 'constraints')
         if vocabconstraints:
             # RQLConstraint is a subclass for RQLVocabularyConstraint, so they
@@ -655,8 +655,8 @@
         else:
             restriction += [cstr.restriction for cstr in constraints
                             if isinstance(cstr, RQLConstraint)]
-        etypecls = self.vreg['etypes'].etype_class(targettype)
-        rql = etypecls.fetch_rql(self.req.user, restriction,
+        etypecls = self._cw.vreg['etypes'].etype_class(targettype)
+        rql = etypecls.fetch_rql(self._cw.user, restriction,
                                  mainvar=searchedvar, ordermethod=ordermethod)
         # ensure we have an order defined
         if not ' ORDERBY ' in rql:
@@ -664,8 +664,8 @@
             rql = '%s ORDERBY %s WHERE %s' % (before, searchedvar, after)
         if insertsecurity:
             rqlexprs = rtype.get_rqlexprs('add')
-            rewriter = RQLRewriter(self.req)
-            rqlst = self.req.vreg.parse(self.req, rql, args)
+            rewriter = RQLRewriter(self._cw)
+            rqlst = self._cw.vreg.parse(self._cw, rql, args)
             for select in rqlst.children:
                 rewriter.rewrite(select, [((searchedvar, searchedvar), rqlexprs)],
                                  select.solutions, args)
@@ -680,11 +680,11 @@
         try:
             rql, args = self.unrelated_rql(rtype, targettype, role, ordermethod)
         except Unauthorized:
-            return self.req.empty_rset()
+            return self._cw.empty_rset()
         if limit is not None:
             before, after = rql.split(' WHERE ', 1)
             rql = '%s LIMIT %s WHERE %s' % (before, limit, after)
-        return self.req.execute(rql, args, tuple(args))
+        return self._cw.execute(rql, args, tuple(args))
 
     # relations cache handling ################################################
 
@@ -709,7 +709,7 @@
         """set cached values for the given relation"""
         if rset:
             related = list(rset.entities(col))
-            rschema = self.req.vreg.schema.rschema(rtype)
+            rschema = self._cw.vreg.schema.rschema(rtype)
             if role == 'subject':
                 rcard = rschema.rproperty(self.e_schema, related[0].e_schema,
                                           'cardinality')[1]
@@ -752,15 +752,15 @@
         # and now update the database
         kwargs['x'] = self.eid
         if _cw_unsafe:
-            self.req.unsafe_execute(
+            self._cw.unsafe_execute(
                 'SET %s WHERE X eid %%(x)s' % ','.join(relations), kwargs, 'x')
         else:
-            self.req.execute('SET %s WHERE X eid %%(x)s' % ','.join(relations),
+            self._cw.execute('SET %s WHERE X eid %%(x)s' % ','.join(relations),
                              kwargs, 'x')
 
     def delete(self):
         assert self.has_eid(), self.eid
-        self.req.execute('DELETE %s X WHERE X eid %%(x)s' % self.e_schema,
+        self._cw.execute('DELETE %s X WHERE X eid %%(x)s' % self.e_schema,
                          {'x': self.eid})
 
     # server side utilities ###################################################
@@ -779,10 +779,10 @@
         """
         # necessary since eid is handled specifically and yams require it to be
         # in the dictionary
-        if self.req is None:
+        if self._cw is None:
             _ = unicode
         else:
-            _ = self.req._
+            _ = self._cw._
         self.e_schema.check(self, creation=creation, _=_)
 
     def fti_containers(self, _done=None):
--- a/selectors.py	Wed Sep 23 09:29:39 2009 +0200
+++ b/selectors.py	Wed Sep 23 09:33:02 2009 +0200
@@ -637,7 +637,7 @@
           proximity so the most specific object'll be selected
     """
     def score_entity(self, entity):
-        return self.score_interfaces(entity.req, entity, entity.__class__)
+        return self.score_interfaces(entity._cw, entity, entity.__class__)
 
 
 class relation_possible(EClassSelector):
@@ -742,9 +742,9 @@
     def score_entity(self, entity):
         rschema = entity.schema.rschema(self.rtype)
         if self.role == 'subject':
-            if not rschema.has_perm(entity.req, 'add', fromeid=entity.eid):
+            if not rschema.has_perm(entity._cw, 'add', fromeid=entity.eid):
                 return 0
-        elif not rschema.has_perm(entity.req, 'add', toeid=entity.eid):
+        elif not rschema.has_perm(entity._cw, 'add', toeid=entity.eid):
             return 0
         return 1
 
@@ -795,7 +795,7 @@
 
     def score_entity(self, entity):
         relpossel = relation_possible(self.rtype, self.role, self.target_etype)
-        if not relpossel.score_class(entity.__class__, entity.req):
+        if not relpossel.score_class(entity.__class__, entity._cw):
             return 0
         rset = entity.related(self.rtype, self.role)
         if self.target_etype: