Back to index

plone3  3.1.7
Classes | Functions | Variables
Archetypes.utils Namespace Reference

Classes

class  DisplayList
class  IntDisplayList
class  Vocabulary
class  OrderedDict

Functions

def makeBridgeMaker
def make_uuid
def uuid_gen
def kernel_make_uuid
def fixSchema
def mapply
def className
def productDir
def pathFor
def capitalize
def findDict
def basename
def unique
def getRelPath
def getRelURL
def getPkgInfo
def shasattr
def isWrapperMethod
def call_original
def wrap_method
def unwrap_method
def _get_position_after
def insert_zmi_tab_before
def insert_zmi_tab_after
def _getSecurity
def mergeSecurity
def setSecurity
def contentDispositionHeader
def addStatusMessage

Variables

string KERNEL_UUID = '/proc/sys/kernel/random/uuid'
 HAS_KERNEL_UUID = True
tuple uid_gen = uuid_gen()
 kernel_make_uuid = make_uuid
list _marker = []
string WRAPPER = '__at_is_wrapper_method__'
string ORIG_NAME = '__at_original_method_name__'

Function Documentation

def Archetypes.utils._get_position_after (   label,
  options 
) [private]

Definition at line 840 of file utils.py.

00840 
00841 def _get_position_after(label, options):
00842     position = 0
00843     for item in options:
00844         if item['label'] != label:
00845             continue
00846         position += 1
00847     return position

Here is the caller graph for this function:

def Archetypes.utils._getSecurity (   klass,
  create = True 
) [private]

Definition at line 860 of file utils.py.

00860 
00861 def _getSecurity(klass, create=True):
00862     # a Zope 2 class can contain some attribute that is an instance
00863     # of ClassSecurityInfo. Zope 2 scans through things looking for
00864     # an attribute that has the name __security_info__ first
00865     info = vars(klass)
00866     security = None
00867     for k, v in info.items():
00868         if hasattr(v, '__security_info__'):
00869             security = v
00870             break
00871     # Didn't found a ClassSecurityInfo object
00872     if security is None:
00873         if not create:
00874             return None
00875         # we stuff the name ourselves as __security__, not security, as this
00876         # could theoretically lead to name clashes, and doesn't matter for
00877         # zope 2 anyway.
00878         security = ClassSecurityInfo()
00879         setattr(klass, '__security__', security)
00880         if DEBUG_SECURITY:
00881             print '%s has no ClassSecurityObject' % klass.__name__
00882     return security

Here is the caller graph for this function:

def Archetypes.utils.addStatusMessage (   request,
  message,
  type = 'info' 
)
Add a status message to the request.

Definition at line 974 of file utils.py.

00974 
00975 def addStatusMessage(request, message, type='info'):
00976     """Add a status message to the request.
00977     """
00978     IStatusMessage(request).addStatusMessage(message, type=type)

Here is the caller graph for this function:

def Archetypes.utils.basename (   path)

Definition at line 197 of file utils.py.

00197 
00198 def basename(path):
00199     return path[max(path.rfind('\\'), path.rfind('/'))+1:]

Here is the caller graph for this function:

def Archetypes.utils.call_original (   self,
  __name__,
  __pattern__,
  args,
  kw 
)

Definition at line 816 of file utils.py.

00816 
00817 def call_original(self, __name__, __pattern__, *args, **kw):
00818     return getattr(self, __pattern__ % __name__)(*args, **kw)

def Archetypes.utils.capitalize (   string)

Definition at line 183 of file utils.py.

00183 
00184 def capitalize(string):
00185     if string[0].islower():
00186         string = string[0].upper() + string[1:]
00187     return string

Here is the caller graph for this function:

def Archetypes.utils.className (   klass)

Definition at line 165 of file utils.py.

00165 
00166 def className(klass):
00167     if type(klass) not in [ClassType, ExtensionClass]:
00168         klass = klass.__class__
00169     return "%s.%s" % (klass.__module__, klass.__name__)

def Archetypes.utils.contentDispositionHeader (   disposition,
  charset = 'utf-8',
  language = None,
  kw 
)
Return a properly quoted disposition header

Originally from CMFManagedFile/content.py.
charset default changed to utf-8 for consistency with the rest of Archetypes.

