Refactor key checking
1. Rename `Twarc.check_keys` to `Twarc.get_keys` to make the
usage clear.
2. Add a prototype `Twarc.validate_keys`, that will check that
the full set of keys is present and valid against the Twitter
API.
@@ -62,7 +62,7 @@ class Twarc(object):
else:
self.config = self.default_config()
- self.check_keys()
+ self.get_keys()
@filter_protected
def search(self, q, max_id=None, since_id=None, lang=None,
@@ -674,7 +674,7 @@ class Twarc(object):
resource_owner_secret=self.access_token_secret
)
- def check_keys(self):
+ def get_keys(self):
"""
Get the Twitter API keys. Order of precedence is command line,
environment, config file. Return True if all the keys were found
@@ -696,9 +696,26 @@ class Twarc(object):
self.access_token_secret):
self.load_config()
- return self.consumer_key and self.consumer_secret and \
+ def validate_keys(self):
+ """
+ Validate the keys provided are authentic credentials.
+ """
+ url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
+
+ keys_present = self.consumer_key and self.consumer_secret and \
self.access_token and self.access_token_secret
+ if keys_present:
+ try:
+ self.get(url)
+ except requests.HTTPError as e:
+ if e.response.status_code == 401:
+ raise RuntimeError('Invalid credentials provided.')
+ else:
+ raise e
+ else:
+ raise RuntimeError('Incomplete credentials provided.')
+
def load_config(self):
path = self.config
profile = self.profile
