source: TI12-security/trunk/ndg_saml/ndg/saml/utils.py @ 6913

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/ndg_saml/ndg/saml/utils.py@6913
Revision 6913, 5.4 KB checked in by pjkersha, 10 years ago (diff)

Incomplete - task 6: Put NDG SAML package on PyPI

  • updating epydoc for 'etree' package
Line 
1"""Utilities module for NDG Security SAML implementation
2
3NERC DataGrid Project
4
5This implementation is adapted from the Java OpenSAML implementation.  The
6copyright and licence information are included here:
7
8Copyright [2005] [University Corporation for Advanced Internet Development, Inc.]
9
10Licensed under the Apache License, Version 2.0 (the "License");
11you may not use this file except in compliance with the License.
12You may obtain a copy of the License at
13
14http://www.apache.org/licenses/LICENSE-2.0
15
16Unless required by applicable law or agreed to in writing, software
17distributed under the License is distributed on an "AS IS" BASIS,
18WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19See the License for the specific language governing permissions and
20limitations under the License.
21"""
22__author__ = "P J Kershaw"
23__date__ = "10/08/09"
24__copyright__ = "(C) 2009 Science and Technology Facilities Council"
25__license__ = "http://www.apache.org/licenses/LICENSE-2.0"
26__contact__ = "Philip.Kershaw@stfc.ac.uk"
27__revision__ = '$Id$'
28try:
29    from datetime import strptime
30except ImportError:
31    # Allow for Python < 2.5
32    from time import strptime as _strptime
33    strptime = lambda datetimeStr, format: datetime(*(_strptime(datetimeStr, 
34                                                                format)[0:6]))
35from datetime import datetime, timedelta
36       
37       
38class SAMLDateTime(object):
39    """Generic datetime formatting utility for SAML timestamps - XMLSchema
40    Datetime format
41   
42    @cvar DATETIME_FORMAT: date/time format string for SAML timestamps
43    @type DATETIME_FORMAT: string
44    """
45    DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
46   
47    @classmethod
48    def toString(cls, dtValue):
49        """Convert issue instant datetime to correct string type for output
50       
51        @type dtValue: datetime.datetime
52        @param dtValue: issue instance as a datetime
53        @rtype: basestring
54        @return: issue instance as a string
55        """
56        if not isinstance(dtValue, datetime):
57            raise TypeError("Expecting datetime type for string conversion, "
58                            "got %r" % dtValue)
59           
60        # isoformat provides the correct formatting
61#        return dtIssueInstant.strftime(cls.DATETIME_FORMAT)
62        return datetime.isoformat(dtValue)+'Z'
63
64    @classmethod
65    def fromString(cls, strDateTime):
66        """Convert issue instant string to datetime type
67       
68        @type strDateTime: basestring
69        @param strDateTime: issue instance as a string
70        @rtype: datetime.datetime
71        @return: issue instance as a datetime
72        """
73        if not isinstance(strDateTime, basestring):
74            raise TypeError("Expecting basestring derived type for string "
75                            "conversion, got %r" % strDateTime)
76       
77        # Workaround for seconds fraction as strptime doesn't seem able to deal
78        # with this
79        strDateTimeFraction, strSecondsFraction = strDateTime.split('.')
80        dtValue = datetime.strptime(strDateTimeFraction, cls.DATETIME_FORMAT)
81        secondsFraction = float("0." + strSecondsFraction.replace('Z', ''))
82        dtValue += timedelta(seconds=secondsFraction)
83        return dtValue
84
85
86class TypedList(list):
87    """Extend list type to enabled only items of a given type.  Supports
88    any type where the array type in the Standard Library is restricted to
89    only limited set of primitive types
90    """
91   
92    def __init__(self, elementType, *arg, **kw):
93        """
94        @type elementType: type/tuple
95        @param elementType: object type or types which the list is allowed to
96        contain.  If more than one type, pass as a tuple
97        """
98        self.__elementType = elementType
99        super(TypedList, self).__init__(*arg, **kw)
100   
101    def _getElementType(self):
102        """@return: element type for this list
103        @rtype: type
104        """
105        return self.__elementType
106   
107    elementType = property(fget=_getElementType, 
108                           doc="The allowed type or types for list elements")
109     
110    def extend(self, iter):
111        """Extend an existing list with the input iterable
112        @param iter: iterable to extend list with
113        @type iter: iterable
114        """
115        for i in iter:
116            if not isinstance(i, self.__elementType):
117                raise TypeError("List items must be of type %s" % 
118                                (self.__elementType,))
119               
120        return super(TypedList, self).extend(iter)
121       
122    def __iadd__(self, iter):
123        """Extend an existing list with the input iterable with += operator
124       
125        @param iter: iterable to extend list with
126        @type iter: iterable
127        """
128        for i in iter:
129            if not isinstance(i, self.__elementType):
130                raise TypeError("List items must be of type %s" % 
131                                (self.__elementType,))
132                   
133        return super(TypedList, self).__iadd__(iter)
134         
135    def append(self, item):
136        """Append a list with the given item
137       
138        @param item: item to extend list
139        @type item: must agree witj "elementType" attribute of this list
140        """
141        if not isinstance(item, self.__elementType):
142                raise TypeError("List items must be of type %s" % 
143                                (self.__elementType,))
144   
145        return super(TypedList, self).append(item)
Note: See TracBrowser for help on using the repository browser.