Definition at line 945 of file utils.py.

00945 
00946 def contentDispositionHeader(disposition, charset='utf-8', language=None, **kw):
00947     """Return a properly quoted disposition header
00948 
00949     Originally from CMFManagedFile/content.py.
00950     charset default changed to utf-8 for consistency with the rest of Archetypes.
00951     """
00952 
00953     from email.Message import Message as emailMessage
00954 
00955     for key, value in kw.items():
00956         # stringify the value
00957         if isinstance(value, unicode):
00958             value = value.encode(charset)
00959         else:
00960             value = str(value)
00961             # raise an error if the charset doesn't match
00962             unicode(value, charset, 'strict')
00963         # if any value contains 8-bit chars, make it an
00964         # encoding 3-tuple for special treatment by
00965         # Message.add_header() (actually _formatparam())
00966         try:
00967             unicode(value, 'us-ascii', 'strict')
00968         except UnicodeDecodeError:
00969             value = (charset, language, value)
00970 
00971     m = emailMessage()
00972     m.add_header('content-disposition', disposition, **kw)
00973     return m['content-disposition']

Here is the caller graph for this function:

def Archetypes.utils.findDict (   listofDicts,
  key,
  value 
)

Definition at line 188 of file utils.py.

00188 
00189 def findDict(listofDicts, key, value):
00190     #Look at a list of dicts for one where key == value
00191     for d in listofDicts:
00192         if d.has_key(key):
00193             if d[key] == value:
00194                 return d
00195     return None
00196 

Here is the caller graph for this function:

def Archetypes.utils.fixSchema (   schema)
Fix persisted schema from AT < 1.3 (UserDict-based)
to work with the new fixed order schema.

Definition at line 73 of file utils.py.

00073 
00074 def fixSchema(schema):
00075     """Fix persisted schema from AT < 1.3 (UserDict-based)
00076     to work with the new fixed order schema."""
00077     from Products.Archetypes.Schema import Schemata
00078     if not hasattr(aq_base(schema), '_fields'):
00079         fields = schema.data.values()
00080         Schemata.__init__(schema, fields)
00081         del schema.data
00082     return schema

Here is the caller graph for this function:

def Archetypes.utils.getPkgInfo (   product)
Get the __pkginfo__ from a product

chdir before importing the product

Definition at line 756 of file utils.py.

00756 
00757 def getPkgInfo(product):
00758     """Get the __pkginfo__ from a product
00759 
00760     chdir before importing the product
00761     """
00762     prd_home = product.__path__[0]
00763     cur_dir = os.path.abspath(os.curdir)
00764     os.chdir(prd_home)
00765     pkg = __import__('%s.__pkginfo__' % product.__name__, product, product,
00766                       ['__pkginfo__'])
00767     os.chdir(cur_dir)
00768     return pkg

def Archetypes.utils.getRelPath (   self,
  ppath 
)
take something with context (self) and a physical path as a
tuple, return the relative path for the portal

Definition at line 745 of file utils.py.

00745 
00746 def getRelPath(self, ppath):
00747     """take something with context (self) and a physical path as a
00748     tuple, return the relative path for the portal"""
00749     urlTool = getToolByName(self, 'portal_url')
00750     portal_path = urlTool.getPortalObject().getPhysicalPath()
00751     ppath = ppath[len(portal_path):]
00752     return ppath

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.utils.getRelURL (   self,
  ppath 
)

Definition at line 753 of file utils.py.

00753 
00754 def getRelURL(self, ppath):
00755     return '/'.join(getRelPath(self, ppath))

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.utils.insert_zmi_tab_after (   label,
  new_option,
  options 
)

Definition at line 854 of file utils.py.

00854 
00855 def insert_zmi_tab_after(label, new_option, options):
00856     _options = list(options)
00857     position = _get_position_after(label, options)
00858     _options.insert(position, new_option)
00859     return tuple(_options)

Here is the call graph for this function:

def Archetypes.utils.insert_zmi_tab_before (   label,
  new_option,
  options 
)

Definition at line 848 of file utils.py.

00848 
00849 def insert_zmi_tab_before(label, new_option, options):
00850     _options = list(options)
00851     position = _get_position_after(label, options)
00852     _options.insert(position-1, new_option)
00853     return tuple(_options)

