11import functools
22import json
33import logging
4+ from collections .abc import Mapping
45from dataclasses import dataclass
56from pathlib import Path
67from typing import Any , cast
@@ -36,14 +37,26 @@ def get_icon(name: str) -> str:
3637
3738
3839@functools .cache
39- def get_region_dict () -> dict [str , str ]:
40+ def get_region_dict () -> Mapping [str , str ]:
4041 """
4142 Get a list of allowed regions as a dictionary of {alpha3: name}.
4243 """
4344 with session_scope () as session :
4445 return {region .code : region .name for region in session .execute (select (Region )).scalars ().all ()}
4546
4647
48+ @functools .cache
49+ def get_region_code_iso3166_alpha3_to_alpha2 () -> Mapping [str , str ]:
50+ """
51+ Gets a best-effort mapping table from ISO-3166 alpha3 to alpha2 codes.
52+ The alpha3 keys of get_region_dict() are not guaranteed to be present in this table.
53+ Valid region codes, this mapping, and localized strings are all versioned separately (database / repo / CLDR).
54+ """
55+ with open (resources_folder / "regions.json" , "r" ) as f :
56+ json_regions = json .load (f )
57+ return {region ["alpha3" ]: region ["alpha2" ] for region in json_regions if "alpha2" in region }
58+
59+
4760def region_is_allowed (code : str ) -> bool :
4861 """
4962 Check a region code is valid
@@ -52,7 +65,7 @@ def region_is_allowed(code: str) -> bool:
5265
5366
5467@functools .cache
55- def get_language_dict () -> dict [str , str ]:
68+ def get_language_dict () -> Mapping [str , str ]:
5669 """
5770 Get a list of allowed languages as a dictionary of {code: name}.
5871 """
@@ -61,7 +74,7 @@ def get_language_dict() -> dict[str, str]:
6174
6275
6376@functools .cache
64- def get_badge_data () -> dict [str , Any ]:
77+ def get_badge_data () -> Mapping [str , Any ]:
6578 """
6679 Get a list of profile badges in form {id: Badge}
6780 """
@@ -83,7 +96,7 @@ class Badge:
8396
8497
8598@functools .cache
86- def get_badge_dict () -> dict [str , Badge ]:
99+ def get_badge_dict () -> Mapping [str , Badge ]:
87100 """
88101 Get a list of profile badges in form {id: Badge}
89102 """
@@ -92,7 +105,7 @@ def get_badge_dict() -> dict[str, Badge]:
92105
93106
94107@functools .cache
95- def get_static_badge_dict () -> dict [str , list [int ]]:
108+ def get_static_badge_dict () -> Mapping [str , list [int ]]:
96109 """
97110 Get a list of static badges in form {id: list(user_ids)}
98111 """
@@ -124,7 +137,7 @@ def get_postcard_font() -> bytes:
124137
125138
126139@functools .cache
127- def get_postcard_metadata () -> dict [str , Any ]:
140+ def get_postcard_metadata () -> Mapping [str , Any ]:
128141 """
129142 Returns the postcard metadata (coordinates, sizes, etc.) from postcard-metadata.json.
130143 """
0 commit comments