~kiko/checkbox/pluggable-questions

« back to all changes in this revision

Viewing changes to hwtest/contrib/urllib2_file.py

  • Committer: Christian Reis
  • Date: 2007-09-19 21:45:48 UTC
  • Revision ID: christian.reis@canonical.com-20070919214548-g105a8uww595nl0y
Rip out curl support, and use urllib2 and a contributed module that handle file posts to submit data. Format data for submission to Launchpad. Almost works -- the hard part, posting the data, is sorted.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
####
 
3
# Version: 0.2.0
 
4
#  - UTF-8 filenames are now allowed (Eli Golovinsky)<br/>
 
5
#  - File object is no more mandatory, Object only needs to have seek() read() attributes (Eli Golovinsky)<br/>
 
6
#
 
7
# Version: 0.1.0
 
8
#  - upload is now done with chunks (Adam Ambrose)
 
9
#
 
10
# Version: older
 
11
# THANKS TO:
 
12
# bug fix: kosh @T aesaeion.com
 
13
# HTTPS support : Ryan Grow <ryangrow @T yahoo.com>
 
14
 
 
15
# Copyright (C) 2004,2005,2006 Fabien SEISEN
 
16
 
17
# This library is free software; you can redistribute it and/or
 
18
# modify it under the terms of the GNU Lesser General Public
 
19
# License as published by the Free Software Foundation; either
 
20
# version 2.1 of the License, or (at your option) any later version.
 
21
 
22
# This library is distributed in the hope that it will be useful,
 
23
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
24
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 
25
# Lesser General Public License for more details.
 
26
 
27
# You should have received a copy of the GNU Lesser General Public
 
28
# License along with this library; if not, write to the Free Software
 
29
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
30
 
31
# you can contact me at: <fabien@seisen.org>
 
32
# http://fabien.seisen.org/python/
 
33
#
 
34
# Also modified by Adam Ambrose (aambrose @T pacbell.net) to write data in
 
35
# chunks (hardcoded to CHUNK_SIZE for now), so the entire contents of the file
 
36
# don't need to be kept in memory.
 
37
#
 
38
"""
 
39
enable to upload files using multipart/form-data
 
40
 
 
41
idea from:
 
42
upload files in python:
 
43
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
 
44
 
 
45
timeoutsocket.py: overriding Python socket API:
 
46
 http://www.timo-tasi.org/python/timeoutsocket.py
 
47
 http://mail.python.org/pipermail/python-announce-list/2001-December/001095.html
 
48
 
 
49
import urllib2_files
 
50
import urllib2
 
51
u = urllib2.urlopen('http://site.com/path' [, data])
 
52
 
 
53
data can be a mapping object or a sequence of two-elements tuples
 
54
(like in original urllib2.urlopen())
 
55
varname still need to be a string and
 
56
value can be string of a file object
 
57
eg:
 
58
  ((varname, value),
 
59
   (varname2, value),
 
60
  )
 
61
  or
 
62
  { name:  value,
 
63
    name2: value2
 
64
  }
 
65
 
 
66
"""
 
67
 
 
68
import os
 
69
import socket
 
70
import sys
 
71
import stat
 
72
import mimetypes
 
73
import mimetools
 
74
import httplib
 
75
import urllib
 
76
import urllib2
 
77
 
 
78
CHUNK_SIZE = 65536
 
79
 
 
80
def get_content_type(filename):
 
81
    return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
 
82
 
 
83
# if sock is None, juste return the estimate size
 
84
def send_data(v_vars, v_files, boundary, sock=None):
 
85
    l = 0
 
86
    for (k, v) in v_vars:
 
87
        buffer=''
 
88
        buffer += '--%s\r\n' % boundary
 
89
        buffer += 'Content-Disposition: form-data; name="%s"\r\n' % k
 
90
        buffer += '\r\n'
 
91
        buffer += v + '\r\n'
 
