Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

default log level and tokens #37

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
50 changes: 34 additions & 16 deletions DEMO.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"The library uses the Python logging module to tell you what it's doing; if desired you can control what sort of output you see by uncommenting one of the lines below:"
"The library uses the Python logging module to tell you what it's doing, with a basic config baked into the API. If desired you can control what sort of output you see by uncommenting one of the lines below.\n",
"\n",
"The default level has changed from DEBGUG (very verbose) to WARNING. "
]
},
{
Expand All @@ -65,23 +67,37 @@
"metadata": {},
"outputs": [],
"source": [
"import logging\n",
"logger = logging.getLogger(\"bcr_api\")\n",
"# import logging\n",
"# logger = logging.getLogger(\"bcr_api\")\n",
"\n",
"# or if you prefer \n",
"# import logging\n",
"# from bcr_api.logger import get_logger\n",
"# logger = get_logger()\n",
"\n",
"#(Default) All logging messages enabled\n",
"#logger.setLevel(logging.DEBUG)\n",
"# All logging messages enabled\n",
"# logger.setLevel(logging.DEBUG)\n",
"\n",
"#Does not report URLs of API requests, but all other messages enabled\n",
"#logger.setLevel(logging.INFO)\n",
"# Does not report URLs of API requests, but all other messages enabled\n",
"# logger.setLevel(logging.INFO)\n",
"\n",
"#Report only errors and warnings\n",
"#logger.setLevel(logging.WARN)\n",
"# Report only errors and warnings - the default level\n",
"# logger.setLevel(logging.WARNING)\n",
"\n",
"#Report only errors\n",
"#logger.setLevel(logging.ERROR)\n",
"# Report only errors\n",
"# logger.setLevel(logging.ERROR)\n",
"\n",
"#Disable logging\n",
"#logger.setLevel(logging.CRITICAL)"
"# Disable logging\n",
"# logger.setLevel(logging.CRITICAL)\n",
"\n",
"# or you might have code which sets up a defaut logging level before touching the API, which works as well\n",
"# however, this would need to go _before_ the imports above\n",
"# import logging\n",
"# logging.basicConfig(\n",
"# format=\"%(asctime)s %(levelname)s: %(message)s\",\n",
"# datefmt=\"%H:%M:%S\",\n",
"# level=logging.DEBUG\n",
"# )"
]
},
{
Expand All @@ -95,12 +111,12 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"When you use the API for the first time you have to authenticate with Brandwatch. This will get you an access token. The access token is stored in a credentials file (`tokens.txt` in this example). Once you've authenticated your access token will be read from that file so you won't need to enter your password again (until your token expires).\n",
"When you use the API for the first time you have to authenticate with Brandwatch. This will get you an access token. The access token is stored in a credentials file (`~/.bcr/credentials.txt` in this example). Once you've authenticated your access token will be read from that file so you won't need to enter your password again (until your token expires).\n",
"\n",
"You can authenticate from command line using the provided console script `bcr-authenticate`:\n",
"\n",
"```\n",
"$ bcr-authenticate\n",
"$ pipenv run bcr-authenticate\n",
"Please enter your Brandwatch credentials below\n",
"Username: example@example\n",
"Password:\n",
Expand All @@ -110,6 +126,8 @@
"Success! Access token: 00000000-0000-0000-0000-000000000000\n",
"```\n",
"\n",
"`bcr-authenticate --store tokens.txt` puts the tokens file back into the current project rather than the shared `~/.bcr/credentials.txt` file.\n",
"\n",
"Alternatively, you can authenticate directly:"
]
},
Expand Down Expand Up @@ -1366,7 +1384,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.2"
"version": "3.11.4"
}
},
"nbformat": 4,
Expand Down
12 changes: 2 additions & 10 deletions src/bcr_api/authenticate.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
# coding=utf-8

from getpass import getpass
import logging
from pathlib import Path

from . import credentials
from bcr_api.config import DEFAULT_CREDENTIALS_PATH
from .bwproject import BWUser

