forked from huashengdun/webssh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
52 lines (44 loc) · 1.49 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
import mimetypes
import os.path
from uuid import uuid4
from webssh.settings import base_dir
def encode_multipart_formdata(fields, files):
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be
uploaded as files.
Return (content_type, body) ready for httplib.HTTP instance
"""
boundary = uuid4().hex
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + boundary)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + boundary)
L.append(
'Content-Disposition: form-data; name="%s"; filename="%s"' % (
key, filename
)
)
L.append('Content-Type: %s' % get_content_type(filename))
L.append('')
L.append(value)
L.append('--' + boundary + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % boundary
return content_type, body
def get_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
def read_file(path, encoding='utf-8'):
with open(path, 'rb') as f:
data = f.read()
if encoding is None:
return data
return data.decode(encoding)
def make_tests_data_path(filename):
return os.path.join(base_dir, 'tests', 'data', filename)