-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
73 lines (56 loc) · 1.88 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from datetime import timedelta
import requests
def parse_content_type(content_type_header: str) -> str:
return content_type_header.split(';')[0]
def get_content_type(response: requests.Response) -> str:
return parse_content_type(response.headers.get('content-type', ''))
language_map = {
'text': 'text',
'text-plain': 'text',
'json': 'json',
'js': 'js',
'xml-application': 'xml',
'xml-text': 'xml',
'html': 'html',
}
content_type_map = {
'text': 'text/plain',
'text-plain': 'text/plain',
'json': 'application/json',
'js': 'application/javascript',
'xml-application': 'application/xml',
'xml-text': 'text/xml',
'html': 'text/html',
}
content_type_map_reverse = {v: k for k, v in content_type_map.items()}
def get_language_for_mime_type(mime_type: str) -> str:
"""
Gets the GtkSource.LanguageManager language id for a given mime type.
Falls back to text if not found.
"""
return language_map[content_type_map_reverse.get(mime_type) or 'text']
def sizeof_fmt(num: float, suffix='B') -> str:
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, 'Y', suffix)
def timedelta_fmt(delta: timedelta) -> str:
ts = delta.total_seconds()
if ts >= 1:
for unit in ['s', 'M', 'H']:
if abs(ts) < 60:
return '%3.1f %s' % (ts, unit)
ts /= 60
else:
mcs = delta.microseconds
for unit in ['μs', 'ms']:
if mcs < 1000:
return '%d %s' % (mcs, unit)
mcs /= 1000
return str(delta)
def format_response_size(response: requests.Response) -> str:
cl = response.headers.get('content-length')
if cl:
return sizeof_fmt(float(cl))
return sizeof_fmt(float(len(response.content)))