Skip to content

Commit 9a971c2

Browse files
authored
Read API key from pymatgen config (#856)
* use pymatgen.core.SETTINGS.get("PMG_MAPI_KEY") as final api_key fallback * add test_pmg_api_key() * monkeypatch.delenv("MP_API_KEY") * fix test_pmg_api_key not unsetting DEFAULT_API_KEY * fix typo
1 parent 47fc608 commit 9a971c2

4 files changed

Lines changed: 37 additions & 18 deletions

File tree

.pre-commit-config.yaml

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,24 @@ ci:
66

77
repos:
88
- repo: https://github.com/astral-sh/ruff-pre-commit
9-
rev: v0.0.284
9+
rev: v0.0.292
1010
hooks:
1111
- id: ruff
1212
args: [--fix, --show-fixes]
1313

1414
- repo: https://github.com/psf/black
15-
rev: 23.7.0
15+
rev: 23.9.1
1616
hooks:
1717
- id: black
1818

1919
- repo: https://github.com/asottile/blacken-docs
20-
rev: "1.15.0"
20+
rev: "1.16.0"
2121
hooks:
2222
- id: blacken-docs
2323
additional_dependencies: [black>=23.7.0]
2424

2525
- repo: https://github.com/pre-commit/pre-commit-hooks
26-
rev: v4.4.0
26+
rev: v4.5.0
2727
hooks:
2828
- id: check-case-conflict
2929
- id: check-symlinks
@@ -34,7 +34,7 @@ repos:
3434
- id: trailing-whitespace
3535

3636
- repo: https://github.com/codespell-project/codespell
37-
rev: v2.2.4
37+
rev: v2.2.6
3838
hooks:
3939
- id: codespell
4040
stages: [commit, commit-msg]

mp_api/client/mprester.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from packaging import version
1616
from pymatgen.analysis.phase_diagram import PhaseDiagram
1717
from pymatgen.analysis.pourbaix_diagram import IonEntry
18-
from pymatgen.core import Element, Structure
18+
from pymatgen.core import SETTINGS, Element, Structure
1919
from pymatgen.core.ion import Ion
2020
from pymatgen.entries.computed_entries import ComputedStructureEntry
2121
from pymatgen.io.vasp import Chgcar
@@ -165,14 +165,17 @@ def __init__(
165165
headers (dict): Custom headers for localhost connections.
166166
mute_progress_bars (bool): Whether to mute progress bars.
167167
"""
168+
# SETTINGS tries to read API key from ~/.config/.pmgrc.yaml
169+
api_key = api_key or DEFAULT_API_KEY or SETTINGS.get("PMG_MAPI_KEY")
170+
168171
if api_key and len(api_key) != 32:
169172
raise ValueError(
170173
"Please use a new API key from https://materialsproject.org/api "
171174
"Keys for the new API are 32 characters, whereas keys for the legacy "
172175
"API are 16 characters."
173176
)
174177

175-
self.api_key = api_key or DEFAULT_API_KEY
178+
self.api_key = api_key
176179
self.endpoint = endpoint
177180
self.headers = headers or {}
178181
self.session = session or BaseRester._create_session(

mp_api/client/routes/materials/substrates.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def search(
4242
"""Query equations of state docs using a variety of search criteria.
4343
4444
Arguments:
45-
area (Tuple[float,float]): Minimum and maximum volume in Ų to consider for the minimim coincident
45+
area (Tuple[float,float]): Minimum and maximum volume in Ų to consider for the minimum coincident
4646
interface area range.
4747
energy (Tuple[float,float]): Minimum and maximum energy in meV to consider for the elastic energy range.
4848
film_id (str): Materials Project ID of the film material.

tests/test_mprester.py

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
from mp_api.client import MPRester
2727
from mp_api.client.core.settings import MAPIClientSettings
2828

29+
os.environ["MP_API_KEY"] = "test"
30+
2931

3032
@pytest.fixture()
3133
def mpr():
@@ -68,14 +70,14 @@ def test_get_materials_ids_references(self, mpr):
6870
assert len(data) > 5
6971

7072
def test_get_materials_ids_doc(self, mpr):
71-
mpids = mpr.get_materials_ids("Al2O3")
72-
random.shuffle(mpids)
73-
doc = mpr.materials.get_data_by_id(mpids.pop(0))
73+
mp_ids = mpr.get_materials_ids("Al2O3")
74+
random.shuffle(mp_ids)
75+
doc = mpr.materials.get_data_by_id(mp_ids.pop(0))
7476
assert doc.formula_pretty == "Al2O3"
7577

76-
mpids = mpr.get_materials_ids("Al-O")
77-
random.shuffle(mpids)
78-
doc = mpr.materials.get_data_by_id(mpids.pop(0))
78+
mp_ids = mpr.get_materials_ids("Al-O")
79+
random.shuffle(mp_ids)
80+
doc = mpr.materials.get_data_by_id(mp_ids.pop(0))
7981
assert doc.chemsys == "Al-O"
8082

8183
def test_get_structures(self, mpr):
@@ -99,9 +101,9 @@ def test_find_structure(self, mpr):
99101
def test_get_bandstructure_by_material_id(self, mpr):
100102
bs = mpr.get_bandstructure_by_material_id("mp-149")
101103
assert isinstance(bs, BandStructureSymmLine)
102-
bs_unif = mpr.get_bandstructure_by_material_id("mp-149", line_mode=False)
103-
assert isinstance(bs_unif, BandStructure)
104-
assert not isinstance(bs_unif, BandStructureSymmLine)
104+
bs_uniform = mpr.get_bandstructure_by_material_id("mp-149", line_mode=False)
105+
assert isinstance(bs_uniform, BandStructure)
106+
assert not isinstance(bs_uniform, BandStructureSymmLine)
105107

106108
def test_get_dos_by_id(self, mpr):
107109
dos = mpr.get_dos_by_material_id("mp-149")
@@ -268,7 +270,7 @@ def test_get_ion_entries(self, mpr):
268270
itertools.chain.from_iterable(i.elements for i in ion_ref_comps)
269271
)
270272
ion_ref_entries = mpr.get_entries_in_chemsys(
271-
list([str(e) for e in ion_ref_elts] + ["O", "H"])
273+
[*map(str, ion_ref_elts), "O", "H"]
272274
)
273275
mpc = MaterialsProjectAqueousCompatibility()
274276
ion_ref_entries = mpc.process_entries(ion_ref_entries)
@@ -322,3 +324,17 @@ def test_large_list(self, mpr):
322324
]
323325
docs = mpr.summary.search(material_ids=mpids, fields=["material_ids"])
324326
assert len(docs) == 15000
327+
328+
329+
def test_pmg_api_key(monkeypatch: pytest.MonkeyPatch):
330+
from pymatgen.core import SETTINGS
331+
332+
# unset DEFAULT_API_KEY
333+
monkeypatch.setattr("mp_api.client.mprester.DEFAULT_API_KEY", None)
334+
335+
fake_api_key = "12345678901234567890123456789012" # 32 chars
336+
# patch pymatgen.core.SETTINGS to contain PMG_MAPI_KEY
337+
monkeypatch.setitem(SETTINGS, "PMG_MAPI_KEY", fake_api_key)
338+
339+
# create MPRester and check that it picked up the API key from pymatgen SETTINGS
340+
assert MPRester().api_key == fake_api_key

0 commit comments

Comments
 (0)