def read(source, data=None, multipart=False, timeout=30, username=None, password=None, headers=None): if multipart: register_openers() datagen, headers = multipart_encode(data) # {'file': open("DSC0001.jpg", "rb")} request = urllib2.Request(source, datagen, headers) elif data is not None: if type(data) == dict: data = urllib.urlencode(data) request = urllib2.Request(source, data) else: request = urllib2.Request(source) if username and password: import base64 auth = base64.b64encode("%s:%s" % (username, password)).replace("\n", "") request.add_header("Authorization", "Basic %s" % auth) if headers: for header, value in headers.items(): request.add_header(header, value) return urllib2.urlopen(request, timeout=timeout).read()
def post(self): content_type = self.request.headers['Content-Type'] if not content_type.lower().startswith('multipart/form-data'): raise Exception('Only accepts multipart form-data.') meta = {} for item in content_type.split(';'): if item.find('=') > -1: pair = item.split('=') meta[pair[0].strip()] = pair[1].replace('"', '').strip() file_vars = self.request.body_file.vars['fileupload'] if not file_vars.type.lower().startswith('image'): raise ValueError('This is not a image file.') datagen, headers = multipart_encode([('key', settings.IMAGE_SHACK_API_KEY), MultipartParam(file_vars.name, fileobj=file_vars.file, filename=file_vars.filename, filetype=file_vars.type)]) result = urlfetch.fetch( url='http://www.imageshack.us/upload_api.php', payload=''.join(datagen), method=urlfetch.POST, headers=headers) file_vars.file.close() self.response.out.write(json.dumps({'filelink': minidom.parseString(result.content).getElementsByTagName('image_link')[0].firstChild.nodeValue}))