Here is the call graph for this function:

Definition at line 813 of file utils.py.

00813 
00814 def isWrapperMethod(meth):
00815     return getattr(meth, WRAPPER, False)

Here is the caller graph for this function:

Definition at line 66 of file utils.py.

00066 
00067     def kernel_make_uuid(*args):
00068         return uid_gen.next()
else:

Definition at line 46 of file utils.py.

00046 
00047 def make_uuid(*args):
00048     t = str(time() * 1000L)
00049     r = str(random()*100000000000000000L)
00050     data = t +' '+ r +' '+ _v_network +' '+ str(args)
00051     uid = md5(data).hexdigest()
00052     return uid
00053 
# linux kernel uid generator. It's a little bit slower but a little bit better

Here is the caller graph for this function:

Definition at line 30 of file utils.py.

00030 
00031 def makeBridgeMaker(func):
00032     def makeBridge(*args):
00033         module=args[0]
00034         ifaces = args[1:]
00035         for iface in ifaces:
00036             func(iface, module, iface.__name__)
00037     return makeBridge
00038 
00039 makeZ2Bridges=makeBridgeMaker(createZope2Bridge)
00040 makeZ3Bridges=makeBridgeMaker(createZope3Bridge)
00041 
00042 try:
00043     _v_network = str(socket.gethostbyname(socket.gethostname()))
00044 except:
00045     _v_network = str(random() * 100000000000000000L)

def Archetypes.utils.mapply (   method,
  args,
  kw 
)
Inspect function and apply positional and keyword arguments as possible.

Add more examples.

>>> def f(a, b, c=2, d=3):
...     print a, b, c, d

>>> mapply(f, *(1, 2), **{'d':4})
1 2 2 4

>>> mapply(f, *(1, 2), **{'c':3})
1 2 3 3

>>> mapply(f, *(1, 2), **{'j':3})
1 2 2 3

>>> def f(a, b):
...     print a, b

>>> mapply(f, *(1, 2), **{'j':3})
1 2

>>> def f(a, b=2):
...     print a, b

>>> mapply(f, *(1,), **{'j':3})
1 2

>>> mapply(f, *(1,), **{'j':3})
1 2

TODO Should raise an exception 'Multiple values for argument' here.

>>> mapply(f, *(1,), **{'a':3})
1 2

>>> mapply(f, *(1,), **{'b':3})
1 3

>>> def f(a=1, b=2):
...     print a, b

>>> mapply(f, *(), **{'b':3})
1 3

>>> mapply(f, *(), **{'a':3})
3 2

Definition at line 85 of file utils.py.

00085 
00086 def mapply(method, *args, **kw):
00087     """ Inspect function and apply positional and keyword arguments as possible.
00088 
00089     Add more examples.
00090 
00091     >>> def f(a, b, c=2, d=3):
00092     ...     print a, b, c, d
00093 
00094     >>> mapply(f, *(1, 2), **{'d':4})
00095     1 2 2 4
00096 
00097     >>> mapply(f, *(1, 2), **{'c':3})
00098     1 2 3 3
00099 
00100     >>> mapply(f, *(1, 2), **{'j':3})
00101     1 2 2 3
00102 
00103     >>> def f(a, b):
00104     ...     print a, b
00105 
00106     >>> mapply(f, *(1, 2), **{'j':3})
00107     1 2
00108 
00109     >>> def f(a, b=2):
00110     ...     print a, b
00111 
00112     >>> mapply(f, *(1,), **{'j':3})
00113     1 2
00114 
00115     >>> mapply(f, *(1,), **{'j':3})
00116     1 2
00117 
00118     TODO Should raise an exception 'Multiple values for argument' here.
00119 
00120     >>> mapply(f, *(1,), **{'a':3})
00121     1 2
00122 
00123     >>> mapply(f, *(1,), **{'b':3})
00124     1 3
00125 
00126     >>> def f(a=1, b=2):
00127     ...     print a, b
00128 
00129     >>> mapply(f, *(), **{'b':3})
00130     1 3
00131 
00132     >>> mapply(f, *(), **{'a':3})
00133     3 2
00134     """
00135     m = method
00136     if hasattr(m, 'im_func'):
00137         m = m.im_func
00138     code = m.func_code
00139     fn_args = getargs(code)
00140     call_args = list(args)
00141     if fn_args[1] is not None and fn_args[2] is not None:
00142         return method(*args, **kw)
00143     if fn_args[1] is None:
00144         if len(call_args) > len(fn_args[0]):
00145             call_args = call_args[:len(fn_args[0])]
00146     nkw = {}
00147     if len(call_args) < len(fn_args[0]):
00148         for arg in fn_args[0][len(call_args):]:
00149             value = kw.get(arg, _marker)
00150             if value is not _marker:
00151                 nkw[arg] = value
00152                 del kw[arg]
00153     largs = len(call_args) + len(nkw.keys())
00154     if largs < len(fn_args[0]):
00155         for arg in fn_args[0][largs:]:
00156             value = kw.get(arg, _marker)
00157             if value is not _marker:
00158                 call_args.append(value)
00159                 del kw[arg]
00160     if fn_args[2] is not None:
00161         return method(*call_args, **kw)
00162     if fn_args[0]:
00163         return method(*call_args, **nkw)
00164     return method()

