Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
maurosoria
GitHub Repository: maurosoria/dirsearch
Path: blob/master/lib/parse/headers.py
896 views
1
# -*- coding: utf-8 -*-
2
# This program is free software; you can redistribute it and/or modify
3
# it under the terms of the GNU General Public License as published by
4
# the Free Software Foundation; either version 2 of the License, or
5
# (at your option) any later version.
6
#
7
# This program is distributed in the hope that it will be useful,
8
# but WITHOUT ANY WARRANTY; without even the implied warranty of
9
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
# GNU General Public License for more details.
11
#
12
# You should have received a copy of the GNU General Public License
13
# along with this program; if not, write to the Free Software
14
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
15
# MA 02110-1301, USA.
16
#
17
# Author: Mauro Soria
18
19
from __future__ import annotations
20
21
from email.parser import BytesParser
22
23
from lib.core.settings import NEW_LINE
24
from lib.core.structures import CaseInsensitiveDict
25
26
27
class HeadersParser:
28
def __init__(self, headers: str | dict[str, str]) -> None:
29
self.str = self.dict = headers
30
31
if isinstance(headers, str):
32
self.dict = self.str_to_dict(headers)
33
elif isinstance(headers, dict):
34
self.str = self.dict_to_str(headers)
35
self.dict = self.str_to_dict(self.str)
36
37
self.headers = CaseInsensitiveDict(self.dict)
38
39
def get(self, key: str) -> str:
40
return self.headers[key]
41
42
@staticmethod
43
def str_to_dict(headers: str) -> dict[str, str]:
44
if not headers:
45
return {}
46
47
return dict(BytesParser().parsebytes(headers.encode()))
48
49
@staticmethod
50
def dict_to_str(headers: dict[str, str]) -> str:
51
if not headers:
52
return
53
54
return NEW_LINE.join(f"{key}: {value}" for key, value in headers.items())
55
56
def __iter__(self):
57
return iter(self.headers.items())
58
59
def __str__(self) -> str:
60
return self.str
61
62