def prev(self): if self.current_page is None: raise WeibopError('Can not go back more, at first page') if self.page_index == 0: # At the beginning of the current page, move to next... self.current_page = self.page_iterator.prev() self.page_index = len(self.current_page) if self.page_index == 0: raise WeibopError('No more items') self.page_index -= 1 self.count -= 1 return self.current_page[self.page_index]
def build_parameters(self, args, kargs): self.parameters = {} for idx, arg in enumerate(args): try: self.parameters[self.allowed_param[idx]] = convert_to_utf8_str(arg) except IndexError: raise WeibopError('Too many parameters supplied!') for k, arg in kargs.items(): if arg is None: continue if k in self.parameters: raise WeibopError('Multiple values for parameter %s supplied!' % k) self.parameters[k] = convert_to_utf8_str(arg)
def get_access_token(self, verifier=None): """ After user has authorized the request token, get access token with user supplied verifier. """ try: url = self._get_oauth_url('access_token') # build request request = oauth.OAuthRequest.from_consumer_and_token( self._consumer, token=self.request_token, http_url=url, verifier=str(verifier)) request.sign_request(self._sigmethod, self._consumer, self.request_token) # send request resp = urlopen(Request(url, headers=request.to_header())) data = resp.read() self.access_token = oauth.OAuthToken.from_string(data) return self.access_token except Exception, e: import traceback traceback.print_exc() raise WeibopError(e)
def prev(self): if self.prev_cursor == 0: raise WeibopError('Can not page back more, at first page') data, self.next_cursor, self.prev_cursor = self.method( cursor=self.prev_cursor, *self.args, **self.kargs) self.count -= 1 return data
def __init__(self, method, *args, **kargs): if hasattr(method, 'pagination_mode'): if method.pagination_mode == 'cursor': self.iterator = CursorIterator(method, args, kargs) else: self.iterator = PageIterator(method, args, kargs) else: raise WeibopError('This method does not perform pagination')
def get_username(self): if self.username is None: api = API(self) user = api.verify_credentials() if user: self.username = user.screen_name else: raise WeibopError( "Unable to get username, invalid oauth token!") return self.username
def _get_request_token(self): try: url = self._get_oauth_url('request_token') request = oauth.OAuthRequest.from_consumer_and_token( self._consumer, http_url=url, callback=self.callback) request.sign_request(self._sigmethod, self._consumer, None) resp = urlopen(Request(url, headers=request.to_header())) data = resp.read() return oauth.OAuthToken.from_string(data) except Exception, e: import traceback traceback.print_exc() print >> sys.stderr, url raise WeibopError(e)
def build_path(self): for variable in re_path_template.findall(self.path): name = variable.strip('{}') if name == 'user' and self.api.auth: value = self.api.auth.get_username() else: try: value = urllib.quote(self.parameters[name]) except KeyError: raise WeibopError('No parameter value found for path variable: %s' % name) del self.parameters[name] self.path = self.path.replace(variable, value)
def _pack_image(filename, max_size, source=None, status=None, lat=None, long=None, contentname="image"): """Pack image from file into multipart-formdata post body""" # image must be less than 700kb in size try: if os.path.getsize(filename) > (max_size * 1024): raise WeibopError('File is too big, must be less than 700kb.') #except os.error, e: except os.error: raise WeibopError('Unable to access file') # image must be gif, jpeg, or png file_type = mimetypes.guess_type(filename) if file_type is None: raise WeibopError('Could not determine file type') file_type = file_type[0] if file_type not in ['image/gif', 'image/jpeg', 'image/png']: raise WeibopError('Invalid file type for image: %s' % file_type) fp = open(filename, 'rb') content = fp.read() r = API._pack_image_content(filename, content, max_size, source=source, status=status, lat=lat, long=long, contentname=contentname, file_type=file_type) fp.close() return r
def get_authorization_url(self, signin_with_twitter=False, callback=None): """Get the authorization URL to redirect the user""" try: # get the request token self.request_token = self._get_request_token() # build auth request and return as url if signin_with_twitter: url = self._get_oauth_url('authenticate') else: url = self._get_oauth_url('authorize') request = oauth.OAuthRequest.from_token_and_callback( token=self.request_token, http_url=url, callback=callback) return request.to_url() except Exception, e: import traceback traceback.print_exc() raise WeibopError(e)
def parse(self, method, payload): try: if method.payload_type is None: return model = getattr(self.model_factory, method.payload_type) except AttributeError: raise WeibopError('No model for this payload type: %s' % method.payload_type) json = JSONParser.parse(self, method, payload) if isinstance(json, tuple): json, cursors = json else: cursors = None if method.payload_list: result = model.parse_list(method.api, json) else: result = model.parse(method.api, json) if cursors: return result, cursors else: return result
def __init__(self, api, args, kargs): # If authentication is required and no credentials # are provided, throw an error. if self.require_auth and not api.auth: raise WeibopError('Authentication required!') self.api = api self.post_data = kargs.pop('post_data', None) self.retry_count = kargs.pop('retry_count', api.retry_count) self.retry_delay = kargs.pop('retry_delay', api.retry_delay) self.retry_errors = kargs.pop('retry_errors', api.retry_errors) self.headers = kargs.pop('headers', {}) self.build_parameters(args, kargs) # Pick correct URL root to use if self.search_api: self.api_root = api.search_root else: self.api_root = api.api_root # Perform any path variable substitution self.build_path() if api.secure: self.scheme = 'https://' else: self.scheme = 'http://' if self.search_api: self.host = api.search_host else: self.host = api.host # Manually set Host header to fix an issue in python 2.5 # or older where Host is set including the 443 port. # This causes Twitter to issue 301 redirect. # See Issue http://github.com/joshthecoder/tweepy/issues/#issue/12 self.headers['Host'] = self.host
def parse(self, method, payload): try: json = self.json_lib.loads(payload) except Exception, e: print "Failed to parse JSON payload:"+ str(payload) raise WeibopError('Failed to parse JSON payload: %s' % e)
def prev(self): if (self.current_page == 1): raise WeibopError('Can not page back more, at first page') self.current_page -= 1 return self.method(page=self.current_page, *self.args, **self.kargs)
def execute(self): # Build the request URL url = self.api_root + self.path #if self.api.source is not None: # self.parameters.setdefault('source',self.api.source) if len(self.parameters): if self.method == 'GET': url = '%s?%s' % (url, urllib.urlencode(self.parameters)) else: self.headers.setdefault("User-Agent","python") if self.post_data is None: self.headers.setdefault("Accept","text/html") self.headers.setdefault("Content-Type","application/x-www-form-urlencoded") self.post_data = urllib.urlencode(self.parameters) # Query the cache if one is available # and this request uses a GET method. if self.api.cache and self.method == 'GET': cache_result = self.api.cache.get(url) # if cache result found and not expired, return it if cache_result: # must restore api reference if isinstance(cache_result, list): for result in cache_result: result._api = self.api else: cache_result._api = self.api return cache_result #urllib.urlencode(self.parameters) # Continue attempting request until successful # or maximum number of retries is reached. sTime = time.time() retries_performed = 0 while retries_performed < self.retry_count + 1: # Open connection # FIXME: add timeout if self.api.secure: conn = httplib.HTTPSConnection(self.host) else: conn = httplib.HTTPConnection(self.host) # Apply authentication if self.api.auth: self.api.auth.apply_auth( self.scheme + self.host + url, self.method, self.headers, self.parameters ) # Execute request try: conn.request(self.method, url, headers=self.headers, body=self.post_data) resp = conn.getresponse() except Exception, e: import traceback traceback.print_exc() raise WeibopError('Failed to send request: %s' % e + "url=" + str(url) +",self.headers="+ str(self.headers)) # Exit request loop if non-retry error code if self.retry_errors: if resp.status not in self.retry_errors: break else: if resp.status == 200: break # Sleep before retrying request again time.sleep(self.retry_delay) retries_performed += 1
class APIMethod(object): path = config['path'] payload_type = config.get('payload_type', None) payload_list = config.get('payload_list', False) allowed_param = config.get('allowed_param', []) method = config.get('method', 'GET') require_auth = config.get('require_auth', False) search_api = config.get('search_api', False) def __init__(self, api, args, kargs): # If authentication is required and no credentials # are provided, throw an error. if self.require_auth and not api.auth: raise WeibopError('Authentication required!') self.api = api self.post_data = kargs.pop('post_data', None) self.retry_count = kargs.pop('retry_count', api.retry_count) self.retry_delay = kargs.pop('retry_delay', api.retry_delay) self.retry_errors = kargs.pop('retry_errors', api.retry_errors) self.headers = kargs.pop('headers', {}) self.build_parameters(args, kargs) # Pick correct URL root to use if self.search_api: self.api_root = api.search_root else: self.api_root = api.api_root # Perform any path variable substitution self.build_path() if api.secure: self.scheme = 'https://' else: self.scheme = 'http://' if self.search_api: self.host = api.search_host else: self.host = api.host # Manually set Host header to fix an issue in python 2.5 # or older where Host is set including the 443 port. # This causes Twitter to issue 301 redirect. # See Issue http://github.com/joshthecoder/tweepy/issues/#issue/12 self.headers['Host'] = self.host def build_parameters(self, args, kargs): self.parameters = {} for idx, arg in enumerate(args): try: self.parameters[self.allowed_param[idx]] = convert_to_utf8_str(arg) except IndexError: raise WeibopError('Too many parameters supplied!') for k, arg in kargs.items(): if arg is None: continue if k in self.parameters: raise WeibopError('Multiple values for parameter %s supplied!' % k) self.parameters[k] = convert_to_utf8_str(arg) def build_path(self): for variable in re_path_template.findall(self.path): name = variable.strip('{}') if name == 'user' and self.api.auth: value = self.api.auth.get_username() else: try: value = urllib.quote(self.parameters[name]) except KeyError: raise WeibopError('No parameter value found for path variable: %s' % name) del self.parameters[name] self.path = self.path.replace(variable, value) def execute(self): # Build the request URL url = self.api_root + self.path #if self.api.source is not None: # self.parameters.setdefault('source',self.api.source) if len(self.parameters): if self.method == 'GET': url = '%s?%s' % (url, urllib.urlencode(self.parameters)) else: self.headers.setdefault("User-Agent","python") if self.post_data is None: self.headers.setdefault("Accept","text/html") self.headers.setdefault("Content-Type","application/x-www-form-urlencoded") self.post_data = urllib.urlencode(self.parameters) # Query the cache if one is available # and this request uses a GET method. if self.api.cache and self.method == 'GET': cache_result = self.api.cache.get(url) # if cache result found and not expired, return it if cache_result: # must restore api reference if isinstance(cache_result, list): for result in cache_result: result._api = self.api else: cache_result._api = self.api return cache_result #urllib.urlencode(self.parameters) # Continue attempting request until successful # or maximum number of retries is reached. sTime = time.time() retries_performed = 0 while retries_performed < self.retry_count + 1: # Open connection # FIXME: add timeout if self.api.secure: conn = httplib.HTTPSConnection(self.host) else: conn = httplib.HTTPConnection(self.host) # Apply authentication if self.api.auth: self.api.auth.apply_auth( self.scheme + self.host + url, self.method, self.headers, self.parameters ) # Execute request try: conn.request(self.method, url, headers=self.headers, body=self.post_data) resp = conn.getresponse() except Exception, e: import traceback traceback.print_exc() raise WeibopError('Failed to send request: %s' % e + "url=" + str(url) +",self.headers="+ str(self.headers)) # Exit request loop if non-retry error code if self.retry_errors: if resp.status not in self.retry_errors: break else: if resp.status == 200: break # Sleep before retrying request again time.sleep(self.retry_delay) retries_performed += 1 # If an error was returned, throw an exception body = resp.read() self.api.last_response = resp if self.api.log is not None: requestUrl = "URL:http://"+ self.host + url eTime = '%.0f' % ((time.time() - sTime) * 1000) postData = "" if self.post_data is not None: postData = ",post:"+ self.post_data[0:500] self.api.log.debug(requestUrl +",time:"+ str(eTime)+ postData+",result:"+ body ) if resp.status != 200: try: print body json = self.api.parser.parse_error(self, body) error_code = json['error_code'] error = json['error'] error_msg = 'error_code:' + error_code +','+ error except Exception: error_msg = "Fanfou error response: status code = %s" % resp.status raise WeibopError(error_msg) # Parse the response payload result = self.api.parser.parse(self, body) conn.close() # Store result into cache if one is available. if self.api.cache and self.method == 'GET' and result: self.api.cache.store(url, result) return result