Skip to content

Commit f7e9250

Browse files
committed
- Added environment variable possibility for APIConfig
- Adapted template for APIConfig to support this - Moved to functions for access_token - Adapted tests to reflect this
1 parent 5f7b8cf commit f7e9250

10 files changed

Lines changed: 78 additions & 12 deletions

File tree

Dockerfile

Lines changed: 0 additions & 2 deletions
This file was deleted.

README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,6 @@ Please see the [Quick start page] for details.
6262
- Support for multiple languages
6363
- Support for multiple authentication schemes
6464
- Support custom themes
65-
- Support environment variables and .env files
6665

6766
## Contributing
6867

src/openapi_python_generator/__main__.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,20 +22,27 @@
2222
type=AutoFormat,
2323
help="Option to choose which auto formatter is applied.",
2424
)
25+
@click.option(
26+
"--env-token-name",
27+
default=None,
28+
help="Name of the environment variable that contains the token. If you set this, the code expects this environment "
29+
"variable to be set and will raise an error if it is not.",
30+
)
2531
@click.version_option(version=__version__)
2632
def main(
2733
source: str,
2834
output: str,
2935
library: Optional[HTTPLibrary] = HTTPLibrary.httpx,
3036
autoformat: Optional[AutoFormat] = AutoFormat.black,
37+
env_token_name: Optional[str] = None,
3138
) -> None:
3239
"""
3340
Generate Python code from an OpenAPI 3.0 specification.
3441
3542
Provide a SOURCE (file or URL) containing the OpenAPI 3 specification and
3643
an OUTPUT path, where the resulting client is created.
3744
"""
38-
generate_data(source, output, library, autoformat)
45+
generate_data(source, output, library, autoformat, env_token_name)
3946

4047

4148
if __name__ == "__main__": # pragma: no cover

src/openapi_python_generator/generate_data.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,11 +142,12 @@ def generate_data(
142142
output: Union[str, Path],
143143
library: Optional[HTTPLibrary] = HTTPLibrary.httpx,
144144
autoformat: Optional[AutoFormat] = AutoFormat.black,
145+
env_token_name: Optional[str] = None,
145146
) -> None:
146147
"""
147148
Generate Python code from an OpenAPI 3.0 specification.
148149
"""
149150
data = get_open_api(source)
150151
click.echo(f"Generating data from {source}")
151-
result = generator(data, library_config_dict[library])
152+
result = generator(data, library_config_dict[library], env_token_name)
152153
write_data(result, output, autoformat)
Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Optional
2+
13
from openapi_schema_pydantic import OpenAPI
24

35
from openapi_python_generator.language_converters.python.jinja_config import (
@@ -7,12 +9,16 @@
79
from openapi_python_generator.models import APIConfig
810

911

10-
def generate_api_config(data: OpenAPI) -> APIConfig:
12+
def generate_api_config(
13+
data: OpenAPI, env_token_name: Optional[str] = None
14+
) -> APIConfig:
1115
"""
1216
Generate the API model.
1317
"""
1418
return APIConfig(
1519
file_name="api_config",
16-
content=JINJA_ENV.get_template(API_CONFIG_TEMPLATE).render(**data.dict()),
20+
content=JINJA_ENV.get_template(API_CONFIG_TEMPLATE).render(
21+
env_token_name=env_token_name, **data.dict()
22+
),
1723
base_url=data.servers[0].url,
1824
)

src/openapi_python_generator/language_converters/python/generator.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from typing import Optional
2+
13
from openapi_schema_pydantic import OpenAPI
24

35
from openapi_python_generator.language_converters.python.api_config_generator import (
@@ -12,14 +14,16 @@
1214
from openapi_python_generator.models import ConversionResult, LibraryConfig
1315

1416

15-
def generator(data: OpenAPI, library_config: LibraryConfig) -> ConversionResult:
17+
def generator(
18+
data: OpenAPI, library_config: LibraryConfig, env_token_name: Optional[str] = None
19+
) -> ConversionResult:
1620
"""
1721
Generate Python code from an OpenAPI 3.0 specification.
1822
"""
1923

2024
models = generate_models(data.components)
2125
services = generate_services(data.paths, library_config)
22-
api_config = generate_api_config(data)
26+
api_config = generate_api_config(data, env_token_name)
2327

2428
return ConversionResult(
2529
models=models,
Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,28 @@
1+
{% if env_token_name is not none %}import os{% endif %}
2+
3+
from typing import Optional
4+
15
class APIConfig():
26
base_path: str = '{{ servers[0].url }}'
3-
access_token: str = None
7+
{% if env_token_name is none %}
8+
_access_token : Optional[str] = None
9+
{% endif %}
10+
11+
@staticmethod
12+
def get_access_token() -> Optional[str]:
13+
{% if env_token_name is not none %}
14+
try:
15+
return os.environ['{{ env_token_name }}']
16+
except KeyError:
17+
return None
18+
{% else %}
19+
return APIConfig._access_token
20+
{% endif %}
21+
22+
@staticmethod
23+
def set_access_token(value : str):
24+
{% if env_token_name is not none %}
25+
raise Exception("This client was generated with an environment variable for the access token. Please set the environment variable '{{ env_token_name }}' to the access token.")
26+
{% else %}
27+
_access_token = value
28+
{% endif %}

src/openapi_python_generator/language_converters/python/templates/httpx.jinja2

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
headers = {
55
'Content-Type': 'application/json',
66
'Accept': 'application/json',
7-
'Authorization': f'Bearer { APIConfig.access_token }',
7+
'Authorization': f'Bearer { APIConfig.get_access_token() }',
88
}
99
query_params = {
1010
{% if query_params|length > 0 %}

src/openapi_python_generator/language_converters/python/templates/requests.jinja2

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ def {{ operation_id }}({{ params | join(',') }}) -> {% if return_type.type is no
44
headers = {
55
'Content-Type': 'application/json',
66
'Accept': 'application/json',
7-
'Authorization': f'Bearer { APIConfig.access_token }',
7+
'Authorization': f'Bearer { APIConfig.get_access_token() }',
88
}
99
query_params = {
1010
{% if query_params|length > 0 %}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import json
22
from datetime import datetime
3+
import os
34

45
import orjson
56
import pytest
@@ -12,6 +13,31 @@
1213
from openapi_python_generator.language_converters.python.generator import generator
1314

1415

16+
def test_get_auth_token_without_env(model_data_with_cleanup):
17+
generate_data(test_data_path, test_result_path)
18+
19+
_locals = locals()
20+
21+
exec(
22+
"from .test_result import *\nassert APIConfig.get_access_token() is None",
23+
globals(),
24+
_locals,
25+
)
26+
27+
28+
def test_get_auth_token_with_env(model_data_with_cleanup):
29+
generate_data(test_data_path, test_result_path, env_token_name="MY_TOKEN")
30+
31+
_locals = locals()
32+
33+
# Need to reload test_result, because older tests may have already been loaded and that would cause an error
34+
exec(
35+
"import test_result\nimport importlib\nimportlib.reload(test_result)\nimport os\nos.environ['MY_TOKEN'] = 'my_token'\nassert test_result.APIConfig.get_access_token() == 'my_token'",
36+
globals(),
37+
_locals,
38+
)
39+
40+
1541
@pytest.mark.parametrize(
1642
"library",
1743
[

0 commit comments

Comments
 (0)