summaryrefslogtreecommitdiff
path: root/src/werkzeug/_internal.py
diff options
context:
space:
mode:
Diffstat (limited to 'src/werkzeug/_internal.py')
-rw-r--r--src/werkzeug/_internal.py194
1 files changed, 117 insertions, 77 deletions
diff --git a/src/werkzeug/_internal.py b/src/werkzeug/_internal.py
index 36084438..d8b83363 100644
--- a/src/werkzeug/_internal.py
+++ b/src/werkzeug/_internal.py
@@ -8,41 +8,46 @@
:copyright: 2007 Pallets
:license: BSD-3-Clause
"""
+import inspect
import re
import string
-import inspect
-from weakref import WeakKeyDictionary
-from datetime import datetime, date
+from datetime import date
+from datetime import datetime
from itertools import chain
+from weakref import WeakKeyDictionary
-from werkzeug._compat import iter_bytes, text_type, int_to_byte, range_type, \
- integer_types
+from ._compat import int_to_byte
+from ._compat import integer_types
+from ._compat import iter_bytes
+from ._compat import range_type
+from ._compat import text_type
_logger = None
_signature_cache = WeakKeyDictionary()
_epoch_ord = date(1970, 1, 1).toordinal()
-_cookie_params = set((b'expires', b'path', b'comment',
- b'max-age', b'secure', b'httponly',
- b'version'))
-_legal_cookie_chars = (string.ascii_letters
- + string.digits
- + u"/=!#$%&'*+-.^_`|~:").encode('ascii')
-
-_cookie_quoting_map = {
- b',': b'\\054',
- b';': b'\\073',
- b'"': b'\\"',
- b'\\': b'\\\\',
+_cookie_params = {
+ b"expires",
+ b"path",
+ b"comment",
+ b"max-age",
+ b"secure",
+ b"httponly",
+ b"version",
}
-for _i in chain(range_type(32), range_type(127, 256)):
- _cookie_quoting_map[int_to_byte(_i)] = ('\\%03o' % _i).encode('latin1')
+_legal_cookie_chars = (
+ string.ascii_letters + string.digits + u"/=!#$%&'*+-.^_`|~:"
+).encode("ascii")
+_cookie_quoting_map = {b",": b"\\054", b";": b"\\073", b'"': b'\\"', b"\\": b"\\\\"}
+for _i in chain(range_type(32), range_type(127, 256)):
+ _cookie_quoting_map[int_to_byte(_i)] = ("\\%03o" % _i).encode("latin1")
-_octal_re = re.compile(br'\\[0-3][0-7][0-7]')
-_quote_re = re.compile(br'[\\].')
-_legal_cookie_chars_re = br'[\w\d!#%&\'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=]'
-_cookie_re = re.compile(br"""
+_octal_re = re.compile(br"\\[0-3][0-7][0-7]")
+_quote_re = re.compile(br"[\\].")
+_legal_cookie_chars_re = br"[\w\d!#%&\'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=]"
+_cookie_re = re.compile(
+ br"""
(?P<key>[^=;]+)
(?:\s*=\s*
(?P<val>
@@ -51,24 +56,27 @@ _cookie_re = re.compile(br"""
)
)?
\s*;
-""", flags=re.VERBOSE)
+""",
+ flags=re.VERBOSE,
+)
class _Missing(object):
-
def __repr__(self):
- return 'no value'
+ return "no value"
def __reduce__(self):
- return '_missing'
+ return "_missing"
+
_missing = _Missing()
def _get_environ(obj):
- env = getattr(obj, 'environ', obj)
- assert isinstance(env, dict), \
- '%r is not a WSGI environment (has to be a dict)' % type(obj).__name__
+ env = getattr(obj, "environ", obj)
+ assert isinstance(env, dict), (
+ "%r is not a WSGI environment (has to be a dict)" % type(obj).__name__
+ )
return env
@@ -77,7 +85,8 @@ def _log(type, message, *args, **kwargs):
global _logger
if _logger is None:
import logging
- _logger = logging.getLogger('werkzeug')
+
+ _logger = logging.getLogger("werkzeug")
if _logger.level == logging.NOTSET:
_logger.setLevel(logging.INFO)
# Only set up a default log handler if the
@@ -90,7 +99,7 @@ def _log(type, message, *args, **kwargs):
def _parse_signature(func):
"""Return a signature object for the function."""
- if hasattr(func, 'im_func'):
+ if hasattr(func, "im_func"):
func = func.im_func
# if we have a cached validator for this function, return it
@@ -99,7 +108,7 @@ def _parse_signature(func):
return parse
# inspect the function signature and collect all the information
- if hasattr(inspect, 'getfullargspec'):
+ if hasattr(inspect, "getfullargspec"):
tup = inspect.getfullargspec(func)
else:
tup = inspect.getargspec(func)
@@ -109,8 +118,9 @@ def _parse_signature(func):
arguments = []
for idx, name in enumerate(positional):
if isinstance(name, list):
- raise TypeError('cannot parse functions that unpack tuples '
- 'in the function signature')
+ raise TypeError(
+ "cannot parse functions that unpack tuples in the function signature"
+ )
try:
default = defaults[idx - arg_count]
except IndexError:
@@ -150,8 +160,17 @@ def _parse_signature(func):
extra.update(kwargs)
kwargs = {}
- return new_args, kwargs, missing, extra, extra_positional, \
- arguments, vararg_var, kwarg_var
+ return (
+ new_args,
+ kwargs,
+ missing,
+ extra,
+ extra_positional,
+ arguments,
+ vararg_var,
+ kwarg_var,
+ )
+
_signature_cache[func] = parse
return parse
@@ -173,12 +192,19 @@ def _date_to_unix(arg):
class _DictAccessorProperty(object):
-
"""Baseclass for `environ_property` and `header_property`."""
+
read_only = False
- def __init__(self, name, default=None, load_func=None, dump_func=None,
- read_only=None, doc=None):
+ def __init__(
+ self,
+ name,
+ default=None,
+ load_func=None,
+ dump_func=None,
+ read_only=None,
+ doc=None,
+ ):
self.name = name
self.default = default
self.load_func = load_func
@@ -203,21 +229,18 @@ class _DictAccessorProperty(object):
def __set__(self, obj, value):
if self.read_only:
- raise AttributeError('read only property')
+ raise AttributeError("read only property")
if self.dump_func is not None:
value = self.dump_func(value)
self.lookup(obj)[self.name] = value
def __delete__(self, obj):
if self.read_only:
- raise AttributeError('read only property')
+ raise AttributeError("read only property")
self.lookup(obj).pop(self.name, None)
def __repr__(self):
- return '<%s %s>' % (
- self.__class__.__name__,
- self.name
- )
+ return "<%s %s>" % (self.__class__.__name__, self.name)
def _cookie_quote(b):
@@ -263,11 +286,11 @@ def _cookie_unquote(b):
k = q_match.start(0)
if q_match and (not o_match or k < j):
_push(b[i:k])
- _push(b[k + 1:k + 2])
+ _push(b[k + 1 : k + 2])
i = k + 2
else:
_push(b[i:j])
- rv.append(int(b[j + 1:j + 4], 8))
+ rv.append(int(b[j + 1 : j + 4], 8))
i = j + 4
return bytes(rv)
@@ -279,12 +302,12 @@ def _cookie_parse_impl(b):
n = len(b)
while i < n:
- match = _cookie_re.search(b + b';', i)
+ match = _cookie_re.search(b + b";", i)
if not match:
break
- key = match.group('key').strip()
- value = match.group('val') or b''
+ key = match.group("key").strip()
+ value = match.group("val") or b""
i = match.end(0)
# Ignore parameters. We have no interest in them.
@@ -295,20 +318,20 @@ def _cookie_parse_impl(b):
def _encode_idna(domain):
# If we're given bytes, make sure they fit into ASCII
if not isinstance(domain, text_type):
- domain.decode('ascii')
+ domain.decode("ascii")
return domain
# Otherwise check if it's already ascii, then return
try:
- return domain.encode('ascii')
+ return domain.encode("ascii")
except UnicodeError:
pass
# Otherwise encode each part separately
- parts = domain.split('.')
+ parts = domain.split(".")
for idx, part in enumerate(parts):
- parts[idx] = part.encode('idna')
- return b'.'.join(parts)
+ parts[idx] = part.encode("idna")
+ return b".".join(parts)
def _decode_idna(domain):
@@ -317,47 +340,54 @@ def _decode_idna(domain):
# unicode error, then we already have a decoded idna domain
if isinstance(domain, text_type):
try:
- domain = domain.encode('ascii')
+ domain = domain.encode("ascii")
except UnicodeError:
return domain
# Decode each part separately. If a part fails, try to
# decode it with ascii and silently ignore errors. This makes
# most sense because the idna codec does not have error handling
- parts = domain.split(b'.')
+ parts = domain.split(b".")
for idx, part in enumerate(parts):
try:
- parts[idx] = part.decode('idna')
+ parts[idx] = part.decode("idna")
except UnicodeError:
- parts[idx] = part.decode('ascii', 'ignore')
+ parts[idx] = part.decode("ascii", "ignore")
- return '.'.join(parts)
+ return ".".join(parts)
def _make_cookie_domain(domain):
if domain is None:
return None
domain = _encode_idna(domain)
- if b':' in domain:
- domain = domain.split(b':', 1)[0]
- if b'.' in domain:
+ if b":" in domain:
+ domain = domain.split(b":", 1)[0]
+ if b"." in domain:
return domain
raise ValueError(
- 'Setting \'domain\' for a cookie on a server running locally (ex: '
- 'localhost) is not supported by complying browsers. You should '
- 'have something like: \'127.0.0.1 localhost dev.localhost\' on '
- 'your hosts file and then point your server to run on '
- '\'dev.localhost\' and also set \'domain\' for \'dev.localhost\''
+ "Setting 'domain' for a cookie on a server running locally (ex: "
+ "localhost) is not supported by complying browsers. You should "
+ "have something like: '127.0.0.1 localhost dev.localhost' on "
+ "your hosts file and then point your server to run on "
+ "'dev.localhost' and also set 'domain' for 'dev.localhost'"
)
def _easteregg(app=None):
"""Like the name says. But who knows how it works?"""
+
def bzzzzzzz(gyver):
import base64
import zlib
- return zlib.decompress(base64.b64decode(gyver)).decode('ascii')
- gyver = u'\n'.join([x + (77 - len(x)) * u' ' for x in bzzzzzzz(b'''
+
+ return zlib.decompress(base64.b64decode(gyver)).decode("ascii")
+
+ gyver = u"\n".join(
+ [
+ x + (77 - len(x)) * u" "
+ for x in bzzzzzzz(
+ b"""
eJyFlzuOJDkMRP06xRjymKgDJCDQStBYT8BCgK4gTwfQ2fcFs2a2FzvZk+hvlcRvRJD148efHt9m
9Xz94dRY5hGt1nrYcXx7us9qlcP9HHNh28rz8dZj+q4rynVFFPdlY4zH873NKCexrDM6zxxRymzz
4QIxzK4bth1PV7+uHn6WXZ5C4ka/+prFzx3zWLMHAVZb8RRUxtFXI5DTQ2n3Hi2sNI+HK43AOWSY
@@ -388,16 +418,22 @@ p1qXK3Du2mnr5INXmT/78KI12n11EFBkJHHp0wJyLe9MvPNUGYsf+170maayRoy2lURGHAIapSpQ
krEDuNoJCHNlZYhKpvw4mspVWxqo415n8cD62N9+EfHrAvqQnINStetek7RY2Urv8nxsnGaZfRr/
nhXbJ6m/yl1LzYqscDZA9QHLNbdaSTTr+kFg3bC0iYbX/eQy0Bv3h4B50/SGYzKAXkCeOLI3bcAt
mj2Z/FM1vQWgDynsRwNvrWnJHlespkrp8+vO1jNaibm+PhqXPPv30YwDZ6jApe3wUjFQobghvW9p
-7f2zLkGNv8b191cD/3vs9Q833z8t''').splitlines()])
+7f2zLkGNv8b191cD/3vs9Q833z8t"""
+ ).splitlines()
+ ]
+ )
def easteregged(environ, start_response):
def injecting_start_response(status, headers, exc_info=None):
- headers.append(('X-Powered-By', 'Werkzeug'))
+ headers.append(("X-Powered-By", "Werkzeug"))
return start_response(status, headers, exc_info)
- if app is not None and environ.get('QUERY_STRING') != 'macgybarchakku':
+
+ if app is not None and environ.get("QUERY_STRING") != "macgybarchakku":
return app(environ, injecting_start_response)
- injecting_start_response('200 OK', [('Content-Type', 'text/html')])
- return [(u'''
+ injecting_start_response("200 OK", [("Content-Type", "text/html")])
+ return [
+ (
+ u"""
<!DOCTYPE html>
<html>
<head>
@@ -415,5 +451,9 @@ mj2Z/FM1vQWgDynsRwNvrWnJHlespkrp8+vO1jNaibm+PhqXPPv30YwDZ6jApe3wUjFQobghvW9p
<p>the Swiss Army knife of Python web development.</p>
<pre>%s\n\n\n</pre>
</body>
-</html>''' % gyver).encode('latin1')]
+</html>"""
+ % gyver
+ ).encode("latin1")
+ ]
+
return easteregged