Skip to content

Commit

Permalink
Make request headers transversal and reloadable
Browse files Browse the repository at this point in the history
  • Loading branch information
oscgonfer committed Jun 9, 2024
1 parent cb1c79b commit ce4bc16
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
15 changes: 2 additions & 13 deletions smartcitizen_connector/device/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from smartcitizen_connector._config import config
from smartcitizen_connector.tools import logger, safe_get, tf, \
convert_freq_to_rollup, clean, localise_date, url_checker, process_headers, get_alphasense, \
get_pt_temp, find_by_field, dict_fmerge
get_pt_temp, find_by_field, dict_fmerge, get_request_headers
from typing import Optional, List, Dict
from requests import get, post, patch
from aiohttp_retry import RetryClient, ExponentialRetry
Expand Down Expand Up @@ -99,24 +99,13 @@ def __init__(self, id = None, params = None, check_postprocessing=True):
else:
raise ValueError("Need at least id or params.id")

# Headers for requests
if 'SC_ADMIN_BEARER' in environ:
logger.info('Admin Bearer found, using it')
self._headers = {'Authorization':'Bearer ' + environ['SC_ADMIN_BEARER']}
elif 'SC_BEARER' in environ:
logger.info('Bearer found in environment, using it.')
# TODO make this explicit
self._headers = {'Authorization':'Bearer ' + environ['SC_BEARER']}
else:
logger.warning('No Bearer not found, you might get throttled!')
self._headers = None

self.params = params
self.url = f'{config.DEVICES_URL}{self.id}'
self.page = f'{config.FRONTEND_URL}{self.id}'
self.method = 'async'
self.data = DataFrame()
self._metrics: List[Metric] = []
self._headers = get_request_headers()
self.__load__()
self.__get_timezone__()
if check_postprocessing:
Expand Down
14 changes: 14 additions & 0 deletions smartcitizen_connector/tools/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import logging
import sys
import time
from os import environ

tf = TimezoneFinder()

Expand Down Expand Up @@ -133,6 +134,19 @@ def format(self, record):
ch.setFormatter(CutsomLoggingFormatter())
logger.addHandler(ch)

def get_request_headers():
# Headers for requests
if 'SC_ADMIN_BEARER' in environ:
logger.info('Admin Bearer found, using it')
return {'Authorization':'Bearer ' + environ['SC_ADMIN_BEARER']}
elif 'SC_BEARER' in environ:
logger.info('Bearer found in environment, using it.')
return {'Authorization':'Bearer ' + environ['SC_BEARER']}
else:
logger.warning('No Bearer found, you might get throttled!. Load SC_BEARER as an environment key with your Oauth token to make this dissapear')

return None

def set_logger_level(level=logging.DEBUG):
logger.setLevel(level)

Expand Down

0 comments on commit ce4bc16

Please sign in to comment.