a514c1c79d552c5d804133c61e315549680f5172
[plcapi.git] / pycurl / examples / file_upload.py
1 #! /usr/bin/env python
2 # -*- coding: iso-8859-1 -*-
3 # vi:ts=4:et
4 # $Id$
5
6 import os, sys
7 import pycurl
8
9 # Class which holds a file reference and the read callback
10 class FileReader:
11     def __init__(self, fp):
12         self.fp = fp
13     def read_callback(self, size):
14         return self.fp.read(size)
15
16 # Check commandline arguments
17 if len(sys.argv) < 3:
18     print "Usage: %s <url> <file to upload>" % sys.argv[0]
19     raise SystemExit
20 url = sys.argv[1]
21 filename = sys.argv[2]
22
23 if not os.path.exists(filename):
24     print "Error: the file '%s' does not exist" % filename
25     raise SystemExit
26
27 # Initialize pycurl
28 c = pycurl.Curl()
29 c.setopt(pycurl.URL, url)
30 c.setopt(pycurl.UPLOAD, 1)
31
32 # Two versions with the same semantics here, but the filereader version
33 # is useful when you have to process the data which is read before returning
34 if 1:
35     c.setopt(pycurl.READFUNCTION, FileReader(open(filename, 'rb')).read_callback)
36 else:
37     c.setopt(pycurl.READFUNCTION, open(filename, 'rb').read)
38
39 # Set size of file to be uploaded.
40 filesize = os.path.getsize(filename)
41 c.setopt(pycurl.INFILESIZE, filesize)
42
43 # Start transfer
44 print 'Uploading file %s to url %s' % (filename, url)
45 c.perform()
46 c.close()