webssh

Web based ssh client https://github.com/huashengdun/webssh webssh.huashengdun.org/
git clone http://git.hanabi.in/repos/webssh.git
Log | Files | Refs | README | LICENSE

utils.py (1530B)


      1 import mimetypes
      2 import os.path
      3 from uuid import uuid4
      4 from webssh.settings import base_dir
      5 
      6 
      7 def encode_multipart_formdata(fields, files):
      8     """
      9     fields is a sequence of (name, value) elements for regular form fields.
     10     files is a sequence of (name, filename, value) elements for data to be
     11     uploaded as files.
     12     Return (content_type, body) ready for httplib.HTTP instance
     13     """
     14     boundary = uuid4().hex
     15     CRLF = '\r\n'
     16     L = []
     17     for (key, value) in fields:
     18         L.append('--' + boundary)
     19         L.append('Content-Disposition: form-data; name="%s"' % key)
     20         L.append('')
     21         L.append(value)
     22     for (key, filename, value) in files:
     23         L.append('--' + boundary)
     24         L.append(
     25             'Content-Disposition: form-data; name="%s"; filename="%s"' % (
     26                 key, filename
     27             )
     28         )
     29         L.append('Content-Type: %s' % get_content_type(filename))
     30         L.append('')
     31         L.append(value)
     32     L.append('--' + boundary + '--')
     33     L.append('')
     34     body = CRLF.join(L)
     35     content_type = 'multipart/form-data; boundary=%s' % boundary
     36     return content_type, body
     37 
     38 
     39 def get_content_type(filename):
     40     return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
     41 
     42 
     43 def read_file(path, encoding='utf-8'):
     44     with open(path, 'rb') as f:
     45         data = f.read()
     46         if encoding is None:
     47             return data
     48         return data.decode(encoding)
     49 
     50 
     51 def make_tests_data_path(filename):
     52     return os.path.join(base_dir, 'tests', 'data', filename)