Add a simple parser for content type specifications.

This commit is contained in:
Aldo Cortesi
2012-03-20 10:31:07 +13:00
parent bc3ba4c993
commit 2739cb4861
3 changed files with 39 additions and 0 deletions

View File

@@ -265,6 +265,33 @@ def parse_proxy_spec(url):
return p[:3]
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], ts[1], d
def hostport(scheme, host, port):
"""
Returns the host component, with a port specifcation if needed.