Skip to content

Commit f7930a9

Browse files
committed
feat: basic api keys #23
1 parent 6628a6b commit f7930a9

File tree

4 files changed

+34
-2
lines changed

4 files changed

+34
-2
lines changed

epidatpy/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,6 @@
2222
GeoType,
2323
TimeType,
2424
)
25+
from ._auth import get_api_key
2526

2627
__author__ = "Delphi Group"

epidatpy/_auth.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import os
2+
import warnings
3+
from typing import Optional
4+
5+
6+
def get_api_key() -> Optional[str]:
7+
key = os.environ.get("DELPHI_EPIDATA_KEY", None)
8+
9+
if not key:
10+
warnings.warn(
11+
"DELPHI_EPIDATA_KEY environment variable not set. "
12+
"Please set it to your Epidata API key to avoid rate limits. "
13+
"You can get a free key at: https://api.delphi.cmu.edu/epidata/admin/registration_form"
14+
)
15+
16+
return key

epidatpy/request.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from json import loads
44

55
from requests import Response, Session
6+
from requests.auth import HTTPBasicAuth
67
from tenacity import retry, stop_after_attempt
78
from pandas import DataFrame
89

@@ -19,18 +20,20 @@
1920
from ._endpoints import AEpiDataEndpoints
2021
from ._constants import HTTP_HEADERS, BASE_URL
2122
from ._covidcast import CovidcastDataSources, define_covidcast_fields
23+
from ._auth import get_api_key
2224

2325

2426
@retry(reraise=True, stop=stop_after_attempt(2))
2527
def _request_with_retry(
2628
url: str, params: Mapping[str, str], session: Optional[Session] = None, stream: bool = False
2729
) -> Response:
2830
"""Make request with a retry if an exception is thrown."""
31+
basic_auth = HTTPBasicAuth("epidata", get_api_key())
2932

3033
def call_impl(s: Session) -> Response:
31-
res = s.get(url, params=params, headers=HTTP_HEADERS, stream=stream)
34+
res = s.get(url, params=params, headers=HTTP_HEADERS, stream=stream, auth=basic_auth)
3235
if res.status_code == 414:
33-
return s.post(url, params=params, headers=HTTP_HEADERS, stream=stream)
36+
return s.post(url, params=params, headers=HTTP_HEADERS, stream=stream, auth=basic_auth)
3437
return res
3538

3639
if session:

tests/test_auth.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from pytest import warns, MonkeyPatch
2+
3+
from epidatpy import get_api_key
4+
5+
6+
def test_get_api_key(monkeypatch: MonkeyPatch) -> None:
7+
with monkeypatch.context() as m:
8+
m.setenv("DELPHI_EPIDATA_KEY", "test")
9+
assert get_api_key() == "test"
10+
m.delenv("DELPHI_EPIDATA_KEY")
11+
with warns(UserWarning):
12+
assert get_api_key() is None

0 commit comments

Comments
 (0)