|
4 | 4 | rule generation, and related. |
5 | 5 | """ |
6 | 6 |
|
| 7 | +import os |
| 8 | +import yaml |
7 | 9 | import re |
8 | 10 | import datetime |
9 | 11 | import logging |
|
12 | 14 | except ImportError: |
13 | 15 | import json |
14 | 16 |
|
15 | | -__all__ = ["gen_rule_payload", "gen_params_from_config", |
| 17 | +__all__ = ["gen_rule_payload", "gen_params_from_config", "load_credentials", |
16 | 18 | "validate_count_api", "GNIP_RESP_CODES", "change_to_count_endpoint"] |
17 | 19 |
|
18 | 20 | logger = logging.getLogger(__name__) |
@@ -205,3 +207,50 @@ def validate_count_api(rule_payload, endpoint): |
205 | 207 | Please check your endpoints and try again""") |
206 | 208 | logger.error(msg) |
207 | 209 | 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