92
        if sock:
 
93
            sock.send(buffer)
 
94
        l += len(buffer)
 
95
    for (k, v) in v_files:
 
96
        fd = v
 
97
        if hasattr(fd, 'size'):
 
98
            file_size = fd.size
 
99
        else:
 
100
            file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
 
101
        name = fd.name.split('/')[-1]
 
102
        if isinstance(name, unicode):
 
103
            name = name.encode('UTF-8')
 
104
        buffer=''
 
105
        buffer += '--%s\r\n' % boundary
 
106
        buffer += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' \
 
107
                  % (k, name)
 
108
        buffer += 'Content-Type: %s\r\n' % get_content_type(name)
 
109
        buffer += 'Content-Length: %s\r\n' % file_size
 
110
        buffer += '\r\n'
 
111
 
 
112
        l += len(buffer)
 
113
        if sock:
 
114
            sock.send(buffer)
 
115
            if hasattr(fd, 'seek'):
 
116
                fd.seek(0)
 
117
            while True:
 
118
                chunk = fd.read(CHUNK_SIZE)
 
119
                if not chunk: break
 
120
                sock.send(chunk)
 
121
 
 
122
        l += file_size
 
123
    buffer='\r\n'
 
124
    buffer += '--%s--\r\n' % boundary
 
125
    buffer += '\r\n'
 
126
    if sock:
 
127
        sock.send(buffer)
 
128
    l += len(buffer)
 
129
    return l
 
130
 
 
131
# mainly a copy of HTTPHandler from urllib2
 
132
class newHTTPHandler(urllib2.BaseHandler):
 
133
    def http_open(self, req):
 
134
        return self.do_open(httplib.HTTP, req)
 
135
 
 
136
    def do_open(self, http_class, req):
 
137
        data = req.get_data()
 
138
        v_files=[]
 
139
        v_vars=[]
 
140
        # mapping object (dict)
 
141
        if req.has_data() and type(data) != str:
 
142
            if hasattr(data, 'items'):
 
143
                data = data.items()
 
144
            else:
 
145
                try:
 
146
                    if len(data) and not isinstance(data[0], tuple):
 
147
                        raise TypeError
 
148
                except TypeError:
 
149
                    ty, va, tb = sys.exc_info()
 
150
                    raise TypeError, "not a valid non-string sequence or mapping object", tb
 
151
                
 
152
            for (k, v) in data:
 
153
                if hasattr(v, 'read'):
 
154
                    v_files.append((k, v))
 
155
                else:
 
156
                    v_vars.append( (k, v) )
 
157
        # no file ? convert to string
 
158
        if len(v_vars) > 0 and len(v_files) == 0:
 
159
            data = urllib.urlencode(v_vars)
 
160
            v_files=[]
 
161
            v_vars=[]
 
162
        host = req.get_host()
 
163
        if not host:
 
164
            raise urllib2.URLError('no host given')
 
165
 
 
166
        h = http_class(host) # will parse host:port
 
167
        if req.has_data():
 
168
            h.putrequest('POST', req.get_selector())
 
169
            if not 'Content-type' in req.headers:
 
170
                if len(v_files) > 0:
 
171
                    boundary = mimetools.choose_boundary()
 
172
                    l = send_data(v_vars, v_files, boundary)
 
173
                    h.putheader('Content-Type',
 
174
                                'multipart/form-data; boundary=%s' % boundary)
 
175
                    h.putheader('Content-length', str(l))
 
176
                else:
 
177
                    h.putheader('Content-type',
 
178
                                'application/x-www-form-urlencoded')
 
179
                    if not 'Content-length' in req.headers:
 
180
                        h.putheader('Content-length', '%d' % len(data))
 
181
        else:
 
182
               h.putrequest('GET', req.get_selector())
 
183
 
 
184
        scheme, sel = urllib.splittype(req.get_selector())
 