Here is the caller graph for this function:

Definition at line 883 of file utils.py.

00883 
00884 def mergeSecurity(klass):
00885     # This method looks into all the base classes and tries to
00886     # merge the security declarations into the current class.
00887     # Not needed in normal circumstances, but useful for debugging.
00888     bases = list(getmro(klass))
00889     bases.reverse()
00890     security = _getSecurity(klass)
00891     for base in bases[:-1]:
00892         s = _getSecurity(base, create=False)
00893         if s is not None:
00894             if DEBUG_SECURITY:
00895                 print base, s.names, s.roles
00896             # Apply security from the base classes to this one
00897             s.apply(klass)
00898             continue
00899         cdict = vars(base)
00900         b_perms = cdict.get('__ac_permissions__', ())
00901         if b_perms and DEBUG_SECURITY:
00902             print base, b_perms
00903         for item in b_perms:
00904             permission_name = item[0]
00905             security._setaccess(item[1], permission_name)
00906             if len(item) > 2:
00907                 security.setPermissionDefault(permission_name, item[2])
00908         roles = [(k, v) for k, v in cdict.items() if k.endswith('__roles__')]
00909         for k, v in roles:
00910             name = k[:-9]
00911             security.names[name] = v

Here is the call graph for this function:

def Archetypes.utils.pathFor (   path = None,
  file = None 
)

Definition at line 174 of file utils.py.

00174 
00175 def pathFor(path=None, file=None):
00176     base = productDir()
00177     if path:
00178         base = os.path.join(base, path)
00179     if file:
00180         base = os.path.join(base, file)
00181 
00182     return base

Here is the call graph for this function:

Definition at line 170 of file utils.py.

00170 
00171 def productDir():
00172     module = sys.modules[__name__]
00173     return os.path.dirname(module.__file__)

Here is the caller graph for this function:

def Archetypes.utils.setSecurity (   klass,
  defaultAccess = None,
  objectPermission = None 
)
Set security of classes

* Adds ClassSecurityInfo if necessary
* Sets default access ('deny' or 'allow')
* Sets permission of objects

Definition at line 912 of file utils.py.

00912 
00913 def setSecurity(klass, defaultAccess=None, objectPermission=None):
00914     """Set security of classes
00915 
00916     * Adds ClassSecurityInfo if necessary
00917     * Sets default access ('deny' or 'allow')
00918     * Sets permission of objects
00919     """
00920     security = _getSecurity(klass)
00921     if defaultAccess:
00922         security.setDefaultAccess(defaultAccess)
00923     if objectPermission:
00924         if objectPermission == 'public':
00925             security.declareObjectPublic()
00926         elif objectPermission == 'private':
00927             security.declareObjectPrivate()
00928         else:
00929             security.declareObjectProtected(objectPermission)
00930 
00931     InitializeClass(klass)
00932 
00933     if DEBUG_SECURITY:
00934         if getattr(klass, '__allow_access_to_unprotected_subobjects__', False):
00935             print '%s: Unprotected access is allowed: %s' % (
00936                   klass.__name__, klass.__allow_access_to_unprotected_subobjects__)
00937         for name in klass.__dict__.keys():
00938             method = getattr(klass, name)
00939             if name.startswith('_') or type(method) != MethodType:
00940                 continue
00941             if not security.names.has_key(name):
00942                 print '%s.%s has no security' % (klass.__name__, name)
00943             elif security.names.get(name) is ACCESS_PUBLIC:
00944                 print '%s.%s is public' % (klass.__name__, name)

