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

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

Incomplete - task 6: Put NDG SAML package on PyPI

  • add documentation folder and Makefile for epydoc
  • updating epydoc for all modules and packages.
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    DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
43   
44    @classmethod
45    def toString(cls, dtValue):
46        """Convert issue instant datetime to correct string type for output
47        @type dtValue: datetime.datetime
48        @param dtValue: issue instance as a datetime
49        @rtype: basestring
50        @return: issue instance as a string
51        """
52        if not isinstance(dtValue, datetime):
53            raise TypeError("Expecting datetime type for string conversion, "
54                            "got %r" % dtValue)
55           
56        # isoformat provides the correct formatting
57#        return dtIssueInstant.strftime(cls.DATETIME_FORMAT)
58        return datetime.isoformat(dtValue)+'Z'
59
60    @classmethod
61    def fromString(cls, strDateTime):
62        """Convert issue instant string to datetime type
63        @type strDateTime: basestring
64        @param strDateTime: issue instance as a string
65        @rtype: datetime.datetime
66        @return: issue instance as a datetime
67        """
68        if not isinstance(strDateTime, basestring):
69            raise TypeError("Expecting basestring derived type for string "
70                            "conversion, got %r" % strDateTime)
71       
72        # Workaround for seconds fraction as strptime doesn't seem able to deal
73        # with this
74        strDateTimeFraction, strSecondsFraction = strDateTime.split('.')
75        dtValue = datetime.strptime(strDateTimeFraction, cls.DATETIME_FORMAT)
76        secondsFraction = float("0." + strSecondsFraction.replace('Z', ''))
77        dtValue += timedelta(seconds=secondsFraction)
78        return dtValue
79
80
81class TypedList(list):
82    """Extend list type to enabled only items of a given type.  Supports
83    any type where the array type in the Standard Library is restricted to
84    only limited set of primitive types
85    """
86   
87    def __init__(self, elementType, *arg, **kw):
88        """
89        @type elementType: type/tuple
90        @param elementType: object type or types which the list is allowed to
91        contain.  If more than one type, pass as a tuple
92        """
93        self.__elementType = elementType
94        super(TypedList, self).__init__(*arg, **kw)
95   
96    def _getElementType(self):
97        return self.__elementType
98   
99    elementType = property(fget=_getElementType, 
100                           doc="The allowed type or types for list elements")
101     
102    def extend(self, iter):
103        for i in iter:
104            if not isinstance(i, self.__elementType):
105                raise TypeError("List items must be of type %s" % 
106                                (self.__elementType,))
107               
108        return super(TypedList, self).extend(iter)
109       
110    def __iadd__(self, iter):
111        for i in iter:
112            if not isinstance(i, self.__elementType):
113                raise TypeError("List items must be of type %s" % 
114                                (self.__elementType,))
115                   
116        return super(TypedList, self).__iadd__(iter)
117         
118    def append(self, item):
119        if not isinstance(item, self.__elementType):
120                raise TypeError("List items must be of type %s" % 
121                                (self.__elementType,))
122   
123        return super(TypedList, self).append(item)
Note: See TracBrowser for help on using the repository browser.