Skip to content
Browse files

anger release commit

  • Loading branch information...
1 parent 03ce311 commit e6c2d2eb7a9608658823fc2854104c2a61284942 @mcdonc mcdonc committed Sep 22, 2011
View
4 pyramid/asset.py
@@ -1,11 +1,13 @@
import os
import pkg_resources
+from pyramid.compat import string_types
+
from pyramid.path import package_path
from pyramid.path import package_name
def resolve_asset_spec(spec, pname='__main__'):
- if pname and not isinstance(pname, basestring):
+ if pname and not isinstance(pname, string_types):
pname = pname.__name__ # as package
if os.path.isabs(spec):
return None, spec
View
6 pyramid/authentication.py
@@ -3,11 +3,14 @@
from hashlib import md5
import datetime
import re
+import sys
import time as time_mod
import urllib
from zope.interface import implements
+from pyramid.compat import long
+
from pyramid.interfaces import IAuthenticationPolicy
from pyramid.interfaces import IDebugLogger
@@ -469,7 +472,8 @@ def parse_ticket(secret, ticket, ip):
digest = ticket[:32]
try:
timestamp = int(ticket[32:40], 16)
- except ValueError, e:
+ except ValueError:
+ e = sys.exc_info()[1]
raise BadTicket('Timestamp is not a hex integer: %s' % e)
try:
userid, data = ticket[40:].split('!', 1)
View
4 pyramid/chameleon_text.py
@@ -3,6 +3,8 @@
from zope.deprecation import deprecated
from zope.interface import implements
+from pyramid.compat import reraise
+
try:
from chameleon.zpt.template import PageTextTemplateFile
# prevent pyflakes complaining about a redefinition below
@@ -12,7 +14,7 @@
# Chameleon doesn't work on non-CPython platforms
class PageTextTemplateFile(object):
def __init__(self, *arg, **kw):
- raise ImportError, exc, tb
+ reraise(ImportError, exc, tb)
from pyramid.interfaces import ITemplateRenderer
View
4 pyramid/chameleon_zpt.py
@@ -3,6 +3,8 @@
from zope.deprecation import deprecated
from zope.interface import implements
+from pyramid.compat import reraise
+
try:
from chameleon.zpt.template import PageTemplateFile
PageTemplateFile # prevent pyflakes complaining about a redefinition below
@@ -11,7 +13,7 @@
# Chameleon doesn't work on non-CPython platforms
class PageTemplateFile(object):
def __init__(self, *arg, **kw):
- raise ImportError, exc, tb
+ reraise(ImportError, exc, tb)
from pyramid.interfaces import ITemplateRenderer
View
175 pyramid/compat.py
@@ -1,3 +1,11 @@
+import sys
+import types
+
+try:
+ import cPickle as pickle
+except ImportError: # pragma: no cover
+ import pickle
+
try:
import json
except ImportError: # pragma: no cover
@@ -6,3 +14,170 @@
except NotImplementedError:
from django.utils import simplejson as json # GAE
+# True if we are running on Python 3.
+PY3 = sys.version_info[0] == 3
+
+if PY3: # pragma: no cover
+ string_types = str,
+ integer_types = int,
+ class_types = type,
+ text_type = str
+ binary_type = bytes
+ long = int
+ def ords_(b):
+ return b
+else:
+ string_types = basestring,
+ integer_types = (int, long)
+ class_types = (type, types.ClassType)
+ text_type = unicode
+ binary_type = str
+ def ords_(s):
+ return [ord(x) for x in s]
+
+def text_(s, encoding='latin-1', errors='strict'):
+ if isinstance(s, binary_type):
+ return s.decode(encoding, errors)
+ return s
+
+def bytes_(s, encoding='latin-1', errors='strict'):
+ if isinstance(s, text_type):
+ return s.encode(encoding, errors)
+ return s
+
+if PY3: # pragma: no cover
+ def native_(s, encoding='latin-1', errors='strict'):
+ if isinstance(s, text_type):
+ return s
+ return str(s, encoding, errors)
+else:
+ def native_(s, encoding='latin-1', errors='strict'):
+ if isinstance(s, text_type):
+ return s.encode(encoding, errors)
+ return str(s)
+
+if PY3: # pragma: no cover
+ fsenc = sys.getfilesystemencoding()
+ def text_to_wsgi(u):
+ # On Python 3, convert an environment variable to a WSGI
+ # "bytes-as-unicode" string
+ return u.encode(fsenc, 'surrogateescape').decode('latin-1')
+else:
+ def text_to_wsgi(u):
+ return u.encode('latin-1', 'surrogateescape')
+
+try:
+ from queue import Queue, Empty
+except ImportError:
+ from Queue import Queue, Empty
+
+try: # pragma: no cover
+ from urllib import parse
+ urlparse = parse
+ from urllib.parse import quote as url_quote
+ from urllib.parse import unquote as url_unquote
+ from urllib.parse import urlencode as url_encode
+ from urllib.request import urlopen as url_open
+except ImportError:
+ import urlparse
+ from urllib import quote as url_quote
+ from urllib import unquote as url_unquote
+ from urllib import urlencode as url_encode
+ from urllib2 import urlopen as url_open
+
+if PY3: # pragma: no cover
+ import builtins
+ exec_ = getattr(builtins, "exec")
+
+
+ def reraise(tp, value, tb=None):
+ if value.__traceback__ is not tb:
+ raise value.with_traceback(tb)
+ raise value
+
+
+ print_ = getattr(builtins, "print")
+ del builtins
+
+else: # pragma: no cover
+ def exec_(code, globs=None, locs=None):
+ """Execute code in a namespace."""
+ if globs is None:
+ frame = sys._getframe(1)
+ globs = frame.f_globals
+ if locs is None:
+ locs = frame.f_locals
+ del frame
+ elif locs is None:
+ locs = globs
+ exec("""exec code in globs, locs""")
+
+
+ exec_("""def reraise(tp, value, tb=None):
+ raise tp, value, tb
+""")
+
+
+ def print_(*args, **kwargs):
+ """The new-style print function."""
+ fp = kwargs.pop("file", sys.stdout)
+ if fp is None:
+ return
+ def write(data):
+ if not isinstance(data, basestring):
+ data = str(data)
+ fp.write(data)
+ want_unicode = False
+ sep = kwargs.pop("sep", None)
+ if sep is not None:
+ if isinstance(sep, unicode):
+ want_unicode = True
+ elif not isinstance(sep, str):
+ raise TypeError("sep must be None or a string")
+ end = kwargs.pop("end", None)
+ if end is not None:
+ if isinstance(end, unicode):
+ want_unicode = True
+ elif not isinstance(end, str):
+ raise TypeError("end must be None or a string")
+ if kwargs:
+ raise TypeError("invalid keyword arguments to print()")
+ if not want_unicode:
+ for arg in args:
+ if isinstance(arg, unicode):
+ want_unicode = True
+ break
+ if want_unicode:
+ newline = unicode("\n")
+ space = unicode(" ")
+ else:
+ newline = "\n"
+ space = " "
+ if sep is None:
+ sep = space
+ if end is None:
+ end = newline
+ for i, arg in enumerate(args):
+ if i:
+ write(sep)
+ write(arg)
+ write(end)
+
+if PY3: # pragma: no cover
+ def iteritems_(d):
+ return d.items()
+ def itervalues_(d):
+ return d.values()
+else:
+ def iteritems_(d):
+ return d.iteritems()
+ def itervalues_(d):
+ return d.itervalues()
+
+
+if PY3:
+ def map_(*arg):
+ return list(map(*arg))
+else:
+ map_ = map
+
View
14 pyramid/config/__init__.py
@@ -13,6 +13,9 @@
from pyramid.asset import resolve_asset_spec
from pyramid.authorization import ACLAuthorizationPolicy
+from pyramid.compat import text_
+from pyramid.compat import reraise
+from pyramid.compat import string_types
from pyramid.events import ApplicationCreated
from pyramid.exceptions import ConfigurationConflictError
from pyramid.exceptions import ConfigurationError
@@ -42,6 +45,8 @@
from pyramid.config.views import ViewsConfiguratorMixin
from pyramid.config.zca import ZCAConfiguratorMixin
+empty = text_('')
+
ConfigurationError = ConfigurationError # pyflakes
class Configurator(
@@ -283,7 +288,7 @@ def setup_registry(self, settings=None, root_factory=None,
self._set_settings(settings)
self._register_response_adapters()
- if isinstance(debug_logger, basestring):
+ if isinstance(debug_logger, string_types):
debug_logger = logging.getLogger(debug_logger)
if debug_logger is None:
@@ -401,7 +406,7 @@ def queryAdapterOrSelf(object, interface, default=None):
if not hasattr(_registry, 'registerSelfAdapter'):
def registerSelfAdapter(required=None, provided=None,
- name=u'', info=u'', event=True):
+ name=empty, info=empty, event=True):
return _registry.registerAdapter(lambda x: x,
required=required,
provided=provided, name=name,
@@ -709,7 +714,7 @@ def absolute_asset_spec(self, relative_spec):
when generating an absolute asset specification. If the
provided ``relative_spec`` argument is already absolute, or if
the ``relative_spec`` is not a string, it is simply returned."""
- if not isinstance(relative_spec, basestring):
+ if not isinstance(relative_spec, string_types):
return relative_spec
return self._make_spec(relative_spec)
@@ -907,7 +912,8 @@ def execute_actions(self, clear=True):
except:
t, v, tb = sys.exc_info()
try:
- raise ConfigurationExecutionError(t, v, info), None, tb
+ reraise(
+ ConfigurationExecutionError(t, v, info), None, tb)
finally:
del t, v, tb
finally:
View
2 pyramid/config/tweens.py
@@ -197,7 +197,7 @@ def implicit(self):
order.append((a, b))
def add_node(node):
- if not graph.has_key(node):
+ if not node in graph:
roots.append(node)
graph[node] = [0] # 0 = number of arcs coming into this node
View
7 pyramid/config/util.py
@@ -1,4 +1,5 @@
import re
+import sys
import traceback
from pyramid.exceptions import ConfigurationError
@@ -111,7 +112,8 @@ def request_method_predicate(context, request):
if path_info is not None:
try:
path_info_val = re.compile(path_info)
- except re.error, why:
+ except re.error:
+ why = sys.exc_info()[1]
raise ConfigurationError(why[0])
def path_info_predicate(context, request):
return path_info_val.match(request.path_info) is not None
@@ -145,7 +147,8 @@ def request_param_predicate(context, request):
header_name, header_val = header.split(':', 1)
try:
header_val = re.compile(header_val)
- except re.error, why:
+ except re.error:
+ why = sys.exc_info()[1]
raise ConfigurationError(why[0])
if header_val is None:
text = "header %s" % header_name
View
5 pyramid/config/views.py
@@ -1,6 +1,4 @@
import inspect
-from urlparse import urljoin
-from urlparse import urlparse
from zope.interface import Interface
from zope.interface import classProvides
@@ -28,6 +26,7 @@
from pyramid.interfaces import PHASE1_CONFIG
from pyramid import renderers
+from pyramid.compat import urlparse
from pyramid.exceptions import ConfigurationError
from pyramid.exceptions import PredicateMismatch
from pyramid.httpexceptions import HTTPForbidden
@@ -43,6 +42,8 @@
from pyramid.config.util import as_sorted_tuple
from pyramid.config.util import make_predicates
+urljoin = urlparse.urljoin
+
def wraps_view(wrapper):
def inner(self, view):
wrapper_view = wrapper(self, view)
View
8 pyramid/exceptions.py
@@ -4,6 +4,8 @@
NotFound = HTTPNotFound # bw compat
Forbidden = HTTPForbidden # bw compat
+CR = '\n'
+
class PredicateMismatch(HTTPNotFound):
"""
Internal exception (not an API) raised by multiviews when no
@@ -42,10 +44,10 @@ def __str__(self):
for discriminator, infos in items:
r.append(" For: %s" % (discriminator, ))
for info in infos:
- for line in unicode(info).rstrip().split(u'\n'):
- r.append(u" "+line)
+ for line in unicode(info).rstrip().split(CR):
+ r.append(" "+line)
- return "\n".join(r)
+ return CR.join(r)
class ConfigurationExecutionError(ConfigurationError):
View
6 pyramid/httpexceptions.py
@@ -122,7 +122,6 @@
``location``, which indicates the location to which to redirect.
"""
-import types
from string import Template
from zope.interface import implements
@@ -131,6 +130,7 @@
from pyramid.interfaces import IExceptionResponse
from pyramid.response import Response
+from pyramid.compat import class_types
def _no_escape(value):
if value is None:
@@ -1016,8 +1016,8 @@ def default_exceptionresponse_view(context, request):
status_map={}
code = None
-for name, value in globals().items():
- if (isinstance(value, (type, types.ClassType)) and
+for name, value in list(globals().items()):
+ if (isinstance(value, class_types) and
issubclass(value, HTTPException)
and not name.startswith('_')):
code = getattr(value, 'code', None)
View
2 pyramid/interfaces.py
@@ -42,7 +42,7 @@ class IApplicationCreated(Interface):
versions before 1.0, this interface can also be imported as
:class:`pyramid.interfaces.IWSGIApplicationCreatedEvent`.
"""
- app = Attribute(u"Created application")
+ app = Attribute("Created application")
IWSGIApplicationCreatedEvent = IApplicationCreated # b /c
View
7 pyramid/registry.py
@@ -1,7 +1,10 @@
from zope.interface.registry import Components
+from pyramid.compat import text_
from pyramid.interfaces import ISettings
+empty = text_('')
+
class Registry(Components, dict):
""" A registry object is an :term:`application registry`. It is used by
the framework itself to perform mappings of URLs to view callables, as
@@ -34,8 +37,8 @@ def registerSubscriptionAdapter(self, *arg, **kw):
self.has_listeners = True
return result
- def registerSelfAdapter(self, required=None, provided=None, name=u'',
- info=u'', event=True):
+ def registerSelfAdapter(self, required=None, provided=None, name=empty,
+ info=empty, event=True):
# registerAdapter analogue which always returns the object itself
# when required is matched
return self.registerAdapter(lambda x: x, required=required,
View
6 pyramid/renderers.py
@@ -15,6 +15,8 @@
from pyramid.asset import asset_spec_from_abspath
from pyramid.compat import json
+from pyramid.compat import string_types
+from pyramid.compat import native_
from pyramid.decorator import reify
from pyramid.events import BeforeRender
from pyramid.path import caller_package
@@ -145,8 +147,8 @@ def _render(value, system):
def string_renderer_factory(info):
def _render(value, system):
- if not isinstance(value, basestring):
- value = str(value)
+ if not isinstance(value, string_types):
+ value = native_(value, 'utf-8')
request = system.get('request')
if request is not None:
response = request.response
View
2 pyramid/resource.py
@@ -1,5 +1,5 @@
""" Backwards compatibility shim module (forever). """
-from asset import * # b/w compat
+from pyramid.asset import * # b/w compat
resolve_resource_spec = resolve_asset_spec
resource_spec_from_abspath = asset_spec_from_abspath
abspath_from_resource_spec = abspath_from_asset_spec
View
11 pyramid/session.py
@@ -1,18 +1,14 @@
-
-try:
- import cPickle as pickle
-except ImportError: # pragma: no cover
- import pickle
-
from hashlib import sha1
import base64
import binascii
import hmac
+import sys
import time
import os
from zope.interface import implements
+from pyramid.compat import pickle
from pyramid.interfaces import ISession
def manage_accessed(wrapped):
@@ -255,8 +251,9 @@ def signed_deserialize(serialized, secret, hmac=hmac):
try:
input_sig, pickled = (serialized[:40],
base64.standard_b64decode(serialized[40:]))
- except (binascii.Error, TypeError), e:
+ except (binascii.Error, TypeError):
# Badly formed data can make base64 die
+ e = sys.exc_info()[1]
raise ValueError('Badly formed base64 data: %s' % e)
sig = hmac.new(secret, pickled, sha1).hexdigest()
View
5 pyramid/static.py
@@ -15,12 +15,15 @@
from repoze.lru import lru_cache
from pyramid.asset import resolve_asset_spec
+from pyramid.compat import text_
from pyramid.httpexceptions import HTTPNotFound
from pyramid.httpexceptions import HTTPMovedPermanently
from pyramid.path import caller_package
from pyramid.response import Response
from pyramid.traversal import traversal_path
+slash = text_('/')
+
def init_mimetypes(mimetypes):
# this is a function so it can be unittested
if hasattr(mimetypes, 'init'):
@@ -192,6 +195,6 @@ def _secure_path(path_tuple):
return None
if any([_contains_slash(item) for item in path_tuple]):
return None
- encoded = u'/'.join(path_tuple) # will be unicode
+ encoded = slash.join(path_tuple) # will be unicode
return encoded
View
9 pyramid/testing.py
@@ -28,6 +28,13 @@
from pyramid.request import CallbackMethodsMixin
from pyramid.url import URLMethodsMixin
+try:
+ import zope.component
+ zope.component
+ have_zca = True
+except ImportError:
+ have_zca = False
+
_marker = object()
def registerDummySecurityPolicy(userid=None, groupids=(), permissive=True):
@@ -801,7 +808,7 @@ def setUp(registry=None, request=None, hook_zca=True, autocommit=True,
# any existing renderer factory lookup system.
config.add_renderer(name, renderer)
config.commit()
- hook_zca and config.hook_zca()
+ have_zca and hook_zca and config.hook_zca()
config.begin(request=request)
return config
View
7 pyramid/tests/test_authentication.py
@@ -1,5 +1,6 @@
import unittest
from pyramid import testing
+from pyramid.compat import text_
class TestCallbackAuthenticationPolicyDebugging(unittest.TestCase):
def setUp(self):
@@ -903,7 +904,7 @@ def test_remember_non_string_token(self):
helper = self._makeOne('secret')
request = self._makeRequest()
self.assertRaises(ValueError, helper.remember, request, 'other',
- tokens=(u'foo',))
+ tokens=(text_('foo'),))
def test_remember_invalid_token_format(self):
helper = self._makeOne('secret')
@@ -1092,8 +1093,8 @@ def _callFUT(self, s, encoding='utf-8'):
return maybe_encode(s, encoding)
def test_unicode(self):
- result = self._callFUT(u'abc')
- self.assertEqual(result, 'abc')
+ result = self._callFUT(text_('abc'))
+ self.assertEqual(result, text_('abc'))
class DummyContext:
pass
View
2 pyramid/tests/test_config/test_assets.py
@@ -581,7 +581,7 @@ def __init__(self, name):
class DummyUnderOverride:
def __call__(self, package, path, override_package, override_prefix,
- _info=u''):
+ _info=''):
self.package = package
self.path = path
self.override_package = override_package
View
2 pyramid/tests/test_config/test_i18n.py
@@ -92,7 +92,7 @@ def test_add_translation_dirs_registers_chameleon_translate(self):
try:
config.add_translation_dirs('pyramid.tests.pkgs.localeapp:locale')
translate = config.registry.getUtility(IChameleonTranslate)
- self.assertEqual(translate('Approve'), u'Approve')
+ self.assertEqual(translate('Approve'), 'Approve')
finally:
manager.pop()
View
2 pyramid/tests/test_config/test_init.py
@@ -333,7 +333,7 @@ def test__fix_registry_registerSelfAdapter(self):
args, kw = reg.adapters[0]
self.assertEqual(args[0]('abc'), 'abc')
self.assertEqual(kw,
- {'info': u'', 'provided': 'provided',
+ {'info': '', 'provided': 'provided',
'required': 'required', 'name': 'abc', 'event': True})
def test_setup_registry_calls_fix_registry(self):
View
13 pyramid/tests/test_config/test_views.py
@@ -1,4 +1,5 @@
import unittest
+import sys
from pyramid import testing
from pyramid.tests.test_config import IDummy
@@ -2530,7 +2531,8 @@ def test_secured_view_raises_forbidden_no_name(self):
request.url = 'url'
try:
result(None, request)
- except HTTPForbidden, e:
+ except HTTPForbidden:
+ e = sys.exc_info()[1]
self.assertEqual(e.message,
'Unauthorized: <lambda> failed permission check')
else: # pragma: no cover
@@ -2552,7 +2554,8 @@ def myview(request): pass
request.url = 'url'
try:
result(None, request)
- except HTTPForbidden, e:
+ except HTTPForbidden:
+ e = sys.exc_info()[1]
self.assertEqual(e.message,
'Unauthorized: myview failed permission check')
else: # pragma: no cover
@@ -2570,7 +2573,8 @@ def predicate1(context, request):
request.method = 'POST'
try:
result(None, None)
- except PredicateMismatch, e:
+ except PredicateMismatch:
+ e = sys.exc_info()[1]
self.assertEqual(e.detail, 'predicate mismatch for view <lambda>')
else: # pragma: no cover
raise AssertionError
@@ -2586,7 +2590,8 @@ def predicate1(context, request):
request.method = 'POST'
try:
result(None, None)
- except PredicateMismatch, e:
+ except PredicateMismatch:
+ e = sys.exc_info()[1]
self.assertEqual(e.detail, 'predicate mismatch for view myview')
else: # pragma: no cover
raise AssertionError
View
3 pyramid/tests/test_docs.py
@@ -1,4 +1,5 @@
import unittest
+from pyramid.compat import print_
if 0:
# no released version of manuel actually works with :lineno:
@@ -31,5 +32,5 @@ def test_docs(cls):
if filename.endswith('.rst'):
docs.append(os.path.join(root, filename))
- print path
+ print_(path)
return manuel.testing.TestSuite(m, *docs)
View
7 pyramid/tests/test_httpexceptions.py
@@ -1,4 +1,5 @@
import unittest
+from pyramid.compat import text_
class Test_exception_response(unittest.TestCase):
def _callFUT(self, *arg, **kw):
@@ -48,9 +49,9 @@ def test_not_basestring(self):
def test_unicode(self):
class DummyUnicodeObject(object):
def __unicode__(self):
- return u'42'
+ return text_('42')
duo = DummyUnicodeObject()
- self.assertEqual(self._callFUT(duo), u'42')
+ self.assertEqual(self._callFUT(duo), text_('42'))
class TestWSGIHTTPException(unittest.TestCase):
def _getTargetClass(self):
@@ -128,7 +129,7 @@ def test_ctor_with_body_doesnt_set_default_app_iter(self):
self.assertEqual(exc.app_iter, ['123'])
def test_ctor_with_unicode_body_doesnt_set_default_app_iter(self):
- exc = self._makeOne(unicode_body=u'123')
+ exc = self._makeOne(unicode_body=text_('123'))
self.assertEqual(exc.app_iter, ['123'])
def test_ctor_with_app_iter_doesnt_set_default_app_iter(self):
View
9 pyramid/tests/test_integration.py
@@ -6,6 +6,7 @@
from pyramid.wsgi import wsgiapp
from pyramid.view import view_config
from pyramid.static import static_view
+from pyramid.compat import text_
from zope.interface import Interface
@@ -82,13 +83,17 @@ def test_hidden(self):
def test_highchars_in_pathelement(self):
res = self.testapp.get('/static/héhé/index.html', status=200)
self._assertBody(
- res.body, os.path.join(here, u'fixtures/static/héhé/index.html')
+ res.body, os.path.join(
+ here,
+ text_('fixtures/static/héhé/index.html', 'utf-8'))
)
def test_highchars_in_filename(self):
res = self.testapp.get('/static/héhé.html', status=200)
self._assertBody(
- res.body, os.path.join(here, u'fixtures/static/héhé.html')
+ res.body, os.path.join(
+ here,
+ text_('fixtures/static/héhé.html', 'utf-8'))
)
def test_not_modified(self):
View
37 pyramid/tests/test_mako_templating.py
@@ -2,6 +2,7 @@
import unittest
from pyramid import testing
+from pyramid.compat import text_
class Base(object):
def setUp(self):
@@ -276,23 +277,23 @@ def test_call(self):
instance = self._makeOne('path', lookup)
result = instance({}, {'system':1})
self.assertTrue(isinstance(result, unicode))
- self.assertEqual(result, u'result')
+ self.assertEqual(result, text_('result'))
def test_call_with_system_context(self):
# lame
lookup = DummyLookup()
instance = self._makeOne('path', lookup)
result = instance({}, {'context':1})
self.assertTrue(isinstance(result, unicode))
- self.assertEqual(result, u'result')
+ self.assertEqual(result, text_('result'))
self.assertEqual(lookup.values, {'_context':1})
def test_call_with_tuple_value(self):
lookup = DummyLookup()
instance = self._makeOne('path', lookup)
result = instance(('fub', {}), {'context':1})
self.assertEqual(lookup.deffed, 'fub')
- self.assertEqual(result, u'result')
+ self.assertEqual(result, text_('result'))
self.assertEqual(lookup.values, {'_context':1})
def test_call_with_nondict_value(self):
@@ -316,7 +317,7 @@ def test_implementation(self):
instance = self._makeOne('path', lookup)
result = instance.implementation().render_unicode()
self.assertTrue(isinstance(result, unicode))
- self.assertEqual(result, u'result')
+ self.assertEqual(result, text_('result'))
class TestIntegration(unittest.TestCase):
def setUp(self):
@@ -333,45 +334,48 @@ def tearDown(self):
def test_render(self):
from pyramid.renderers import render
result = render('helloworld.mak', {'a':1}).replace('\r','')
- self.assertEqual(result, u'\nHello föö\n')
+ self.assertEqual(result, text_('\nHello föö\n', 'utf-8'))
def test_render_from_fs(self):
from pyramid.renderers import render
self.config.add_settings({'reload_templates': True})
result = render('helloworld.mak', {'a':1}).replace('\r','')
- self.assertEqual(result, u'\nHello föö\n')
+ self.assertEqual(result, text_('\nHello föö\n', 'utf-8'))
def test_render_inheritance(self):
from pyramid.renderers import render
result = render('helloinherit.mak', {}).replace('\r','')
- self.assertEqual(result, u'Layout\nHello World!\n')
+ self.assertEqual(result, text_('Layout\nHello World!\n'))
def test_render_inheritance_pkg_spec(self):
from pyramid.renderers import render
result = render('hello_inherit_pkg.mak', {}).replace('\r','')
- self.assertEqual(result, u'Layout\nHello World!\n')
+ self.assertEqual(result, text_('Layout\nHello World!\n'))
def test_render_to_response(self):
from pyramid.renderers import render_to_response
result = render_to_response('helloworld.mak', {'a':1})
- self.assertEqual(result.ubody.replace('\r',''), u'\nHello föö\n')
+ self.assertEqual(result.ubody.replace('\r',''),
+ text_('\nHello föö\n', 'utf-8'))
def test_render_to_response_pkg_spec(self):
from pyramid.renderers import render_to_response
result = render_to_response('pyramid.tests:fixtures/helloworld.mak',
{'a':1})
- self.assertEqual(result.ubody.replace('\r', ''), u'\nHello föö\n')
+ self.assertEqual(result.ubody.replace('\r', ''),
+ text_('\nHello föö\n', 'utf-8'))
def test_render_with_abs_path(self):
from pyramid.renderers import render
result = render('/helloworld.mak', {'a':1}).replace('\r','')
- self.assertEqual(result, u'\nHello föö\n')
+ self.assertEqual(result, text_('\nHello föö\n', 'utf-8'))
def test_get_renderer(self):
from pyramid.renderers import get_renderer
result = get_renderer('helloworld.mak')
- self.assertEqual(result.implementation().render_unicode().replace('\r',''),
- u'\nHello föö\n')
+ self.assertEqual(
+ result.implementation().render_unicode().replace('\r',''),
+ text_('\nHello föö\n', 'utf-8'))
def test_template_not_found(self):
from pyramid.renderers import render
@@ -381,8 +385,9 @@ def test_template_not_found(self):
def test_template_default_escaping(self):
from pyramid.renderers import render
- result = render('nonminimal.mak', {'name':'<b>fred</b>'}).replace('\r','')
- self.assertEqual(result, u'Hello, &lt;b&gt;fred&lt;/b&gt;!\n')
+ result = render('nonminimal.mak',
+ {'name':'<b>fred</b>'}).replace('\r','')
+ self.assertEqual(result, text_('Hello, &lt;b&gt;fred&lt;/b&gt;!\n'))
class TestPkgResourceTemplateLookup(unittest.TestCase):
def _makeOne(self, **kw):
@@ -448,7 +453,7 @@ def render_unicode(self, **values):
if self.exc:
raise self.exc
self.values = values
- return u'result'
+ return text_('result')
class DummyRendererInfo(object):
def __init__(self, kw):
View
2 pyramid/tests/test_paster.py
@@ -1062,7 +1062,7 @@ def items(self, section):
self.section = section
if self.result is None:
from ConfigParser import NoSectionError
- raise NoSectionError, section
+ raise NoSectionError(section)
return self.result
class DummyConfigParserFactory(object):
View
8 pyramid/tests/test_request.py
@@ -1,6 +1,8 @@
import unittest
from pyramid import testing
+from pyramid.compat import text_
+
class TestRequest(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
@@ -50,7 +52,7 @@ def test_params_decoded_from_utf_8_by_default(self):
}
request = self._makeOne(environ)
request.charset = None
- self.assertEqual(request.GET['la'], u'La Pe\xf1a')
+ self.assertEqual(request.GET['la'], text_('La Pe\xf1a', 'utf-8'))
def test_class_implements(self):
from pyramid.interfaces import IRequest
@@ -166,7 +168,7 @@ def test_route_url(self):
self.config.registry.registerUtility(mapper, IRoutesMapper)
result = inst.route_url('flub', 'extra1', 'extra2',
a=1, b=2, c=3, _query={'a':1},
- _anchor=u"foo")
+ _anchor=text_("foo"))
self.assertEqual(result,
'http://example.com:5432/1/2/3/extra1/extra2?a=1#foo')
@@ -184,7 +186,7 @@ def test_route_path(self):
self.config.registry.registerUtility(mapper, IRoutesMapper)
result = inst.route_path('flub', 'extra1', 'extra2',
a=1, b=2, c=3, _query={'a':1},
- _anchor=u"foo")
+ _anchor=text_("foo"))
self.assertEqual(result, '/1/2/3/extra1/extra2?a=1#foo')
def test_static_url(self):
View
4 pyramid/tests/test_router.py
@@ -1,3 +1,4 @@
+import sys
import unittest
from pyramid import testing
@@ -1204,7 +1205,8 @@ def info(self, msg):
def exc_raised(exc, func, *arg, **kw):
try:
func(*arg, **kw)
- except exc, e:
+ except exc:
+ e = sys.exc_info()[1]
return e
else:
raise AssertionError('%s not raised' % exc) # pragma: no cover
View
6 pyramid/tests/test_testing.py
@@ -1,5 +1,5 @@
-
import unittest
+from pyramid.compat import text_
class TestBase(unittest.TestCase):
def setUp(self):
@@ -46,14 +46,14 @@ def test_it(self):
self.assertEqual(result['context'], ob1)
self.assertEqual(result['view_name'], '')
self.assertEqual(result['subpath'], ())
- self.assertEqual(result['traversed'], (u'ob1',))
+ self.assertEqual(result['traversed'], (text_('ob1'),))
self.assertEqual(result['virtual_root'], ob1)
self.assertEqual(result['virtual_root_path'], ())
result = adapter(DummyRequest({'PATH_INFO':'/ob2'}))
self.assertEqual(result['context'], ob2)
self.assertEqual(result['view_name'], '')
self.assertEqual(result['subpath'], ())
- self.assertEqual(result['traversed'], (u'ob2',))
+ self.assertEqual(result['traversed'], (text_('ob2'),))
self.assertEqual(result['virtual_root'], ob2)
self.assertEqual(result['virtual_root_path'], ())
self.assertRaises(KeyError, adapter, DummyRequest({'PATH_INFO':'/ob3'}))
View
61 pyramid/tests/test_traversal.py
@@ -1,30 +1,32 @@
import unittest
from pyramid.testing import cleanUp
+from pyramid.compat import text_
class TraversalPathTests(unittest.TestCase):
def _callFUT(self, path):
from pyramid.traversal import traversal_path
return traversal_path(path)
def test_path_startswith_endswith(self):
- self.assertEqual(self._callFUT('/foo/'), (u'foo',))
+ self.assertEqual(self._callFUT('/foo/'), (text_('foo'),))
def test_empty_elements(self):
- self.assertEqual(self._callFUT('foo///'), (u'foo',))
+ self.assertEqual(self._callFUT('foo///'), (text_('foo'),))
def test_onedot(self):
- self.assertEqual(self._callFUT('foo/./bar'), (u'foo', u'bar'))
+ self.assertEqual(self._callFUT('foo/./bar'),
+ (text_('foo'), text_('bar')))
def test_twodots(self):
- self.assertEqual(self._callFUT('foo/../bar'), (u'bar',))
+ self.assertEqual(self._callFUT('foo/../bar'), (text_('bar'),))
def test_twodots_at_start(self):
- self.assertEqual(self._callFUT('../../bar'), (u'bar',))
+ self.assertEqual(self._callFUT('../../bar'), (text_('bar'),))
def test_element_urllquoted(self):
self.assertEqual(self._callFUT('/foo/space%20thing/bar'),
- (u'foo', u'space thing', u'bar'))
+ (text_('foo'), text_('space thing'), text_('bar')))
def test_segments_are_unicode(self):
result = self._callFUT('/foo/bar')
@@ -34,8 +36,8 @@ def test_segments_are_unicode(self):
def test_same_value_returned_if_cached(self):
result1 = self._callFUT('/foo/bar')
result2 = self._callFUT('/foo/bar')
- self.assertEqual(result1, (u'foo', u'bar'))
- self.assertEqual(result2, (u'foo', u'bar'))
+ self.assertEqual(result1, (text_('foo'), text_('bar')))
+ self.assertEqual(result2, (text_('foo'), text_('bar')))
def test_utf8(self):
import urllib
@@ -54,15 +56,16 @@ def test_utf16(self):
self.assertRaises(URLDecodeError, self._callFUT, path)
def test_unicode_highorder_chars(self):
- path = u'/%E6%B5%81%E8%A1%8C%E8%B6%8B%E5%8A%BF'
- self.assertEqual(self._callFUT(path), (u'\u6d41\u884c\u8d8b\u52bf',))
+ path = text_('/%E6%B5%81%E8%A1%8C%E8%B6%8B%E5%8A%BF')
+ self.assertEqual(self._callFUT(path),
+ (text_('\u6d41\u884c\u8d8b\u52bf'),))
def test_unicode_simple(self):
- path = u'/abc'
- self.assertEqual(self._callFUT(path), (u'abc',))
+ path = text_('/abc')
+ self.assertEqual(self._callFUT(path), (text_('abc'),))
def test_unicode_undecodeable_to_ascii(self):
- path = unicode('/La Pe\xc3\xb1a', 'utf-8')
+ path = text_('/La Pe\xc3\xb1a', 'utf-8')
self.assertRaises(UnicodeEncodeError, self._callFUT, path)
class ResourceTreeTraverserTests(unittest.TestCase):
@@ -146,7 +149,7 @@ def test_call_withconn_getitem_withpath_nosubpath(self):
self.assertEqual(result['context'], foo)
self.assertEqual(result['view_name'], 'bar')
self.assertEqual(result['subpath'], ())
- self.assertEqual(result['traversed'], (u'foo',))
+ self.assertEqual(result['traversed'], (text_('foo'),))
self.assertEqual(result['root'], root)
self.assertEqual(result['virtual_root'], root)
self.assertEqual(result['virtual_root_path'], ())
@@ -161,7 +164,7 @@ def test_call_withconn_getitem_withpath_withsubpath(self):
self.assertEqual(result['context'], foo)
self.assertEqual(result['view_name'], 'bar')
self.assertEqual(result['subpath'], ('baz', 'buz'))
- self.assertEqual(result['traversed'], (u'foo',))
+ self.assertEqual(result['traversed'], (text_('foo'),))
self.assertEqual(result['root'], root)
self.assertEqual(result['virtual_root'], root)
self.assertEqual(result['virtual_root_path'], ())
@@ -194,10 +197,12 @@ def test_call_with_vh_root(self):
self.assertEqual(result['context'], baz)
self.assertEqual(result['view_name'], '')
self.assertEqual(result['subpath'], ())
- self.assertEqual(result['traversed'], (u'foo', u'bar', u'baz'))
+ self.assertEqual(result['traversed'],
+ (text_('foo'), text_('bar'), text_('baz')))
self.assertEqual(result['root'], root)
self.assertEqual(result['virtual_root'], bar)
- self.assertEqual(result['virtual_root_path'], (u'foo', u'bar'))
+ self.assertEqual(result['virtual_root_path'],
+ (text_('foo'), text_('bar')))
def test_call_with_vh_root2(self):
environ = self._getEnviron(PATH_INFO='/bar/baz',
@@ -212,10 +217,11 @@ def test_call_with_vh_root2(self):
self.assertEqual(result['context'], baz)
self.assertEqual(result['view_name'], '')
self.assertEqual(result['subpath'], ())
- self.assertEqual(result['traversed'], (u'foo', u'bar', u'baz'))
+ self.assertEqual(result['traversed'],
+ (text_('foo'), text_('bar'), text_('baz')))
self.assertEqual(result['root'], root)
self.assertEqual(result['virtual_root'], foo)
- self.assertEqual(result['virtual_root_path'], (u'foo',))
+ self.assertEqual(result['virtual_root_path'], (text_('foo'),))
def test_call_with_vh_root3(self):
environ = self._getEnviron(PATH_INFO='/foo/bar/baz',
@@ -230,7 +236,8 @@ def test_call_with_vh_root3(self):
self.assertEqual(result['context'], baz)
self.assertEqual(result['view_name'], '')
self.assertEqual(result['subpath'], ())
- self.assertEqual(result['traversed'], (u'foo', u'bar', u'baz'))
+ self.assertEqual(result['traversed'],
+ (text_('foo'), text_('bar'), text_('baz')))
self.assertEqual(result['root'], root)
self.assertEqual(result['virtual_root'], root)
self.assertEqual(result['virtual_root_path'], ())
@@ -248,10 +255,12 @@ def test_call_with_vh_root4(self):
self.assertEqual(result['context'], baz)
self.assertEqual(result['view_name'], '')
self.assertEqual(result['subpath'], ())
- self.assertEqual(result['traversed'], (u'foo', u'bar', u'baz'))
+ self.assertEqual(result['traversed'],
+ (text_('foo'), text_('bar'), text_('baz')))
self.assertEqual(result['root'], root)
self.assertEqual(result['virtual_root'], baz)
- self.assertEqual(result['virtual_root_path'], (u'foo', u'bar', u'baz'))
+ self.assertEqual(result['virtual_root_path'],
+ (text_('foo'), text_('bar'), text_('baz')))
def test_call_with_vh_root_path_root(self):
policy = self._makeOne(None)
@@ -592,13 +601,15 @@ def test_absolute_unicode_found(self):
unprintable = DummyContext()
root = DummyContext(unprintable)
unprintable.__parent__ = root
- unprintable.__name__ = unicode(
+ unprintable.__name__ = text_(
'/\xe6\xb5\x81\xe8\xa1\x8c\xe8\xb6\x8b\xe5\x8a\xbf', 'utf-8')
root.__parent__ = None
root.__name__ = None
traverser = ResourceTreeTraverser
self._registerTraverser(traverser)
- result = self._callFUT(root, u'/%E6%B5%81%E8%A1%8C%E8%B6%8B%E5%8A%BF')
+ result = self._callFUT(
+ root,
+ text_('/%E6%B5%81%E8%A1%8C%E8%B6%8B%E5%8A%BF'))
self.assertEqual(result, unprintable)
class ResourcePathTests(unittest.TestCase):
@@ -1168,7 +1179,7 @@ def __init__(self, next=None, name=None):
def __getitem__(self, name):
if self.next is None:
- raise KeyError, name
+ raise KeyError(name)
return self.next
def __repr__(self):
View
14 pyramid/tests/test_url.py
@@ -2,6 +2,7 @@
from pyramid.testing import setUp
from pyramid.testing import tearDown
+from pyramid.compat import text_
class TestURLMethodsMixin(unittest.TestCase):
def setUp(self):
@@ -172,7 +173,7 @@ def test_route_url_no_elements(self):
mapper = DummyRoutesMapper(route=DummyRoute('/1/2/3'))
request.registry.registerUtility(mapper, IRoutesMapper)
result = request.route_url('flub', a=1, b=2, c=3, _query={'a':1},
- _anchor=u"foo")
+ _anchor=text_("foo"))
self.assertEqual(result,
'http://example.com:5432/1/2/3?a=1#foo')
@@ -281,7 +282,7 @@ def test_current_route_url_with_elements_query_and_anchor(self):
request.matchdict = {}
request.registry.registerUtility(mapper, IRoutesMapper)
result = request.current_route_url('extra1', 'extra2', _query={'a':1},
- _anchor=u"foo")
+ _anchor=text_("foo"))
self.assertEqual(result,
'http://example.com:5432/1/2/3/extra1/extra2?a=1#foo')
@@ -294,7 +295,8 @@ def test_current_route_url_with_route_name(self):
request.matchdict = {}
request.registry.registerUtility(mapper, IRoutesMapper)
result = request.current_route_url('extra1', 'extra2', _query={'a':1},
- _anchor=u"foo", _route_name='bar')
+ _anchor=text_("foo"),
+ _route_name='bar')
self.assertEqual(result,
'http://example.com:5432/1/2/3/extra1/extra2?a=1#foo')
@@ -308,7 +310,7 @@ def test_current_route_path(self):
request.script_name = '/script_name'
request.registry.registerUtility(mapper, IRoutesMapper)
result = request.current_route_path('extra1', 'extra2', _query={'a':1},
- _anchor=u"foo")
+ _anchor=text_("foo"))
self.assertEqual(result, '/script_name/1/2/3/extra1/extra2?a=1#foo')
def test_route_path_with_elements(self):
@@ -319,7 +321,7 @@ def test_route_path_with_elements(self):
request.script_name = ''
result = request.route_path('flub', 'extra1', 'extra2',
a=1, b=2, c=3, _query={'a':1},
- _anchor=u"foo")
+ _anchor=text_("foo"))
self.assertEqual(result, '/1/2/3/extra1/extra2?a=1#foo')
def test_route_path_with_script_name(self):
@@ -330,7 +332,7 @@ def test_route_path_with_script_name(self):
request.registry.registerUtility(mapper, IRoutesMapper)
result = request.route_path('flub', 'extra1', 'extra2',
a=1, b=2, c=3, _query={'a':1},
- _anchor=u"foo")
+ _anchor=text_("foo"))
self.assertEqual(result, '/foo/1/2/3/extra1/extra2?a=1#foo')
def test_static_url_staticurlinfo_notfound(self):
View
21 pyramid/tests/test_urldispatch.py
@@ -1,5 +1,6 @@
import unittest
from pyramid import testing
+from pyramid.compat import text_
class TestRoute(unittest.TestCase):
def _getTargetClass(self):
@@ -146,7 +147,7 @@ def test___call__route_fails_to_match_with_predicates(self):
def test___call__custom_predicate_gets_info(self):
mapper = self._makeOne()
def pred(info, request):
- self.assertEqual(info['match'], {'action':u'action1'})
+ self.assertEqual(info['match'], {'action':'action1'})
self.assertEqual(info['route'], mapper.routes['foo'])
return True
mapper.connect('foo', 'archives/:action/article1', predicates=[pred])
@@ -269,7 +270,7 @@ def test_with_star(self):
'traverse':('everything', 'else', 'here')})
self.assertEqual(matcher('foo/baz/biz/buz/bar'), None)
self.assertEqual(generator(
- {'baz':1, 'buz':2, 'traverse':u'/a/b'}), '/foo/1/biz/2/bar/a/b')
+ {'baz':1, 'buz':2, 'traverse':'/a/b'}), '/foo/1/biz/2/bar/a/b')
def test_with_bracket_star(self):
matcher, generator = self._callFUT(
@@ -364,9 +365,10 @@ def test_matcher_functional_newstyle(self):
{'x':'abc', 'traverse':('def', 'g')})
self.matches('*traverse', '/zzz/abc', {'traverse':('zzz', 'abc')})
self.matches('*traverse', '/zzz/%20abc', {'traverse':('zzz', ' abc')})
- self.matches('{x}', '/La%20Pe%C3%B1a', {'x':u'La Pe\xf1a'})
+ self.matches('{x}', '/La%20Pe%C3%B1a',
+ {'x':text_('La Pe\xf1a', 'utf-8')})
self.matches('*traverse', '/La%20Pe%C3%B1a/x',
- {'traverse':(u'La Pe\xf1a', 'x')})
+ {'traverse':(text_('La Pe\xf1a', 'utf-8'), 'x')})
self.matches('/foo/{id}.html', '/foo/bar.html', {'id':'bar'})
self.matches('/{num:[0-9]+}/*traverse', '/555/abc/def',
{'num':'555', 'traverse':('abc', 'def')})
@@ -387,9 +389,10 @@ def test_matcher_functional_oldstyle(self):
{'x':'abc', 'traverse':('def', 'g')})
self.matches('*traverse', '/zzz/abc', {'traverse':('zzz', 'abc')})
self.matches('*traverse', '/zzz/%20abc', {'traverse':('zzz', ' abc')})
- self.matches(':x', '/La%20Pe%C3%B1a', {'x':u'La Pe\xf1a'})
+ self.matches(':x', '/La%20Pe%C3%B1a',
+ {'x':text_('La Pe\xf1a', 'utf-8')})
self.matches('*traverse', '/La%20Pe%C3%B1a/x',
- {'traverse':(u'La Pe\xf1a', 'x')})
+ {'traverse':(text_('La Pe\xf1a', 'utf-8'), 'x')})
self.matches('/foo/:id.html', '/foo/bar.html', {'id':'bar'})
self.matches('/foo/:id_html', '/foo/bar_html', {'id_html':'bar_html'})
self.matches('zzz/:_', '/zzz/abc', {'_':'abc'})
@@ -413,7 +416,8 @@ def test_generator_functional_newstyle(self):
self.generates('/{x}*y', {'x':unicode('/La Pe\xc3\xb1a', 'utf-8'),
'y':'/rest/of/path'},
'/%2FLa%20Pe%C3%B1a/rest/of/path')
- self.generates('*traverse', {'traverse':('a', u'La Pe\xf1a')},
+ self.generates('*traverse', {'traverse':('a',
+ text_('La Pe\xf1a', 'utf-8'))},
'/a/La%20Pe%C3%B1a')
self.generates('/foo/{id}.html', {'id':'bar'}, '/foo/bar.html')
self.generates('/foo/{_}', {'_':'20'}, '/foo/20')
@@ -433,7 +437,8 @@ def test_generator_functional_oldstyle(self):
self.generates('/:x*y', {'x':unicode('/La Pe\xc3\xb1a', 'utf-8'),
'y':'/rest/of/path'},
'/%2FLa%20Pe%C3%B1a/rest/of/path')
- self.generates('*traverse', {'traverse':('a', u'La Pe\xf1a')},
+ self.generates('*traverse', {'traverse':('a',
+ text_('La Pe\xf1a', 'utf-8'))},
'/a/La%20Pe%C3%B1a')
self.generates('/foo/:id.html', {'id':'bar'}, '/foo/bar.html')
self.generates('/foo/:_', {'_':'20'}, '/foo/20')
View
4 pyramid/tests/test_util.py
@@ -1,4 +1,5 @@
import unittest
+import sys
class TestDottedNameResolver(unittest.TestCase):
def _makeOne(self, package=None):
@@ -9,7 +10,8 @@ def config_exc(self, func, *arg, **kw):
from pyramid.exceptions import ConfigurationError
try:
func(*arg, **kw)
- except ConfigurationError, e:
+ except ConfigurationError:
+ e = sys.exc_info()[1]
return e
else:
raise AssertionError('Invalid not raised') # pragma: no cover
View
9 pyramid/traversal.py
@@ -1,3 +1,4 @@
+import sys
import urllib
import warnings
@@ -11,11 +12,14 @@
from pyramid.interfaces import ITraverser
from pyramid.interfaces import VH_ROOT_KEY
+from pyramid.compat import text_
from pyramid.encode import url_quote
from pyramid.exceptions import URLDecodeError
from pyramid.location import lineage
from pyramid.threadlocal import get_current_registry
+empty = text_('')
+
def find_root(resource):
""" Find the root node in the resource tree to which ``resource``
belongs. Note that ``resource`` should be :term:`location`-aware.
@@ -478,7 +482,8 @@ def traversal_path(path):
segment = urllib.unquote(segment)
try:
segment = segment.decode('utf-8')
- except UnicodeDecodeError, e:
+ except UnicodeDecodeError:
+ e = sys.exc_info()[1]
raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason)
if not segment or segment == '.':
continue
@@ -639,7 +644,7 @@ def __call__(self, request):
ob = next
i += 1
- return {'context':ob, 'view_name':u'', 'subpath':subpath,
+ return {'context':ob, 'view_name':empty, 'subpath':subpath,
'traversed':vpath_tuple, 'virtual_root':vroot,
'virtual_root_path':vroot_tuple, 'root':root}
View
4 pyramid/tweens.py
@@ -15,11 +15,11 @@ def excview_tween(request):
attrs = request.__dict__
try:
response = handler(request)
- except Exception, exc:
+ except Exception:
# WARNING: do not assign the result of sys.exc_info() to a
# local var here, doing so will cause a leak
attrs['exc_info'] = sys.exc_info()
- attrs['exception'] = exc
+ exc = attrs['exception'] = attrs['exc_info'][1]
# clear old generated request.response, if any; it may
# have been mutated by the view, and its state is not
# sane (e.g. caching headers)
View
10 pyramid/urldispatch.py
@@ -1,10 +1,11 @@
import re
-from urllib import unquote
+import sys
from zope.interface import implements
from pyramid.interfaces import IRoutesMapper
from pyramid.interfaces import IRoute
+from pyramid.compat import url_unquote
from pyramid.encode import url_quote
from pyramid.exceptions import URLDecodeError
from pyramid.traversal import traversal_path
@@ -133,14 +134,15 @@ def matcher(path):
if m is None:
return m
d = {}
- for k, v in m.groupdict().iteritems():
+ for k, v in m.groupdict().items():
if k == star:
d[k] = traversal_path(v)
else:
- encoded = unquote(v)
+ encoded = url_unquote(v)
try:
d[k] = encoded.decode('utf-8')
- except UnicodeDecodeError, e:
+ except UnicodeDecodeError:
+ e = sys.exc_info()[1]
raise URLDecodeError(
e.encoding, e.object, e.start, e.end, e.reason
)
View
7 pyramid/util.py
@@ -2,6 +2,7 @@
import sys
import weakref
+from pyramid.compat import string_types
from pyramid.exceptions import ConfigurationError
from pyramid.path import package_of
@@ -69,7 +70,7 @@ def __init__(self, package):
self.package_name = None
self.package = None
else:
- if isinstance(package, basestring):
+ if isinstance(package, string_types):
try:
__import__(package)
except ImportError:
@@ -132,12 +133,12 @@ def _zope_dottedname_style(self, value):
return found
def resolve(self, dotted):
- if not isinstance(dotted, basestring):
+ if not isinstance(dotted, string_types):
raise ConfigurationError('%r is not a string' % (dotted,))
return self.maybe_resolve(dotted)
def maybe_resolve(self, dotted):
- if isinstance(dotted, basestring):
+ if isinstance(dotted, string_types):
if ':' in dotted:
return self._pkg_resources_style(dotted)
else:
View
3 pyramid/view.py
@@ -7,6 +7,7 @@
from pyramid.interfaces import IView
from pyramid.interfaces import IViewClassifier
+from pyramid.compat import map_
from pyramid.httpexceptions import HTTPFound
from pyramid.httpexceptions import default_exceptionresponse_view
from pyramid.path import caller_package
@@ -52,7 +53,7 @@ def render_view_to_response(context, request, name='', secure=True):
disallowed.
If ``secure`` is ``False``, no permission checking is done."""
- provides = [IViewClassifier] + map(providedBy, (request, context))
+ provides = [IViewClassifier] + map_(providedBy, (request, context))
try:
reg = request.registry
except AttributeError:
View
36 setup.py
@@ -18,6 +18,9 @@
from setuptools import setup, find_packages
+PY3 = sys.version_info[0] == 3
+JYTHON = platform.system() != 'Java'
+
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
@@ -28,9 +31,6 @@
install_requires=[
'Chameleon >= 1.2.3',
'Mako >= 0.3.6', # strict_undefined
- 'Paste > 1.7', # temp version pin to prevent PyPi install failure :-(
- 'PasteDeploy',
- 'PasteScript >= 1.7.4', # "here" in logging fileConfig
'WebOb >= 1.0.2', # no "default_charset"; request.script_name doesnt error
'repoze.lru',
'setuptools',
@@ -40,21 +40,29 @@
'translationstring',
]
-if platform.system() == 'Java':
- tests_require = install_requires + [
- 'WebTest',
- 'virtualenv',
- 'zope.component>=3.11.0',
- ]
-else:
- tests_require= install_requires + [
+if not PY3:
+ install_requires.extend([
+ 'Paste > 1.7', # temp version pin to prevent PyPi install failure :-(
+ 'PasteDeploy',
+ 'PasteScript >= 1.7.4', # "here" in logging fileConfig
+ ])
+
+tests_require = install_requires + [
+ 'WebTest',
+ 'virtualenv',
+ ]
+
+if not JYTHON:
+ tests_require.extend([
'Sphinx',
'docutils',
'repoze.sphinx.autointerface',
- 'WebTest',
- 'virtualenv',
+ ])
+
+if not PY3:
+ tests_require.extend([
'zope.component>=3.11.0',
- ]
+ ])
if sys.version_info[:2] < (2, 6):
install_requires.append('simplejson')

0 comments on commit e6c2d2e

Please sign in to comment.
Something went wrong with that request. Please try again.