From 5c39cd159ef761500f3cb0292a3da40d5e250417 Mon Sep 17 00:00:00 2001 From: Harmon Date: Wed, 24 Mar 2021 04:04:24 -0500 Subject: [PATCH] Replace TweepError with TweepyException where not HTTP request error --- tweepy/api.py | 15 ++++++++------- tweepy/auth.py | 18 +++++++++--------- tweepy/cursor.py | 18 +++++++++--------- tweepy/parsers.py | 8 +++++--- tweepy/streaming.py | 8 ++++---- 5 files changed, 35 insertions(+), 32 deletions(-) diff --git a/tweepy/api.py b/tweepy/api.py index 893f6cf..3c25397 100644 --- a/tweepy/api.py +++ b/tweepy/api.py @@ -13,6 +13,7 @@ from urllib.parse import urlencode import requests from tweepy.error import is_rate_limit_error_message, RateLimitError, TweepError +from tweepy.errors import TweepyException from tweepy.models import Model from tweepy.parsers import ModelParser, Parser from tweepy.utils import list_to_csv @@ -104,7 +105,7 @@ class API: # If authentication is required and no credentials # are provided, throw an error. if require_auth and not self.auth: - raise TweepError('Authentication required!') + raise TweepyException('Authentication required!') self.cached_result = False @@ -176,7 +177,7 @@ class API: auth=auth, proxies=self.proxy ) except Exception as e: - raise TweepError(f'Failed to send request: {e}').with_traceback(sys.exc_info()[2]) + raise TweepyException(f'Failed to send request: {e}').with_traceback(sys.exc_info()[2]) if 200 <= resp.status_code < 300: break @@ -1197,16 +1198,16 @@ class API: if f is None: try: if os.path.getsize(filename) > (max_size * 1024): - raise TweepError(f'File is too big, must be less than {max_size}kb.') + raise TweepyException(f'File is too big, must be less than {max_size}kb.') except os.error as e: - raise TweepError(f'Unable to access file: {e.strerror}') + raise TweepyException(f'Unable to access file: {e.strerror}') # build the mulitpart-formdata body fp = open(filename, 'rb') else: f.seek(0, 2) # Seek to end of file if f.tell() > (max_size * 1024): - raise TweepError(f'File is too big, must be less than {max_size}kb.') + raise TweepyException(f'File is too big, must be less than {max_size}kb.') f.seek(0) # Reset to beginning of file fp = f @@ -1218,11 +1219,11 @@ class API: f.seek(0) file_type = imghdr.what(filename, h=h) or mimetypes.guess_type(filename)[0] if file_type is None: - raise TweepError('Could not determine file type') + raise TweepyException('Could not determine file type') if file_type in ['gif', 'jpeg', 'png', 'webp']: file_type = 'image/' + file_type elif file_type not in ['image/gif', 'image/jpeg', 'image/png']: - raise TweepError(f'Invalid file type for image: {file_type}') + raise TweepyException(f'Invalid file type for image: {file_type}') if isinstance(filename, str): filename = filename.encode('utf-8') diff --git a/tweepy/auth.py b/tweepy/auth.py index 9833eff..dc6c968 100644 --- a/tweepy/auth.py +++ b/tweepy/auth.py @@ -10,7 +10,7 @@ from requests.auth import AuthBase from requests_oauthlib import OAuth1, OAuth1Session from tweepy.api import API -from tweepy.error import TweepError +from tweepy.errors import TweepyException WARNING_MESSAGE = """Warning! Due to a Twitter API bug, signin_with_twitter and access_type don't always play nice together. Details @@ -71,7 +71,7 @@ class OAuthHandler(AuthHandler): url += f'?x_auth_access_type={access_type}' return self.oauth.fetch_request_token(url) except Exception as e: - raise TweepError(e) + raise TweepyException(e) def set_access_token(self, key, secret): self.access_token = key @@ -91,7 +91,7 @@ class OAuthHandler(AuthHandler): self.request_token = self._get_request_token(access_type=access_type) return self.oauth.authorization_url(url) except Exception as e: - raise TweepError(e) + raise TweepyException(e) def get_access_token(self, verifier=None): """ @@ -110,7 +110,7 @@ class OAuthHandler(AuthHandler): self.access_token_secret = resp['oauth_token_secret'] return self.access_token, self.access_token_secret except Exception as e: - raise TweepError(e) + raise TweepyException(e) def get_xauth_access_token(self, username, password): """ @@ -132,7 +132,7 @@ class OAuthHandler(AuthHandler): credentials = parse_qs(r.content) return credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0] except Exception as e: - raise TweepError(e) + raise TweepyException(e) def get_username(self): if self.username is None: @@ -141,8 +141,8 @@ class OAuthHandler(AuthHandler): if user: self.username = user.screen_name else: - raise TweepError('Unable to get username,' - ' invalid oauth token!') + raise TweepyException('Unable to get username,' + ' invalid oauth token!') return self.username @@ -172,8 +172,8 @@ class AppAuthHandler(AuthHandler): data={'grant_type': 'client_credentials'}) data = resp.json() if data.get('token_type') != 'bearer': - raise TweepError('Expected token_type to equal "bearer", ' - f'but got {data.get("token_type")} instead') + raise TweepyException('Expected token_type to equal "bearer", ' + f'but got {data.get("token_type")} instead') self._bearer_token = data['access_token'] diff --git a/tweepy/cursor.py b/tweepy/cursor.py index 5c09c22..a9a70f0 100644 --- a/tweepy/cursor.py +++ b/tweepy/cursor.py @@ -2,7 +2,7 @@ # Copyright 2009-2021 Joshua Roesslein # See LICENSE for details. -from tweepy.error import TweepError +from tweepy.errors import TweepyException from tweepy.parsers import ModelParser, RawParser @@ -22,9 +22,9 @@ class Cursor: elif method.pagination_mode == 'page': self.iterator = PageIterator(method, *args, **kwargs) else: - raise TweepError('Invalid pagination mode.') + raise TweepyException('Invalid pagination mode.') else: - raise TweepError('This method does not perform pagination') + raise TweepyException('This method does not perform pagination') def pages(self, limit=0): """Return iterator for pages""" @@ -83,7 +83,7 @@ class CursorIterator(BaseIterator): def prev(self): if self.prev_cursor == 0: - raise TweepError('Can not page back more, at first page') + raise TweepyException('Can not page back more, at first page') data, self.next_cursor, self.prev_cursor = self.method(cursor=self.prev_cursor, *self.args, **self.kwargs) @@ -110,7 +110,7 @@ class DMCursorIterator(BaseIterator): return data def prev(self): - raise TweepError('This method does not allow backwards pagination') + raise TweepyException('This method does not allow backwards pagination') class IdIterator(BaseIterator): @@ -208,7 +208,7 @@ class PageIterator(BaseIterator): def prev(self): if self.current_page == 1: - raise TweepError('Can not page back more, at first page') + raise TweepyException('Can not page back more, at first page') self.current_page -= 1 return self.method(page=self.current_page, *self.args, **self.kwargs) @@ -232,7 +232,7 @@ class NextIterator(BaseIterator): return data def prev(self): - raise TweepError('This method does not allow backwards pagination') + raise TweepyException('This method does not allow backwards pagination') class ItemIterator(BaseIterator): @@ -260,13 +260,13 @@ class ItemIterator(BaseIterator): def prev(self): if self.current_page is None: - raise TweepError('Can not go back more, at first page') + raise TweepyException('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 TweepError('No more items') + raise TweepyException('No more items') self.page_index -= 1 self.num_tweets -= 1 return self.current_page[self.page_index] diff --git a/tweepy/parsers.py b/tweepy/parsers.py index cda1bf0..5963afb 100644 --- a/tweepy/parsers.py +++ b/tweepy/parsers.py @@ -4,7 +4,7 @@ import json as json_lib -from tweepy.error import TweepError +from tweepy.errors import TweepyException from tweepy.models import ModelFactory @@ -47,7 +47,7 @@ class JSONParser(Parser): try: json = json_lib.loads(payload) except Exception as e: - raise TweepError(f'Failed to parse JSON payload: {e}') + raise TweepyException(f'Failed to parse JSON payload: {e}') if return_cursors and isinstance(json, dict): if 'next' in json: @@ -88,7 +88,9 @@ class ModelParser(JSONParser): return model = getattr(self.model_factory, payload_type) except AttributeError: - raise TweepError(f'No model for this payload type: {payload_type}') + raise TweepyException( + f'No model for this payload type: {payload_type}' + ) json = JSONParser.parse(self, payload, return_cursors=return_cursors) if isinstance(json, tuple): diff --git a/tweepy/streaming.py b/tweepy/streaming.py index 0b20fd9..917408f 100644 --- a/tweepy/streaming.py +++ b/tweepy/streaming.py @@ -17,7 +17,7 @@ from requests_oauthlib import OAuth1 import urllib3 import tweepy -from tweepy.error import TweepError +from tweepy.errors import TweepyException from tweepy.models import Status log = logging.getLogger(__name__) @@ -154,7 +154,7 @@ class Stream: filter_level=None, languages=None, stall_warnings=False, threaded=False): if self.running: - raise TweepError("Stream is already connected") + raise TweepyException("Stream is already connected") method = "POST" endpoint = "statuses/filter" @@ -167,7 +167,7 @@ class Stream: body["track"] = ','.join(map(str, track)) if locations and len(locations) > 0: if len(locations) % 4: - raise TweepError( + raise TweepyException( "Number of location coordinates should be a multiple of 4" ) body["locations"] = ','.join(f"{l:.4f}" for l in locations) @@ -186,7 +186,7 @@ class Stream: def sample(self, *, languages=None, stall_warnings=False, threaded=False): if self.running: - raise TweepError("Stream is already connected") + raise TweepyException("Stream is already connected") method = "GET" endpoint = "statuses/sample" -- 2.25.1