diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/pyramid/authentication.py | 13 | ||||
| -rw-r--r-- | src/pyramid/compat.py | 35 | ||||
| -rw-r--r-- | src/pyramid/config/__init__.py | 3 | ||||
| -rw-r--r-- | src/pyramid/config/predicates.py | 3 | ||||
| -rw-r--r-- | src/pyramid/csrf.py | 12 | ||||
| -rw-r--r-- | src/pyramid/httpexceptions.py | 3 | ||||
| -rw-r--r-- | src/pyramid/registry.py | 5 | ||||
| -rw-r--r-- | src/pyramid/request.py | 11 | ||||
| -rw-r--r-- | src/pyramid/session.py | 5 | ||||
| -rw-r--r-- | src/pyramid/testing.py | 4 | ||||
| -rw-r--r-- | src/pyramid/traversal.py | 10 | ||||
| -rw-r--r-- | src/pyramid/url.py | 2 | ||||
| -rw-r--r-- | src/pyramid/urldispatch.py | 4 | ||||
| -rw-r--r-- | src/pyramid/util.py | 71 |
14 files changed, 87 insertions, 94 deletions
diff --git a/src/pyramid/authentication.py b/src/pyramid/authentication.py index 05131a521..21cfc0c0e 100644 --- a/src/pyramid/authentication.py +++ b/src/pyramid/authentication.py @@ -13,13 +13,11 @@ from zope.interface import implementer from webob.cookies import CookieProfile -from pyramid.compat import bytes_, ascii_native_, native_ - from pyramid.interfaces import IAuthenticationPolicy, IDebugLogger from pyramid.security import Authenticated, Everyone -from pyramid.util import strings_differ +from pyramid.util import strings_differ, bytes_, ascii_, text_ from pyramid.util import SimpleSerializer VALID_TOKEN = re.compile(r"^[A-Za-z][A-Za-z0-9+_-]*$") @@ -747,7 +745,7 @@ def parse_ticket(secret, ticket, ip, hashalg='md5'): If the ticket cannot be parsed, a ``BadTicket`` exception will be raised with an explanation. """ - ticket = native_(ticket).strip('"') + ticket = text_(ticket).strip('"') digest_size = hashlib.new(hashalg).digest_size * 2 digest = ticket[:digest_size] try: @@ -866,16 +864,13 @@ class AuthTktCookieHelper(object): domain=None, samesite='Lax', ): - - serializer = SimpleSerializer() - self.cookie_profile = CookieProfile( cookie_name=cookie_name, secure=secure, max_age=max_age, httponly=http_only, path=path, - serializer=serializer, + serializer=SimpleSerializer(), samesite=samesite, ) @@ -1045,7 +1040,7 @@ class AuthTktCookieHelper(object): for token in tokens: if isinstance(token, str): try: - token = ascii_native_(token) + token = ascii_(token) except UnicodeEncodeError: raise ValueError("Invalid token %r" % (token,)) if not (isinstance(token, str) and VALID_TOKEN.match(token)): diff --git a/src/pyramid/compat.py b/src/pyramid/compat.py index 30fc10395..ec0ca7017 100644 --- a/src/pyramid/compat.py +++ b/src/pyramid/compat.py @@ -9,38 +9,3 @@ try: # pragma: no cover except BaseException: # pragma: no cover __pypy__ = None PYPY = False - - -def text_(s, encoding='latin-1', errors='strict'): - """ If ``s`` is an instance of ``bytes``, return - ``s.decode(encoding, errors)``, otherwise return ``s``""" - if isinstance(s, bytes): - return s.decode(encoding, errors) - return s - - -def bytes_(s, encoding='latin-1', errors='strict'): - """ If ``s`` is an instance of ``str``, return - ``s.encode(encoding, errors)``, otherwise return ``s``""" - if isinstance(s, str): - return s.encode(encoding, errors) - return s - - -def ascii_native_(s): - """ - If ``s`` is an instance of ``str``, return - ``s.encode('ascii')``, otherwise return ``str(s, 'ascii', 'strict')`` - """ - if isinstance(s, str): - s = s.encode('ascii') - return str(s, 'ascii', 'strict') - - -def native_(s, encoding='latin-1', errors='strict'): - """ If ``s`` is an instance of ``str``, return - ``s``, otherwise return ``str(s, encoding, errors)`` - """ - if isinstance(s, str): - return s - return str(s, encoding, errors) diff --git a/src/pyramid/config/__init__.py b/src/pyramid/config/__init__.py index 198532e0c..072b654c4 100644 --- a/src/pyramid/config/__init__.py +++ b/src/pyramid/config/__init__.py @@ -35,7 +35,7 @@ from pyramid.settings import aslist from pyramid.threadlocal import manager -from pyramid.util import WeakOrderedSet, object_description +from pyramid.util import WeakOrderedSet, get_callable_name, object_description from pyramid.config.actions import action_method, ActionState from pyramid.config.predicates import not_ @@ -698,6 +698,7 @@ class Configurator( ``add_directive`` does not participate in conflict detection, and later calls to ``add_directive`` will override earlier calls. """ + name = get_callable_name(name) c = self.maybe_dotted(directive) if not hasattr(self.registry, '_directives'): self.registry._directives = {} diff --git a/src/pyramid/config/predicates.py b/src/pyramid/config/predicates.py index 789bcd6ae..3eb07c17d 100644 --- a/src/pyramid/config/predicates.py +++ b/src/pyramid/config/predicates.py @@ -1,13 +1,12 @@ from hashlib import md5 from webob.acceptparse import Accept -from pyramid.compat import bytes_ from pyramid.exceptions import ConfigurationError from pyramid.interfaces import IPredicateList, PHASE1_CONFIG from pyramid.predicates import Notted from pyramid.registry import predvalseq from pyramid.util import TopologicalSorter -from pyramid.util import is_nonstr_iter +from pyramid.util import is_nonstr_iter, bytes_ MAX_ORDER = 1 << 30 diff --git a/src/pyramid/csrf.py b/src/pyramid/csrf.py index ece55ce10..26c628acc 100644 --- a/src/pyramid/csrf.py +++ b/src/pyramid/csrf.py @@ -5,11 +5,16 @@ from webob.cookies import CookieProfile from zope.interface import implementer -from pyramid.compat import bytes_, text_ from pyramid.exceptions import BadCSRFOrigin, BadCSRFToken from pyramid.interfaces import ICSRFStoragePolicy from pyramid.settings import aslist -from pyramid.util import SimpleSerializer, is_same_domain, strings_differ +from pyramid.util import ( + SimpleSerializer, + is_same_domain, + strings_differ, + bytes_, + text_, +) @implementer(ICSRFStoragePolicy) @@ -118,7 +123,6 @@ class CookieCSRFStoragePolicy(object): path='/', samesite='Lax', ): - serializer = SimpleSerializer() self.cookie_profile = CookieProfile( cookie_name=cookie_name, secure=secure, @@ -126,7 +130,7 @@ class CookieCSRFStoragePolicy(object): httponly=httponly, path=path, domains=[domain], - serializer=serializer, + serializer=SimpleSerializer(), samesite=samesite, ) self.cookie_name = cookie_name diff --git a/src/pyramid/httpexceptions.py b/src/pyramid/httpexceptions.py index 7e83f783f..56797dc88 100644 --- a/src/pyramid/httpexceptions.py +++ b/src/pyramid/httpexceptions.py @@ -137,10 +137,9 @@ from zope.interface import implementer from webob import html_escape as _html_escape from webob.acceptparse import create_accept_header -from pyramid.compat import text_ - from pyramid.interfaces import IExceptionResponse from pyramid.response import Response +from pyramid.util import text_ def _no_escape(value): diff --git a/src/pyramid/registry.py b/src/pyramid/registry.py index c24125830..7b2547dd7 100644 --- a/src/pyramid/registry.py +++ b/src/pyramid/registry.py @@ -4,15 +4,12 @@ import threading from zope.interface import implementer from zope.interface.registry import Components -from pyramid.compat import text_ from pyramid.decorator import reify from pyramid.interfaces import IIntrospector, IIntrospectable, ISettings from pyramid.path import CALLER_PACKAGE, caller_package -empty = text_('') - class Registry(Components, dict): """ A registry object is an :term:`application registry`. @@ -77,7 +74,7 @@ class Registry(Components, dict): return result def registerSelfAdapter( - self, required=None, provided=None, name=empty, info=empty, event=True + self, required=None, provided=None, name='', info='', event=True ): # registerAdapter analogue which always returns the object itself # when required is matched diff --git a/src/pyramid/request.py b/src/pyramid/request.py index 5ee87ff58..23c00468d 100644 --- a/src/pyramid/request.py +++ b/src/pyramid/request.py @@ -13,14 +13,17 @@ from pyramid.interfaces import ( ISessionFactory, ) -from pyramid.compat import text_, bytes_, native_ - from pyramid.decorator import reify from pyramid.i18n import LocalizerRequestMixin from pyramid.response import Response, _get_response_factory from pyramid.security import AuthenticationAPIMixin, AuthorizationAPIMixin from pyramid.url import URLMethodsMixin -from pyramid.util import InstancePropertyHelper, InstancePropertyMixin +from pyramid.util import ( + InstancePropertyHelper, + InstancePropertyMixin, + text_, + bytes_, +) from pyramid.view import ViewMethodsMixin @@ -281,7 +284,7 @@ def call_app_with_subpath_as_path_info(request, app): # compute new_path_info new_path_info = '/' + '/'.join( - [native_(x.encode('utf-8'), 'latin-1') for x in subpath] + [text_(x.encode('utf-8'), 'latin-1') for x in subpath] ) if new_path_info != '/': # don't want a sole double-slash diff --git a/src/pyramid/session.py b/src/pyramid/session.py index 1b1bfb3e5..70ac4f55f 100644 --- a/src/pyramid/session.py +++ b/src/pyramid/session.py @@ -8,11 +8,12 @@ from zope.interface import implementer from webob.cookies import JSONSerializer, SignedSerializer -from pyramid.compat import text_, bytes_, native_ from pyramid.csrf import check_csrf_origin, check_csrf_token from pyramid.interfaces import ISession +from pyramid.util import text_, bytes_ + def manage_accessed(wrapped): """ Decorator which causes a cookie to be renewed when an accessor @@ -304,7 +305,7 @@ def BaseCookieSessionFactory( exception is not None ): # dont set a cookie during exceptions return False - cookieval = native_( + cookieval = text_( serializer.dumps((self.accessed, self.created, dict(self))) ) if len(cookieval) > 4064: diff --git a/src/pyramid/testing.py b/src/pyramid/testing.py index af8008e45..04497234b 100644 --- a/src/pyramid/testing.py +++ b/src/pyramid/testing.py @@ -8,7 +8,7 @@ from zope.interface import implementer, alsoProvides from pyramid.interfaces import IRequest, ISession -from pyramid.compat import PYPY, text_ +from pyramid.compat import PYPY from pyramid.config import Configurator from pyramid.decorator import reify @@ -28,7 +28,7 @@ from pyramid.threadlocal import get_current_registry, manager from pyramid.i18n import LocalizerRequestMixin from pyramid.request import CallbackMethodsMixin from pyramid.url import URLMethodsMixin -from pyramid.util import InstancePropertyMixin +from pyramid.util import InstancePropertyMixin, text_ from pyramid.view import ViewMethodsMixin diff --git a/src/pyramid/traversal.py b/src/pyramid/traversal.py index e846881f3..7de4c3f91 100644 --- a/src/pyramid/traversal.py +++ b/src/pyramid/traversal.py @@ -11,13 +11,11 @@ from pyramid.interfaces import ( VH_ROOT_KEY, ) -from pyramid.compat import native_, ascii_native_ - from pyramid.encode import url_quote from pyramid.exceptions import URLDecodeError from pyramid.location import lineage from pyramid.threadlocal import get_current_registry -from pyramid.util import is_nonstr_iter +from pyramid.util import ascii_, is_nonstr_iter, text_ PATH_SEGMENT_SAFE = "~!$&'()*+,;=:@" # from webob PATH_SAFE = PATH_SEGMENT_SAFE + "/" @@ -86,7 +84,7 @@ def find_resource(resource, path): resolved by ``find_resource``. """ if isinstance(path, str): - path = ascii_native_(path) + path = ascii_(path) D = traverse(resource, path) view_name = D['view_name'] context = D['context'] @@ -303,7 +301,7 @@ def traverse(resource, path): # step rather than later down the line as the result of calling # ``traversal_path``). - path = ascii_native_(path) + path = ascii_(path) if path and path[0] == '/': resource = find_root(resource) @@ -592,7 +590,7 @@ def quote_path_segment(segment, safe=PATH_SEGMENT_SAFE): except KeyError: if segment.__class__ not in (str, bytes): segment = str(segment) - result = url_quote(native_(segment, 'utf-8'), safe) + result = url_quote(text_(segment, 'utf-8'), safe) # we don't need a lock to mutate _segment_cache, as the below # will generate exactly one Python bytecode (STORE_SUBSCR) _segment_cache[(segment, safe)] = result diff --git a/src/pyramid/url.py b/src/pyramid/url.py index 730b7de23..22551a349 100644 --- a/src/pyramid/url.py +++ b/src/pyramid/url.py @@ -5,10 +5,10 @@ import os from pyramid.interfaces import IResourceURL, IRoutesMapper, IStaticURLInfo -from pyramid.compat import bytes_ from pyramid.encode import url_quote, urlencode from pyramid.path import caller_package from pyramid.threadlocal import get_current_registry +from pyramid.util import bytes_ from pyramid.traversal import ( ResourceURL, diff --git a/src/pyramid/urldispatch.py b/src/pyramid/urldispatch.py index 97626c5dd..73b7be9f3 100644 --- a/src/pyramid/urldispatch.py +++ b/src/pyramid/urldispatch.py @@ -3,13 +3,11 @@ from zope.interface import implementer from pyramid.interfaces import IRoutesMapper, IRoute -from pyramid.compat import text_ - from pyramid.exceptions import URLDecodeError from pyramid.traversal import quote_path_segment, split_path_info, PATH_SAFE -from pyramid.util import is_nonstr_iter +from pyramid.util import is_nonstr_iter, text_ _marker = object() diff --git a/src/pyramid/util.py b/src/pyramid/util.py index 0688e67d3..ab46c91f7 100644 --- a/src/pyramid/util.py +++ b/src/pyramid/util.py @@ -4,10 +4,6 @@ from hmac import compare_digest import inspect import weakref -from pyramid.exceptions import ConfigurationError, CyclicDependencyError - -from pyramid.compat import bytes_, text_, native_ - from pyramid.path import DottedNameResolver as _DottedNameResolver _marker = object() @@ -20,6 +16,32 @@ class DottedNameResolver(_DottedNameResolver): _DottedNameResolver.__init__(self, package) +def text_(s, encoding='latin-1', errors='strict'): + """ If ``s`` is an instance of ``bytes``, return + ``s.decode(encoding, errors)``, otherwise return ``s``""" + if isinstance(s, bytes): + return s.decode(encoding, errors) + return s + + +def bytes_(s, encoding='latin-1', errors='strict'): + """ If ``s`` is an instance of ``str``, return + ``s.encode(encoding, errors)``, otherwise return ``s``""" + if isinstance(s, str): + return s.encode(encoding, errors) + return s + + +def ascii_(s): + """ + If ``s`` is an instance of ``str``, return + ``s.encode('ascii')``, otherwise return ``str(s, 'ascii', 'strict')`` + """ + if isinstance(s, str): + s = s.encode('ascii') + return str(s, 'ascii', 'strict') + + def is_nonstr_iter(v): if isinstance(v, str): return False @@ -322,11 +344,11 @@ def object_description(object): (possibly shortened) string representation is returned. """ if isinstance(object, str): - return text_(object) + return object if isinstance(object, int): - return text_(str(object)) + return str(object) if isinstance(object, (bool, float, type(None))): - return text_(str(object)) + return str(object) if isinstance(object, set): return shortrepr(object, '}') if isinstance(object, tuple): @@ -337,26 +359,25 @@ def object_description(object): return shortrepr(object, '}') module = inspect.getmodule(object) if module is None: - return text_('object %s' % str(object)) + return 'object %s' % str(object) modulename = module.__name__ if inspect.ismodule(object): - return text_('module %s' % modulename) + return 'module %s' % modulename if inspect.ismethod(object): oself = getattr(object, '__self__', None) - if oself is None: # pragma: no cover - oself = getattr(object, 'im_self', None) - return text_( - 'method %s of class %s.%s' - % (object.__name__, modulename, oself.__class__.__name__) + return 'method %s of class %s.%s' % ( + object.__name__, + modulename, + oself.__class__.__name__, ) if inspect.isclass(object): dottedname = '%s.%s' % (modulename, object.__name__) - return text_('class %s' % dottedname) + return 'class %s' % dottedname if inspect.isfunction(object): dottedname = '%s.%s' % (modulename, object.__name__) - return text_('function %s' % dottedname) - return text_('object %s' % str(object)) + return 'function %s' % dottedname + return 'object %s' % str(object) def shortrepr(object, closer): @@ -487,11 +508,17 @@ class TopologicalSorter(object): has_after.add(b) if not self.req_before.issubset(has_before): + # avoid circular dependency + from pyramid.exceptions import ConfigurationError + raise ConfigurationError( 'Unsatisfied before dependencies: %s' % (', '.join(sorted(self.req_before - has_before))) ) if not self.req_after.issubset(has_after): + # avoid circular dependency + from pyramid.exceptions import ConfigurationError + raise ConfigurationError( 'Unsatisfied after dependencies: %s' % (', '.join(sorted(self.req_after - has_after))) @@ -512,6 +539,9 @@ class TopologicalSorter(object): del graph[root] if graph: + # avoid circular dependency + from pyramid.exceptions import CyclicDependencyError + # loop in input cycledeps = {} for k, v in graph.items(): @@ -533,8 +563,11 @@ def get_callable_name(name): if it is not. """ try: - return native_(name, 'ascii') + return ascii_(name) except (UnicodeEncodeError, UnicodeDecodeError): + # avoid circular dependency + from pyramid.exceptions import ConfigurationError + msg = ( '`name="%s"` is invalid. `name` must be ascii because it is ' 'used on __name__ of the method' @@ -641,7 +674,7 @@ def takes_one_arg(callee, attr=None, argname=None): class SimpleSerializer(object): def loads(self, bstruct): - return native_(bstruct) + return text_(bstruct) def dumps(self, appstruct): return bytes_(appstruct) |
