-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathutils.py
67 lines (54 loc) · 1.93 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
"""Wykop utils module."""
import mimetypes
from pkg_resources import get_distribution, DistributionNotFound
from six import b, u, PY3, text_type, string_types
from six.moves.urllib.request import pathname2url
def paramsencode(d):
return ','.join(['%s,%s' % (k, d[k]) for k in sorted(d)])
def dictmap(f, d):
return dict([(k_v[0], f(k_v[1])) for k_v in iter(d.items())])
def mimetype(filename):
return mimetypes.guess_type(pathname2url(filename))[0]
def force_bytes(s, encoding='utf-8', errors='strict'):
if isinstance(s, bytes):
if encoding == 'utf-8':
return s
else:
return s.decode('utf-8', errors).encode(encoding, errors)
if not isinstance(s, string_types):
try:
if PY3:
return text_type(s).encode(encoding)
else:
return bytes(s)
except UnicodeEncodeError:
if isinstance(s, Exception):
return b(' ').join(force_bytes(arg, encoding, errors)
for arg in s)
return text_type(s).encode(encoding, errors)
else:
return s.encode(encoding, errors)
def force_text(s, encoding='utf-8', errors='strict'):
if issubclass(type(s), text_type):
return s
try:
if not issubclass(type(s), string_types):
if PY3:
if isinstance(s, bytes):
s = text_type(s, encoding, errors)
else:
s = text_type(s)
elif hasattr(s, '__unicode__'):
s = text_type(s)
else:
s = text_type(bytes(s), encoding, errors)
else:
s = s.decode(encoding, errors)
except UnicodeDecodeError:
s = u(' ').join(force_text(arg, encoding, errors) for arg in s)
return s
def get_version():
try:
return get_distribution('wykop').version
except DistributionNotFound:
return 'dev'