Here is the call graph for this function:

Here is the caller graph for this function:

def Archetypes.utils.shasattr (   obj,
  attr,
  acquire = False 
)
Safe has attribute method

* It's acquisition safe by default because it's removing the acquisition
  wrapper before trying to test for the attribute.

* It's not using hasattr which might swallow a ZODB ConflictError (actually
  the implementation of hasattr is swallowing all exceptions). Instead of
  using hasattr it's comparing the output of getattr with a special marker
  object.

TODO the getattr() trick can be removed when Python's hasattr() is fixed to
catch only AttributeErrors.

Quoting Shane Hathaway:

That said, I was surprised to discover that Python 2.3 implements hasattr
this way (from bltinmodule.c):

        v = PyObject_GetAttr(v, name);
        if (v == NULL) {
                PyErr_Clear();
                Py_INCREF(Py_False);
                return Py_False;
        }
    Py_DECREF(v);
    Py_INCREF(Py_True);
    return Py_True;

It should not swallow all errors, especially now that descriptors make
computed attributes quite common.  getattr() only recently started catching
only AttributeErrors, but apparently hasattr is lagging behind.  I suggest
the consistency between getattr and hasattr should be fixed in Python, not
Zope.

Shane

Definition at line 769 of file utils.py.

00769 
00770 def shasattr(obj, attr, acquire=False):
00771     """Safe has attribute method
00772 
00773     * It's acquisition safe by default because it's removing the acquisition
00774       wrapper before trying to test for the attribute.
00775 
00776     * It's not using hasattr which might swallow a ZODB ConflictError (actually
00777       the implementation of hasattr is swallowing all exceptions). Instead of
00778       using hasattr it's comparing the output of getattr with a special marker
00779       object.
00780 
00781     TODO the getattr() trick can be removed when Python's hasattr() is fixed to
00782     catch only AttributeErrors.
00783 
00784     Quoting Shane Hathaway:
00785 
00786     That said, I was surprised to discover that Python 2.3 implements hasattr
00787     this way (from bltinmodule.c):
00788 
00789             v = PyObject_GetAttr(v, name);
00790             if (v == NULL) {
00791                     PyErr_Clear();
00792                     Py_INCREF(Py_False);
00793                     return Py_False;
00794             }
00795         Py_DECREF(v);
00796         Py_INCREF(Py_True);
00797         return Py_True;
00798 
00799     It should not swallow all errors, especially now that descriptors make
00800     computed attributes quite common.  getattr() only recently started catching
00801     only AttributeErrors, but apparently hasattr is lagging behind.  I suggest
00802     the consistency between getattr and hasattr should be fixed in Python, not
00803     Zope.
00804 
00805     Shane
00806     """
00807     if not acquire:
00808         obj = aq_base(obj)
00809     return getattr(obj, attr, _marker) is not _marker
00810 

Return a list of the elements in s, but without duplicates.

For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
unique("abcabc") some permutation of ["a", "b", "c"], and
unique(([1, 2], [2, 3], [1, 2])) some permutation of
[[2, 3], [1, 2]].

For best speed, all sequence elements should be hashable.  Then
unique() will usually work in linear time.

If not possible, the sequence elements should enjoy a total
ordering, and if list(s).sort() doesn't raise TypeError it's
assumed that they do enjoy a total ordering.  Then unique() will
usually work in O(N*log2(N)) time.

If that's not possible either, the sequence elements must support
equality-testing.  Then unique() will usually work in quadratic
time.

Definition at line 200 of file utils.py.

