Ticket #31564: Upload.py

File Upload.py, 1.3 KB (added by Jacob Crabtree, 4 years ago)

PycURL Script for Upload

Line 
1import os
2import pycurl
3from io import BytesIO
4
5
6def config_pycurl(url, file_handle, file_size, response_buffer):
7 # Create the curl object, set the URL and HTTP method
8 c = pycurl.Curl()
9 c.setopt(pycurl.VERBOSE, True)
10 c.setopt(pycurl.URL, url)
11 c.setopt(pycurl.POST, 1)
12
13 # Give curl a buffer to write the remote server's response to
14 c.setopt(pycurl.WRITEDATA, response_buffer)
15
16 c.setopt(pycurl.SSL_VERIFYPEER, 0)
17 c.setopt(pycurl.SSL_VERIFYHOST, 0)
18
19 c.setopt(pycurl.POSTFIELDSIZE, file_size)
20 c.setopt(pycurl.READFUNCTION, file_handle.read)
21 return c
22
23
24def send_pycurl(url, file_path, file_size):
25 resp_buffer = BytesIO()
26
27 input_file = open(file_path, 'rb')
28 c = config_pycurl(url, input_file, file_size, resp_buffer)
29 c.perform()
30
31 # Get HTTP response code, clean up handles
32 resp_code = c.getinfo(c.RESPONSE_CODE)
33 c.close()
34 input_file.close()
35
36 # Get response from the server - iso-8859-1 is the default encoding curl performs
37 resp_body = resp_buffer.getvalue().decode('iso-8859-1')
38 print(f'code: {resp_code}')
39 print(f'response: {resp_body}')
40
41
42if __name__ == '__main__':
43 post_url = 'http://localhost:8000/upload'
44 name = 'test_files/ascii1gb.txt'
45 send_pycurl(post_url, name, os.path.getsize(name))
Back to Top