Skip to content

Commit 7dcfdd8

Browse files
author
Aaron Gonzales
committed
added credential handling functionality
1 parent f70b68b commit 7dcfdd8

1 file changed

Lines changed: 50 additions & 1 deletion

File tree

twittersearch/api_utils.py

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
rule generation, and related.
55
"""
66

7+
import os
8+
import yaml
79
import re
810
import datetime
911
import logging
@@ -12,7 +14,7 @@
1214
except ImportError:
1315
import json
1416

15-
__all__ = ["gen_rule_payload", "gen_params_from_config",
17+
__all__ = ["gen_rule_payload", "gen_params_from_config", "load_credentials",
1618
"validate_count_api", "GNIP_RESP_CODES", "change_to_count_endpoint"]
1719

1820
logger = logging.getLogger(__name__)
@@ -205,3 +207,50 @@ def validate_count_api(rule_payload, endpoint):
205207
Please check your endpoints and try again""")
206208
logger.error(msg)
207209
raise ValueError
210+
211+
212+
def load_credentials(filename=None, account_type=None):
213+
"""
214+
handlles credeintial managmenet via a YAML file. YAML files should look
215+
like this:
216+
217+
.. code:: yaml
218+
219+
twitter_search_api:
220+
endpoint: <FULL_URL_OF_ENDPOINT>
221+
account: <ACCOUNT_NAME>
222+
username: <USERNAME>
223+
password: <PW>
224+
bearer_token: <TOKEN>
225+
226+
with the appropriate fields filled out for your account.
227+
228+
Args:
229+
filename (str): pass a filename here if you do not want to use the
230+
default '~/.twitter_keys.yaml'
231+
account_type (str): pass your account type, "premium" or "enterprise"
232+
233+
returns: tuple of (dict, dict), both search_api args and count_api args.
234+
235+
Example:
236+
>>> from twittersearch.api_utils import load_credentials
237+
>>> search_args, count_args = load_credentials(account_type="enterprise")
238+
239+
"""
240+
if account_type is None or account_type not in {"premium", "enterprise"}:
241+
logger.error("You must provide either 'premium' or 'enterprise' here")
242+
raise KeyError
243+
filename = "~/.twitter_keys.yaml" if filename is None else filename
244+
with open(os.path.expanduser(filename)) as f:
245+
search_creds = yaml.load(f)["twitter_search_api"]
246+
247+
if account_type == "premium":
248+
search_args = {"bearer_token": search_creds["bearer_token"],
249+
"endpoint": search_creds["endpoint"]}
250+
if account_type == "enterprise":
251+
search_args = {"username": search_creds["username"],
252+
"password": search_creds["password"],
253+
"endpoint": search_creds["endpoint"]}
254+
count_args = {**search_args,
255+
**{"endpoint": change_to_count_endpoint(search_args["endpoint"])}}
256+
return search_args, count_args

0 commit comments

Comments
 (0)