00200 
00201 def unique(s):
00202     """Return a list of the elements in s, but without duplicates.
00203 
00204     For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
00205     unique("abcabc") some permutation of ["a", "b", "c"], and
00206     unique(([1, 2], [2, 3], [1, 2])) some permutation of
00207     [[2, 3], [1, 2]].
00208 
00209     For best speed, all sequence elements should be hashable.  Then
00210     unique() will usually work in linear time.
00211 
00212     If not possible, the sequence elements should enjoy a total
00213     ordering, and if list(s).sort() doesn't raise TypeError it's
00214     assumed that they do enjoy a total ordering.  Then unique() will
00215     usually work in O(N*log2(N)) time.
00216 
00217     If that's not possible either, the sequence elements must support
00218     equality-testing.  Then unique() will usually work in quadratic
00219     time.
00220     """
00221     # taken from ASPN Python Cookbook,
00222     # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
00223 
00224     n = len(s)
00225     if n == 0:
00226         return []
00227 
00228     # Try using a dict first, as that's the fastest and will usually
00229     # work.  If it doesn't work, it will usually fail quickly, so it
00230     # usually doesn't cost much to *try* it.  It requires that all the
00231     # sequence elements be hashable, and support equality comparison.
00232     u = {}
00233     try:
00234         for x in s:
00235             u[x] = 1
00236     except TypeError:
00237         del u  # move on to the next method
00238     else:
00239         return u.keys()
00240 
00241     # We can't hash all the elements.  Second fastest is to sort,
00242     # which brings the equal elements together; then duplicates are
00243     # easy to weed out in a single pass.
00244     # NOTE:  Python's list.sort() was designed to be efficient in the
00245     # presence of many duplicate elements.  This isn't true of all
00246     # sort functions in all languages or libraries, so this approach
00247     # is more effective in Python than it may be elsewhere.
00248     try:
00249         t = list(s)
00250         t.sort()
00251     except TypeError:
00252         del t  # move on to the next method
00253     else:
00254         assert n > 0
00255         last = t[0]
00256         lasti = i = 1
00257         while i < n:
00258             if t[i] != last:
00259                 t[lasti] = last = t[i]
00260                 lasti += 1
00261             i += 1
00262         return t[:lasti]
00263 
00264     # Brute force is all that's left.
00265     u = []
00266     for x in s:
00267         if x not in u:
00268             u.append(x)
00269     return u
00270 
00271 

def Archetypes.utils.unwrap_method (   klass,
  name 
)

Definition at line 830 of file utils.py.

00830 
00831 def unwrap_method(klass, name):
00832     old_method = getattr(klass, name)
00833     if not isWrapperMethod(old_method):
00834         raise ValueError, ('Non-wrapped method %s.%s' % (klass.__name__, name))
00835     orig_name = getattr(old_method, ORIG_NAME)
00836     new_method = getattr(klass, orig_name)
00837     delattr(klass, orig_name)
00838     setattr(klass, name, new_method)
00839 

Here is the call graph for this function:

Definition at line 58 of file utils.py.

00058 
00059     def uuid_gen():
00060         fp = open(KERNEL_UUID, 'r')
00061         while 1:
00062             uid = fp.read()[:-1]
00063             fp.seek(0)
            yield uid
def Archetypes.utils.wrap_method (   klass,
  name,
  method,
  pattern = '__at_wrapped_%s__' 
)

Definition at line 819 of file utils.py.

00819 
00820 def wrap_method(klass, name, method, pattern='__at_wrapped_%s__'):
00821     old_method = getattr(klass, name)
00822     if isWrapperMethod(old_method):
00823         log('Already wrapped method %s.%s. Skipping.' % (klass.__name__, name))
00824         return
00825     new_name = pattern % name
00826     setattr(klass, new_name, old_method)
00827     setattr(method, ORIG_NAME, new_name)
00828     setattr(method, WRAPPER, True)
00829     setattr(klass, name, method)

Here is the call graph for this function:


Variable Documentation

Definition at line 83 of file utils.py.

Definition at line 57 of file utils.py.

Definition at line 70 of file utils.py.

string Archetypes.utils.KERNEL_UUID = '/proc/sys/kernel/random/uuid'

Definition at line 54 of file utils.py.

string Archetypes.utils.ORIG_NAME = '__at_original_method_name__'

Definition at line 812 of file utils.py.

Definition at line 64 of file utils.py.

string Archetypes.utils.WRAPPER = '__at_is_wrapper_method__'

Definition at line 811 of file utils.py.