def send_request(self, method=None, parameters=None, files=None, buffers=None): protocol = 'https://' if USE_SSL else 'http://' url = '%s%s/%s.%s' % (protocol, API_HOST, method, self.format) data = { 'api_key': self.api_key, 'api_secret': self.api_secret } if parameters: data.update(parameters) # Local file is provided, use multi-part form if files or buffers: from multipart import Multipart form = Multipart() for key, value in data.iteritems(): form.field(key, value) if files: for i, file in enumerate(files, 1): if hasattr(file, 'read'): if hasattr(file, 'name'): name = os.path.basename(file.name) else: name = 'attachment_%d' % i close_file = False else: name = os.path.basename(file) file = open(file, 'rb') close_file = True try: form.file(name, name, file.read()) finally: if close_file: file.close() else: for i, buffer in enumerate(buffers, 1): name = 'attachment_%d' % i form.file(name, name, buffer) (content_type, post_data) = form.get() headers = {'Content-Type': content_type} else: post_data = urllib.urlencode(data) headers = {} request = urllib2.Request(url, headers=headers, data=post_data) try: response = urllib2.urlopen(request) response = response.read() except urllib2.HTTPError as e: response = e.read() response_data = json.loads(response) if 'status' in response_data and response_data['status'] == 'failure': raise FaceError(response_data['error_code'], response_data['error_message']) return response_data
def send_request(self, method=None, parameters=None, files=None, buffers=None): protocol = "https://" if USE_SSL else "http://" url = "%s%s/%s.%s" % (protocol, API_HOST, method, self.format) data = {"api_key": self.api_key, "api_secret": self.api_secret} if parameters: data.update(parameters) # Local file is provided, use multi-part form if files or buffers: from multipart import Multipart form = Multipart() for key, value in data.iteritems(): form.field(key, value) if files: for i, file in enumerate(files, 1): if hasattr(file, "read"): if hasattr(file, "name"): name = os.path.basename(file.name) else: name = "attachment_%d" % i close_file = False else: name = os.path.basename(file) file = open(file, "rb") close_file = True try: form.file(name, name, file.read()) finally: if close_file: file.close() else: for i, buffer in enumerate(buffers, 1): name = "attachment_%d" % i form.file(name, name, buffer) (content_type, post_data) = form.get() headers = {"Content-Type": content_type} else: post_data = urllib.urlencode(data) headers = {} request = urllib2.Request(url, headers=headers, data=post_data) try: response = urllib2.urlopen(request) response = response.read() except urllib2.HTTPError as e: response = e.read() response_data = json.loads(response) if "status" in response_data and response_data["status"] == "failure": raise FaceError(response_data["error_code"], response_data["error_message"]) return response_data
def uploadRun(self, email, password, files): ''' ''' def file2text(fn): fh = open(fn) fc = fh.read() fh.close() return fc upload_url = self.url + '/add_run.php' success = True backupdir = self.getConfigDataFromFile()[2] if not self.isLoggedIn: self.isLoggedIn = self.webLogin(email, password) if self.isLoggedIn: for full_path in files: self.logger.info("uploading file %s" % full_path) path, fname = os.path.split(full_path) if self.isNewFile(fname): m = Multipart() m.field('public_run', 'checked') m.field('MAX_FILE_SIZE', '14000000') m.file( 'runfile', fname, file2text(full_path), {'Content-Type': 'application/x-www-form-urlencoded'}) ct, body = m.get() request = urllib2.Request(upload_url, headers={'Content-Type': ct}, data=body) reply = ClientCookie.urlopen(request) file_uploaded = 'Runometer: Show Run' in reply.read() if file_uploaded: self.logFileUploaded(fname) shutil.copy(full_path, backupdir) success = success * file_uploaded else: self.logger.info( "File %s already uploaded in some previous session" % fname) return success
def send_request(self, method=None, parameters=None, files=None, buffers=None): protocol = 'https://' if USE_SSL else 'http://' url = '%s%s/%s.%s' % (protocol, API_HOST, method, self.format) data = { 'api_key': self.api_key, 'api_secret': self.api_secret } if parameters: data.update(parameters) # Local file is provided, use multi-part form if files or buffers: from multipart import Multipart form = Multipart() for key, value in data.iteritems(): form.field(key, value) if files: for i, file in enumerate(files, 1): if hasattr(file, 'read'): if hasattr(file, 'name'): name = os.path.basename(file.name) else: name = 'attachment_%d' % i close_file = False else: name = os.path.basename(file) file = open(file, 'rb') close_file = True try: form.file(name, name, file.read()) finally: if close_file: file.close() else: for i, buffer in enumerate(buffers, 1): name = 'attachment_%d' % i form.file(name, name, buffer) (content_type, post_data) = form.get() headers = {'Content-Type': content_type} else: post_data = urllib.urlencode(data) headers = {} print post_data request = urllib2.Request(url, headers=headers, data=post_data) response = urllib2.urlopen(request) response = response.read() response_data = json.loads(response) if 'status' in response_data and response_data['status'] == 'failure': raise FaceError(response_data['error_code'], response_data['error_message']) return response_data
def update_theme(email, password, blog_name, file_path): cj = cookielib.CookieJar() handler = urllib2.HTTPHandler(debuglevel=0) opener = urllib2.build_opener(RedirectHandler(), handler, urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) login_url = "http://www.tumblr.com/login" login_post_data = { 'email': email, 'password': password } login_req = urllib2.Request(login_url, urllib.urlencode(login_post_data)) urllib2.urlopen(login_req).read() dashboard_req = urllib2.Request("http://www.tumblr.com/customize/%s"% blog_name) custom_html = urllib2.urlopen(dashboard_req).read() form_key = re.compile("form_key.*?value=\"(.*?)\"").findall(custom_html)[0] customize_url = "http://www.tumblr.com/customize/%s" % blog_name m = Multipart() m.field("edit_tumblelog[custom_theme]", open(file_path, 'r').read()) m.field("form_key", form_key) ct, body = m.get() request = urllib2.Request(url=customize_url, headers={'Content-Type':ct, 'User-Agent': "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.12) Gecko/20080207 Ubuntu/7.10 (gutsy) Firefox/2.0.0.12", 'Connection': 'keep-alive'}, data=body) reply = urllib2.urlopen(request) reply.read()
def __upload_to_form(self, form_url, filename, callback, **kwargs): '''Uploads a photo - can be used to either upload a new photo or replace an existing one. form_url must be either ``FlickrAPI.flickr_replace_form`` or ``FlickrAPI.flickr_upload_form``. ''' if not filename: raise IllegalArgumentException("filename must be specified") if not self.token_cache.token: raise IllegalArgumentException("Authentication is required") # Figure out the response format format = self.__extract_upload_response_format(kwargs) # Update the arguments with the ones the user won't have to supply arguments = {'auth_token': self.token_cache.token, 'api_key': self.api_key} arguments.update(kwargs) # Convert to UTF-8 if an argument is an Unicode string kwargs = make_utf8(arguments) if self.secret: kwargs["api_sig"] = self.sign(kwargs) url = "http://%s%s" % (FlickrAPI.flickr_host, form_url) # construct POST data body = Multipart() for arg, value in kwargs.iteritems(): part = Part({'name': arg}, value) body.attach(part) filepart = FilePart({'name': 'photo'}, filename, 'image/jpeg') body.attach(filepart) return self.__wrap_in_parser(self.__send_multipart, format, url, body, callback)
def upload(self, photos, **params):#{{{ params['format'] = self.format params['api_key'] = self.api_key if self.token: params['auth_token'] = self.token params['api_sig'] =self.sign(**params) req_url = self.api_host + '/api/upload/' body = Multipart() for arg, value in params.iteritems(): part = Part({'name': arg}, value) body.attach(part) if type(photos) != types.ListType: photos = [photos] for photo in photos: filepart = Part({'name': 'photo', 'filename':params['title'].encode('utf8')}, photo['data'], 'image/'+photo['type']) body.attach(filepart) request = urllib2.Request(url=req_url) request.add_data(str(body)) (header, value) = body.header() request.add_header(header, value) #request.add_header('content-length', len(str(body))) return json.loads(urllib2.urlopen(request).read())#}}}
def uploadRun(self, email, password, files): ''' ''' def file2text(fn): fh=open(fn) fc = fh.read() fh.close() return fc upload_url = self.url + '/add_run.php' success = True backupdir = self.getConfigDataFromFile()[2] if not self.isLoggedIn: self.isLoggedIn = self.webLogin(email, password) if self.isLoggedIn: for full_path in files: self.logger.info("uploading file %s" % full_path) path, fname = os.path.split(full_path) if self.isNewFile(fname): m = Multipart() m.field('public_run','checked') m.field('MAX_FILE_SIZE','14000000') m.file('runfile',fname ,file2text(full_path),{'Content-Type':'application/x-www-form-urlencoded'}) ct,body = m.get() request = urllib2.Request(upload_url, headers={'Content-Type':ct}, data=body) reply = ClientCookie.urlopen(request) file_uploaded = 'Runometer: Show Run' in reply.read() if file_uploaded: self.logFileUploaded(fname) shutil.copy(full_path, backupdir) success = success * file_uploaded else: self.logger.info("File %s already uploaded in some previous session" % fname) return success
def send_request(self, method=None, parameters=None): url = '%s/%s' % (API_URL, method) data = { 'api_key': self.api_key, 'api_secret': self.api_secret, 'format': self.format } if parameters: data.update(parameters) # raise Exception(url, data) # Local file is provided, use multi-part form if 'file' in parameters: from multipart import Multipart form = Multipart() for key, value in data.iteritems(): if key == 'file': file = open(value, 'r') # with open(value, 'r') as file: form.file(os.path.basename(key), os.path.basename(key), file.read()) else: form.field(key, value) (content_type, post_data) = form.get() headers = {'Content-Type': content_type} else: post_data = urllib.urlencode(data) headers = {} request = urllib2.Request(url, headers=headers, data=post_data) response = urllib2.urlopen(request) response = response.read() response_data = json.loads(response) if 'status' in response_data and \ response_data['status'] == 'failure': raise FaceError(response_data['error_code'], response_data['error_message']) return response_data
def update_theme(email, password, blog_name, file_path): cj = cookielib.CookieJar() handler = urllib2.HTTPHandler(debuglevel=0) opener = urllib2.build_opener(RedirectHandler(), handler, urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) login_url = "http://www.tumblr.com/login" login_post_data = {'email': email, 'password': password} login_req = urllib2.Request(login_url, urllib.urlencode(login_post_data)) urllib2.urlopen(login_req).read() dashboard_req = urllib2.Request("http://www.tumblr.com/customize/%s" % blog_name) custom_html = urllib2.urlopen(dashboard_req).read() form_key = re.compile("form_key.*?value=\"(.*?)\"").findall(custom_html)[0] customize_url = "http://www.tumblr.com/customize/%s" % blog_name m = Multipart() m.field("edit_tumblelog[custom_theme]", open(file_path, 'r').read()) m.field("form_key", form_key) ct, body = m.get() request = urllib2.Request( url=customize_url, headers={ 'Content-Type': ct, 'User-Agent': "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.12) Gecko/20080207 Ubuntu/7.10 (gutsy) Firefox/2.0.0.12", 'Connection': 'keep-alive' }, data=body) reply = urllib2.urlopen(request) reply.read()
def send_request(self, method=None, parameters=None): url = '%s/%s' % (API_URL, method) data = {'api_key': self.api_key, 'api_secret': self.api_secret, 'format': self.format} post_data = urllib.urlencode(data) headers = {} if parameters: data.update(parameters) # Local file is provided, use multi-part form if 'file' in parameters: from multipart import Multipart form = Multipart() for key, value in data.iteritems(): if key == 'file': with open(value, 'r') as file: form.file(os.path.basename(key), os.path.basename(key), file.read()) else: form.field(key, value) (content_type, post_data) = form.get() headers = {'Content-Type': content_type} else: post_data = urllib.urlencode(data) request = urllib2.Request(url, headers=headers, data=post_data) response = urllib2.urlopen(request) response = response.read() response_data = json.loads(response) if 'status' in response_data and \ response_data['status'] == 'failure': raise FaceError(response_data['error_code'], response_data['error_message']) return response_data
from urllib import urlencode from urllib2 import * from cookielib import CookieJar from multipart import Multipart, Part from inforeader import getVal import os infile = 'data.in' outfile = 'data.out' cid = getVal("init.info", "diy", "cid") pid = getVal("init.info", "problem", "pid") url = 'http://acm.hdu.edu.cn/diy/diy_uploaddata.php?action=upload&cid=' + cid + '&pid=' + pid body = Multipart() intext = open(infile, "rb").read() outtext = open(outfile, "rb").read() inpart = Part({"name":"inputfile", "filename":infile}, intext, "text/plain") outpart = Part({"name":"outputfile", "filename":outfile}, outtext, "text/plain") body.attach(inpart) body.attach(outpart) request = Request(url) request.add_data(str(body)) (header, value) = body.header() request.add_header(header, value) cookiejar = CookieJar() cookieproc = HTTPCookieProcessor(cookiejar)