Compatibility fixes.
authorRadek Czajka <rczajka@rczajka.pl>
Sun, 21 Sep 2014 20:34:09 +0000 (22:34 +0200)
committerRadek Czajka <rczajka@rczajka.pl>
Sun, 21 Sep 2014 20:34:53 +0000 (22:34 +0200)
* Use unicode_literals thoughout the package.
* Add indexes to '{}'.format(), unindexed version unsupported in Py2.6.
* Remove remnants of Python 2.5 support (Django 1.5 is required anyway).
* Stop relying on `hasattr` on OneToOneField, won't work on Python 3.2 + Django 1.6
  (see https://code.djangoproject.com/ticket/21563).

13 files changed:
cas_provider/__init__.py
cas_provider/admin.py
cas_provider/attribute_formatters.py
cas_provider/exceptions.py
cas_provider/forms.py
cas_provider/management/commands/cleanuptickets.py
cas_provider/models.py
cas_provider/signals.py
cas_provider/urls.py
cas_provider/views.py
cas_provider_examples/manage.py
cas_provider_examples/simple/settings.py
cas_provider_examples/simple/urls.py

index 22cedc3..ff16364 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from django.conf import settings
 
 __all__ = []
index 90182e2..075fcb9 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from django.contrib import admin
 from .models import *
 
index b06cd84..8574962 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from lxml import etree
 import collections
 
@@ -15,7 +17,7 @@ except NameError:
 def jasig(auth_success, attrs):
     attributes = etree.SubElement(auth_success, CAS + 'attributes')
     style = etree.SubElement(attributes, CAS + 'attraStyle')
-    style.text = u'Jasig'
+    style.text = 'Jasig'
     for name, value in sorted(attrs.items()):
         if isinstance(value, collections.Iterable) and not isinstance(value, basestring):
             for e in value:
@@ -28,7 +30,7 @@ def jasig(auth_success, attrs):
 
 def ruby_cas(auth_success, attrs):
     style = etree.SubElement(auth_success, CAS + 'attraStyle')
-    style.text = u'RubyCAS'
+    style.text = 'RubyCAS'
     for name, value in sorted(attrs.items()):
         if isinstance(value, collections.Iterable) and not isinstance(value, basestring):
             for e in value:
@@ -40,7 +42,7 @@ def ruby_cas(auth_success, attrs):
 
 
 def name_value(auth_success, attrs):
-    etree.SubElement(auth_success, CAS + 'attribute', name=u'attraStyle', value=u'Name-Value')
+    etree.SubElement(auth_success, CAS + 'attribute', name='attraStyle', value='Name-Value')
     for name, value in sorted(attrs.items()):
         if isinstance(value, collections.Iterable) and not isinstance(value, basestring):
             for e in value:
index 202eda8..fdb6251 100644 (file)
@@ -1,6 +1,7 @@
 # -*- coding: utf-8 -*-
 """cas_provider.exceptions -- exceptions defined for CAS login workflows
 """
+from __future__ import unicode_literals
 
 
 class SameEmailMismatchedPasswords(Exception): pass
index 7f3d5b6..e4df105 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from django import forms
 from django.utils.translation import ugettext_lazy as _
 
index c951993..994c766 100644 (file)
@@ -6,7 +6,7 @@ Calls ``ServiceTickets.objects.delete_expired_users()``, which
 contains the actual logic for determining which accounts are deleted.
 
 """
-from __future__ import print_function
+from __future__ import print_function, unicode_literals
 
 from django.core.management.base import NoArgsCommand
 from django.conf import settings
index 12fed4c..36014b5 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from django.conf import settings
 from django.db import models
 from django.utils.translation import ugettext_lazy as _
@@ -8,10 +10,7 @@ try:
 except ImportError:
     from urllib import urlencode
     from urlparse import urlparse, ParseResult
-    try:
-        from urlparse import parse_qs
-    except: # Python <2.6 compatibility
-        from cgi import parse_qs
+    from urlparse import parse_qs
 
 __all__ = ['ServiceTicket', 'LoginTicket', 'ProxyGrantingTicket', 'ProxyTicket', 'ProxyGrantingTicketIOU']
 
@@ -32,7 +31,7 @@ class BaseTicket(models.Model):
 
     def _generate_ticket(self, length=ticket.max_length, chars=string.ascii_letters + string.digits):
         """ Generates a random string of the requested length. Used for creation of tickets. """
-        return u"%s-%s" % (self.prefix, ''.join(Random().sample(chars, length - (len(self.prefix) + 1))))
+        return "%s-%s" % (self.prefix, ''.join(Random().sample(chars, length - (len(self.prefix) + 1))))
 
 
 class ServiceTicket(BaseTicket):
@@ -73,7 +72,7 @@ class ProxyGrantingTicket(BaseTicket):
 
     def __init__(self, *args, **kwargs):
         if 'pgtiou' not in kwargs:
-            kwargs['pgtiou'] = u"PGTIOU-%s" % (''.join(Random().sample(string.ascii_letters + string.digits, 50)))
+            kwargs['pgtiou'] = "PGTIOU-%s" % (''.join(Random().sample(string.ascii_letters + string.digits, 50)))
         super(ProxyGrantingTicket, self).__init__(*args, **kwargs)
 
     class Meta:
index ad366fd..3c469db 100644 (file)
@@ -1,6 +1,8 @@
 # -*- coding: utf-8 -*-
 """cas_provider.signals -- signal definitions for cas_provider
 """
+from __future__ import unicode_literals
+
 from django import dispatch
 
 
index a2f5fe7..fb59599 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from django.conf.urls import patterns, url
 
 
index 126e3d1..76bcbb2 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 import logging
 logger = logging.getLogger('cas_provider.views')
 
@@ -45,10 +47,10 @@ INVALID_REQUEST = 'INVALID_REQUEST'
 INTERNAL_ERROR = 'INTERNAL_ERROR'
 
 ERROR_MESSAGES = (
-    (INVALID_TICKET, u'The provided ticket is invalid.'),
-    (INVALID_SERVICE, u'Service is invalid'),
-    (INVALID_REQUEST, u'Not all required parameters were sent.'),
-    (INTERNAL_ERROR, u'An internal error occurred during ticket validation'),
+    (INVALID_TICKET, 'The provided ticket is invalid.'),
+    (INVALID_SERVICE, 'Service is invalid'),
+    (INVALID_REQUEST, 'Not all required parameters were sent.'),
+    (INTERNAL_ERROR, 'An internal error occurred during ticket validation'),
     )
 
 
@@ -273,8 +275,12 @@ def ticket_validate(service, ticket_string, pgtUrl):
         if pgt:
             pgtIouId = pgt.pgtiou
 
-    if hasattr(ticket, 'proxyticket'):
-        pgt = ticket.proxyticket.proxyGrantingTicket
+    try:
+        proxyTicket = ticket.proxyticket
+    except ProxyTicket.DoesNotExist:
+        pass
+    else:
+        pgt = proxyTicket.proxyGrantingTicket
         # I am issued by this proxy granting ticket
         while pgt.pgt is not None:
             proxies += (pgt.service,)
@@ -327,10 +333,10 @@ def generate_proxy_granting_ticket(pgt_url, ticket):
         urlopen(urlunsplit(uri))
     except HTTPError as e:
         if not e.code in proxy_callback_good_status:
-            logger.debug('Checking Proxy Callback URL {} returned {}. Not issuing PGT.'.format(uri, e.code))
+            logger.debug('Checking Proxy Callback URL {0} returned {1}. Not issuing PGT.'.format(uri, e.code))
             return
     except URLError as e:
-        logger.debug('Checking Proxy Callback URL {} raised URLError. Not issuing PGT.'.format(uri))
+        logger.debug('Checking Proxy Callback URL {0} raised URLError. Not issuing PGT.'.format(uri))
         return
 
     pgt.save()
@@ -346,7 +352,7 @@ def _cas2_sucess_response(user, pgt=None, proxies=None):
 
 
 def _cas2_error_response(code, message=None):
-    return HttpResponse(u'''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
+    return HttpResponse('''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
             <cas:authenticationFailure code="%(code)s">
                 %(message)s
             </cas:authenticationFailure>
index fc99637..a2aa65d 100755 (executable)
@@ -1,4 +1,6 @@
 #!/usr/bin/env python
+from __future__ import unicode_literals
+
 import os
 import sys
 
index 679863a..51a1436 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 # Django settings for xxx project.
 
 DEBUG = True
index 1d8eafa..71e70f3 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from django.conf.urls import patterns, include, url
 from django.contrib import admin
 from django.views.generic import TemplateView