aboutsummaryrefslogtreecommitdiffstats
path: root/netlib/http/headers.py
diff options
context:
space:
mode:
Diffstat (limited to 'netlib/http/headers.py')
-rw-r--r--netlib/http/headers.py56
1 files changed, 42 insertions, 14 deletions
diff --git a/netlib/http/headers.py b/netlib/http/headers.py
index 60d3f429..14888ea9 100644
--- a/netlib/http/headers.py
+++ b/netlib/http/headers.py
@@ -2,27 +2,28 @@ from __future__ import absolute_import, print_function, division
import re
-try:
- from collections.abc import MutableMapping
-except ImportError: # pragma: no cover
- from collections import MutableMapping # Workaround for Python < 3.3
-
import six
-from ..multidict import MultiDict
-from ..utils import always_bytes
+from netlib import multidict
+from netlib import strutils
# See also: http://lucumr.pocoo.org/2013/7/2/the-updated-guide-to-unicode/
if six.PY2: # pragma: no cover
- _native = lambda x: x
- _always_bytes = lambda x: x
+ def _native(x):
+ return x
+
+ def _always_bytes(x):
+ return x
else:
# While headers _should_ be ASCII, it's not uncommon for certain headers to be utf-8 encoded.
- _native = lambda x: x.decode("utf-8", "surrogateescape")
- _always_bytes = lambda x: always_bytes(x, "utf-8", "surrogateescape")
+ def _native(x):
+ return x.decode("utf-8", "surrogateescape")
+
+ def _always_bytes(x):
+ return strutils.always_bytes(x, "utf-8", "surrogateescape")
-class Headers(MultiDict):
+class Headers(multidict.MultiDict):
"""
Header class which allows both convenient access to individual headers as well as
direct access to the underlying raw data. Provides a full dictionary interface.
@@ -70,7 +71,7 @@ class Headers(MultiDict):
For use with the "Set-Cookie" header, see :py:meth:`get_all`.
"""
- def __init__(self, fields=None, **headers):
+ def __init__(self, fields=(), **headers):
"""
Args:
fields: (optional) list of ``(name, value)`` header byte tuples,
@@ -91,7 +92,7 @@ class Headers(MultiDict):
headers = {
_always_bytes(name).replace(b"_", b"-"): _always_bytes(value)
for name, value in six.iteritems(headers)
- }
+ }
self.update(headers)
@staticmethod
@@ -174,3 +175,30 @@ class Headers(MultiDict):
fields.append([name, value])
self.fields = fields
return replacements
+
+
+def parse_content_type(c):
+ """
+ A simple parser for content-type values. Returns a (type, subtype,
+ parameters) tuple, where type and subtype are strings, and parameters
+ is a dict. If the string could not be parsed, return None.
+
+ E.g. the following string:
+
+ text/html; charset=UTF-8
+
+ Returns:
+
+ ("text", "html", {"charset": "UTF-8"})
+ """
+ parts = c.split(";", 1)
+ ts = parts[0].split("/", 1)
+ if len(ts) != 2:
+ return None
+ d = {}
+ if len(parts) == 2:
+ for i in parts[1].split(";"):
+ clause = i.split("=", 1)
+ if len(clause) == 2:
+ d[clause[0].strip()] = clause[1].strip()
+ return ts[0].lower(), ts[1].lower(), d