import argparse
Expand All @@ -23,13 +22,6 @@ def authenticate(username, password, credentials_path=None):


def main():
logger = logging.getLogger("bcr_api")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter("%(levelname)s: %(message)s", "%H:%M:%S")
handler.setFormatter(formatter)
logger.addHandler(handler)

parser = argparse.ArgumentParser(
description="Logging to Brandwatch and retrieve and access token.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
Expand All @@ -40,7 +32,7 @@ def main():
"-s",
type=Path,
metavar="PATH",
default=credentials.DEFAULT_CREDENTIALS_PATH,
default=DEFAULT_CREDENTIALS_PATH,
help="Path to where access tokens are stored.",
)

Expand Down
5 changes: 3 additions & 2 deletions src/bcr_api/bwdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
"""
import datetime
from . import filters
import logging
from .logger import get_logger

logger = logging.getLogger("bcr_api")

logger = get_logger()


class BWData:
Expand Down
18 changes: 8 additions & 10 deletions src/bcr_api/bwproject.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,14 @@

import requests
import time
import logging
import json

from .config import DEFAULT_CREDENTIALS_PATH
from .credentials import CredentialsStore
from .logger import get_logger

logger = logging.getLogger("bcr_api")
handler = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s", "%H:%M:%S")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

logger = get_logger()


class BWUser:
Expand All @@ -33,7 +30,7 @@ class BWUser:
def __init__(
self,
token=None,
token_path="tokens.txt",
token_path=DEFAULT_CREDENTIALS_PATH,
username=None,
password=None,
grant_type="api-password",
Expand All @@ -48,7 +45,8 @@ def __init__(
username: Brandwatch username.
password: Brandwatch password - Optional if you already have an access token.
token: Access token - Optional.
token_path: File path to the file where access tokens will be read from and written to - Optional. Defaults to tokens.txt, pass None to disable.
token_path: File path to the file where access tokens will be read from and written to.
Optional. Defaults to DEFAULT_CREDENTIALS_PATH, pass None to disable.
"""
self.apiurl = apiurl
self.oauthpath = "oauth/token"
Expand Down Expand Up @@ -257,7 +255,7 @@ def __init__(
self,
project,
token=None,
token_path="tokens.txt",
token_path=DEFAULT_CREDENTIALS_PATH,
username=None,
password=None,
grant_type="api-password",
Expand Down
4 changes: 2 additions & 2 deletions src/bcr_api/bwresources.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
import json
from . import filters
from . import bwdata
import logging
from .logger import get_logger


logger = logging.getLogger("bcr_api")
logger = get_logger()


class AmbiguityError(ValueError):
Expand Down
5 changes: 5 additions & 0 deletions src/bcr_api/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import os
from pathlib import Path


DEFAULT_CREDENTIALS_PATH = Path(os.path.expanduser("~")) / ".bcr" / "credentials.txt"
13 changes: 9 additions & 4 deletions src/bcr_api/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
credentials contains the CredentialsStore class, which responsible for persisting access tokens to disk.
"""

import logging
import os
from pathlib import Path

DEFAULT_CREDENTIALS_PATH = Path(os.path.expanduser("~")) / ".bcr" / "credentials.txt"
from .config import DEFAULT_CREDENTIALS_PATH
from .logger import get_logger

logger = logging.getLogger("bcr_api")

logger = get_logger()


class CredentialsStore:
Expand All @@ -30,6 +30,11 @@ def __init__(self, credentials_path=None):
def __getitem__(self, username):
"""Get self[username]"""
user_tokens = self._read()
username = username.lower()
if username not in user_tokens:
raise KeyError(
f"{username} not present in credentials {self._credentials_path}"
)
return user_tokens[username.lower()]

def __setitem__(self, username, token):
Expand Down
11 changes: 11 additions & 0 deletions src/bcr_api/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import logging


logging.basicConfig(
format="%(asctime)s %(levelname)s: %(message)s",
datefmt="%H:%M:%S",
)


def get_logger():
return logging.getLogger("bcr_api")