oidutil.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. """This module contains general utility code that is used throughout
  2. the library.
  3. For users of this library, the C{L{log}} function is probably the most
  4. interesting.
  5. """
  6. __all__ = ['log', 'appendArgs', 'toBase64', 'fromBase64', 'autoSubmitHTML']
  7. import binascii
  8. import sys
  9. import urlparse
  10. from urllib import urlencode
  11. elementtree_modules = [
  12. 'lxml.etree',
  13. 'xml.etree.cElementTree',
  14. 'xml.etree.ElementTree',
  15. 'cElementTree',
  16. 'elementtree.ElementTree',
  17. ]
  18. def autoSubmitHTML(form, title='OpenID transaction in progress'):
  19. return """
  20. <html>
  21. <head>
  22. <title>%s</title>
  23. </head>
  24. <body onload="document.forms[0].submit();">
  25. %s
  26. <script>
  27. var elements = document.forms[0].elements;
  28. for (var i = 0; i < elements.length; i++) {
  29. elements[i].style.display = "none";
  30. }
  31. </script>
  32. </body>
  33. </html>
  34. """ % (title, form)
  35. def importElementTree(module_names=None):
  36. """Find a working ElementTree implementation, trying the standard
  37. places that such a thing might show up.
  38. >>> ElementTree = importElementTree()
  39. @param module_names: The names of modules to try to use as
  40. ElementTree. Defaults to C{L{elementtree_modules}}
  41. @returns: An ElementTree module
  42. """
  43. if module_names is None:
  44. module_names = elementtree_modules
  45. for mod_name in module_names:
  46. try:
  47. ElementTree = __import__(mod_name, None, None, ['unused'])
  48. except ImportError:
  49. pass
  50. else:
  51. # Make sure it can actually parse XML
  52. try:
  53. ElementTree.XML('<unused/>')
  54. except (SystemExit, MemoryError, AssertionError):
  55. raise
  56. except:
  57. why = sys.exc_info()[1]
  58. log('Not using ElementTree library %r because it failed to '
  59. 'parse a trivial document: %s' % (mod_name, why))
  60. else:
  61. return ElementTree
  62. else:
  63. raise ImportError('No ElementTree library found. '
  64. 'You may need to install one. '
  65. 'Tried importing %r' % (module_names,)
  66. )
  67. def log(message, level=0):
  68. """Handle a log message from the OpenID library.
  69. This implementation writes the string it to C{sys.stderr},
  70. followed by a newline.
  71. Currently, the library does not use the second parameter to this
  72. function, but that may change in the future.
  73. To install your own logging hook::
  74. from openid import oidutil
  75. def myLoggingFunction(message, level):
  76. ...
  77. oidutil.log = myLoggingFunction
  78. @param message: A string containing a debugging message from the
  79. OpenID library
  80. @type message: str
  81. @param level: The severity of the log message. This parameter is
  82. currently unused, but in the future, the library may indicate
  83. more important information with a higher level value.
  84. @type level: int or None
  85. @returns: Nothing.
  86. """
  87. sys.stderr.write(message)
  88. sys.stderr.write('\n')
  89. def appendArgs(url, args):
  90. """Append query arguments to a HTTP(s) URL. If the URL already has
  91. query arguemtns, these arguments will be added, and the existing
  92. arguments will be preserved. Duplicate arguments will not be
  93. detected or collapsed (both will appear in the output).
  94. @param url: The url to which the arguments will be appended
  95. @type url: str
  96. @param args: The query arguments to add to the URL. If a
  97. dictionary is passed, the items will be sorted before
  98. appending them to the URL. If a sequence of pairs is passed,
  99. the order of the sequence will be preserved.
  100. @type args: A dictionary from string to string, or a sequence of
  101. pairs of strings.
  102. @returns: The URL with the parameters added
  103. @rtype: str
  104. """
  105. if hasattr(args, 'items'):
  106. args = args.items()
  107. args.sort()
  108. else:
  109. args = list(args)
  110. if len(args) == 0:
  111. return url
  112. if '?' in url:
  113. sep = '&'
  114. else:
  115. sep = '?'
  116. # Map unicode to UTF-8 if present. Do not make any assumptions
  117. # about the encodings of plain bytes (str).
  118. i = 0
  119. for k, v in args:
  120. if type(k) is not str:
  121. k = k.encode('UTF-8')
  122. if type(v) is not str:
  123. v = v.encode('UTF-8')
  124. args[i] = (k, v)
  125. i += 1
  126. return '%s%s%s' % (url, sep, urlencode(args))
  127. def toBase64(s):
  128. """Represent string s as base64, omitting newlines"""
  129. return binascii.b2a_base64(s)[:-1]
  130. def fromBase64(s):
  131. try:
  132. return binascii.a2b_base64(s)
  133. except binascii.Error, why:
  134. # Convert to a common exception type
  135. raise ValueError(why[0])
  136. class Symbol(object):
  137. """This class implements an object that compares equal to others
  138. of the same type that have the same name. These are distict from
  139. str or unicode objects.
  140. """
  141. def __init__(self, name):
  142. self.name = name
  143. def __eq__(self, other):
  144. return type(self) is type(other) and self.name == other.name
  145. def __ne__(self, other):
  146. return not (self == other)
  147. def __hash__(self):
  148. return hash((self.__class__, self.name))
  149. def __repr__(self):
  150. return '<Symbol %s>' % (self.name,)