185
        sel_host, sel_path = urllib.splithost(sel)
 
186
        h.putheader('Host', sel_host or host)
 
187
        for name, value in self.parent.addheaders:
 
188
            name = name.capitalize()
 
189
            if name not in req.headers:
 
190
                h.putheader(name, value)
 
191
        for k, v in req.headers.items():
 
192
            h.putheader(k, v)
 
193
        # httplib will attempt to connect() here.  be prepared
 
194
        # to convert a socket error to a URLError.
 
195
        try:
 
196
            h.endheaders()
 
197
        except socket.error, err:
 
198
            raise urllib2.URLError(err)
 
199
 
 
200
        if req.has_data():
 
201
            if len(v_files) >0:
 
202
                l = send_data(v_vars, v_files, boundary, h)
 
203
            elif len(v_vars) > 0:
 
204
                # if data is passed as dict ...
 
205
                data = urllib.urlencode(v_vars)
 
206
                h.send(data)
 
207
            else:
 
208
                # "normal" urllib2.urlopen()
 
209
                h.send(data)
 
210
 
 
211
        code, msg, hdrs = h.getreply()
 
212
        fp = h.getfile()
 
213
        if code == 200:
 
214
            resp = urllib.addinfourl(fp, hdrs, req.get_full_url())
 
215
            resp.code = code
 
216
            resp.msg = msg
 
217
            return resp
 
218
        else:
 
219
            return self.parent.error('http', req, fp, code, msg, hdrs)
 
220
 
 
221
urllib2._old_HTTPHandler = urllib2.HTTPHandler
 
222
urllib2.HTTPHandler = newHTTPHandler
 
223
 
 
224
class newHTTPSHandler(newHTTPHandler):
 
225
    def https_open(self, req):
 
226
        return self.do_open(httplib.HTTPS, req)
 
227
    
 
228
urllib2.HTTPSHandler = newHTTPSHandler
 
229
 
 
230
if __name__ == '__main__':
 
231
    import getopt
 
232
    import urllib2
 
233
    import urllib2_file
 
234
    import string
 
235
    import sys
 
236
 
 
237
    def usage(progname):
 
238
        print """
 
239
SYNTAX: %s -u url -f file [-v]
 
240
""" % progname
 
241
    
 
242
    try:
 
243
        opts, args = getopt.getopt(sys.argv[1:], 'hvu:f:')
 
244
    except getopt.GetoptError, errmsg:
 
245
        print "ERROR:", errmsg
 
246
        sys.exit(1)
 
247
 
 
248
    v_url = ''
 
249
    v_verbose = 0
 
250
    v_file = ''
 
251
 
 
252
    for name, value in opts:
 
253
        if name in ('-h',):
 
254
            usage(sys.argv[0])
 
255
            sys.exit(0)
 
256
        elif name in ('-v',):
 
257
            v_verbose += 1
 
258
        elif name in ('-u',):
 
259
            v_url = value
 
260
        elif name in ('-f',):
 
261
            v_file = value
 
262
        else:
 
263
            print "invalid argument:", name
 
264
            sys.exit(2)
 
265
 
 
266
    error = 0
 
267
    if v_url == '':
 
268
        print "need -u"
 
269
        error += 1
 
270
    if v_file == '':
 
271
        print "need -f"
 
272
        error += 1
 
273
 
 
274
    if error > 0:
 
275
        sys.exit(3)
 
276
        
 
277
    fd = open(v_file, 'r')
 
278
    data = {
 
279
        'filename' : fd,
 
280
        }
 
281
    # u = urllib2.urlopen(v_url, data)
 
282
    req = urllib2.Request(v_url, data, {})
 
283
    try:
 
284
        u = urllib2.urlopen(req)
 
285
    except urllib2.HTTPError, errobj:
 
286
        print "HTTPError:", errobj.code
 
287
        
 
288
    else:
 
289
        buf = u.read()
 
290
        print "OK"