I have written a short function in Python3 to parse HTTP headers. I was wondering if anyone would be able to take a look at it and tell me if there is anything that I could have done differently to make the code better. What I have currently produces the required outcome but I am not sure if there would be any situation in which this code would not produce the desired result.
This is what I have:
def _parse_headers(self, headers):
lines = headers.split("\r\n")
info = lines[0].split(" ")
method = None
path = None
protocol = None
headers = {}
if len(info) > 0:
method = info[0]
if len(info) > 1:
path = info[1]
if len(info) > 2:
protocol = info[2]
for line in lines[1:]:
if line:
parts = line.split(":")
key = None
value = None
if len(parts) > 0:
key = parts[0]
if len(parts) > 1:
value = parts[1]
if not key is None and not value is None:
headers[key.strip().upper()] = value.strip()
return {
"method": method,
"path": path,
"protocol": protocol,
"headers": headers
}