Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CTOOLS-2: Set proxy config when address it not None, even if username… #11

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions generate/default_templates/README.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# {{{projectName}}}
{{#appDescriptionWithNewLines}}
{{{.}}}
{{/appDescriptionWithNewLines}}

This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project:

- API version: {{appVersion}}
- Package version: {{packageVersion}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}
{{/hideGenerationTimestamp}}
- Build package: {{generatorClass}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}

## Requirements.

Python {{{generatorLanguageVersion}}}

## Installation & Usage
### pip install

If the python package is hosted on a repository, you can install directly using:

```sh
pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git
```
(you may need to run `pip` with root permission: `sudo pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git`)

Then import the package:
```python
import {{{packageName}}}
```

### Setuptools

Install via [Setuptools](http://pypi.python.org/pypi/setuptools).

```sh
python setup.py install --user
```
(or `sudo python setup.py install` to install the package for all users)

Then import the package:
```python
import {{{packageName}}}
```

### Tests

Execute `pytest` to run the tests.

## Getting Started

Please follow the [installation procedure](#installation--usage) and then run the following:

{{> common_README }}
135 changes: 135 additions & 0 deletions generate/templates/README.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# {{{projectName}}}
{{#appDescriptionWithNewLines}}
{{{.}}}
{{/appDescriptionWithNewLines}}

This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project:

- API version: {{appVersion}}
- Package version: {{packageVersion}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}
{{/hideGenerationTimestamp}}
- Build package: {{generatorClass}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}

## Requirements.

Python {{{generatorLanguageVersion}}}

## Installation & Usage
### pip install

If the python package is hosted on a repository, you can install directly using:

```sh
pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git
```
(you may need to run `pip` with root permission: `sudo pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git`)

Then import the package:
```python
import {{{packageName}}}
```

### Setuptools

Install via [Setuptools](http://pypi.python.org/pypi/setuptools).

```sh
python setup.py install --user
```
(or `sudo python setup.py install` to install the package for all users)

Then import the package:
```python
import {{{packageName}}}
```

### Tests

Execute `pytest` to run the tests.

## Getting Started

You'll need to provide some configuration to connect to the {{packageName}} application.
These can be provided using a secrets file or environment variables.

### Environment variables

In order to use [short lived access tokens](https://support.lusid.com/knowledgebase/article/KA-01654/en-us) you will need to have appropriate values set for the following environment variables:

```
FBN_TOKEN_URL,
{{#lambda.uppercase}}FBN_{{packageName}}_API_URL{{/lambda.uppercase}},
FBN_USERNAME,
FBN_PASSWORD,
FBN_CLIENT_ID,
FBN_CLIENT_SECRET,
FBN_ACCESS_TOKEN
```

To use a long lived Personal Access Token, you must provide the following environment variables:
```
{{#lambda.uppercase}}FBN_{{packageName}}_API_URL{{/lambda.uppercase}},
FBN_ACCESS_TOKEN
```

You can send your requests to {{packageName}} via a proxy, by setting `FBN_PROXY_ADDRESS`.
If your proxy has basic auth enabled, you must akso supply `FBN_PROXY_USERNAME` and `FBN_PROXY_PASSWORD`

### Secrets file

In order to use [short lived access tokens](https://support.lusid.com/knowledgebase/article/KA-01654/en-us) you will need to have appropriate values set in a `secrets.json` file in the same folder as your script.

```
{
"api":
{
"tokenUrl":"<your-token-url>",
"{{packageName}}Url":"<FINBOURNE-application-url>",
"username":"<your-username>",
"password":"<your-password>",
"clientId":"<your-client-id>",
"clientSecret":"<your-client-secret>",
}
}
```

To use a long lived Personal Access Token, you must provide a `secrets.json` with the following variables:
```
{
"api":
{
"{{packageName}}Url":"<FINBOURNE-application-url>",
"accessToken":"<your-access-token>"
}
}
```

You can send your requests to {{packageName}} via a proxy, by adding a proxy section to your `secrets.json`.
If your proxy has basic auth enabled, you must also supply a `username` and `password` in this section.

```
{
"api":
{
"{{packageName}}Url":"<FINBOURNE-application-url>",
"accessToken":"<your-access-token>"
},
"proxy":
{
"address":"<your-proxy-address>",
"username":"<your-proxy-username>",
"password":"<your-proxy-password>"
}
}
```

### Using the SDK

Please follow the [installation procedure](#installation--usage) and then run the following:

{{> common_README }}
3 changes: 2 additions & 1 deletion generate/templates/extensions/api_configuration.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ from typing import Optional, Union, Tuple, Any, Callable
from {{packageName}}.configuration import Configuration
from {{packageName}}.extensions.refreshing_token import RefreshingToken
from {{packageName}}.extensions.socket_keep_alive import keep_alive_socket_options
from {{packageName}}.extensions.proxy_config import ProxyConfig
from requests import Response
logger = logging.getLogger(__name__)

Expand All @@ -19,7 +20,7 @@ class ApiConfiguration:
client_secret=None,
app_name=None,
certificate_filename=None,
proxy_config=None,
proxy_config:Optional[ProxyConfig]=None,
access_token=None,
):
"""
Expand Down
4 changes: 1 addition & 3 deletions generate/templates/extensions/configuration_loaders.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,7 @@ def get_api_configuration(config_loaders: Iterable[ConfigurationLoader]) -> ApiC
proxy_username = config.pop("proxy_username", None)
proxy_password = config.pop("proxy_password", None)
# If the proxy address is missing ensure that no proxy is used in the ApiConfiguration
if all(
(item is not None for item in (proxy_address, proxy_password, proxy_username))
):
if proxy_address is not None:
config["proxy_config"] = ProxyConfig(
address=proxy_address, username=proxy_username, password=proxy_password
)
Expand Down
13 changes: 8 additions & 5 deletions generate/templates/extensions/proxy_config.mustache
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from urllib3 import make_headers
from typing import Any
from typing import Dict


class ProxyConfig:
Expand Down Expand Up @@ -56,14 +56,17 @@ class ProxyConfig:
return {"http": proxy_url, "https": proxy_url}

@property
def headers(self) -> Any:
def headers(self) -> Dict[str, str]:
"""Return Proxy auth headers

Returns
-------
Any
Proxy auth headers
"""
return make_headers(
proxy_basic_auth=f"{self.__username}:{self.__password}"
)
if self.__username is not None and self.__password is not None:
return make_headers(
proxy_basic_auth=f"{self.__username}:{self.__password}"
)
else:
return {}
32 changes: 30 additions & 2 deletions test_sdk/unit/test_configuration_loaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,36 @@ def test_load_config_gets_config_dict(self):

def test_get_api_configuration_overwrites_content_in_order():
mock_config_loader_1 = EnvironmentVariablesConfigurationLoader()
mock_config_loader_1.load_config = mock.MagicMock(return_value={"token_url":"1"})
mock_config_loader_1.load_config = mock.MagicMock(return_value={"token_url": "1"})
mock_config_loader_2 = EnvironmentVariablesConfigurationLoader()
mock_config_loader_2.load_config = mock.MagicMock(return_value={"token_url":"2"})
mock_config_loader_2.load_config = mock.MagicMock(return_value={"token_url": "2"})
api_config = get_api_configuration([mock_config_loader_1, mock_config_loader_2])
assert api_config.token_url == "2"


def test_get_api_configuration_returns_api_config_with_proxy_settings_when_proxy_address_not_None(): # noqa
proxy_address = "http://www.example.com"
mock_config_loader = EnvironmentVariablesConfigurationLoader()
mock_config_loader.load_config = mock.MagicMock(
return_value={"proxy_address": proxy_address}
)
api_config = get_api_configuration((mock_config_loader,))
assert api_config.proxy_config is not None
assert api_config.proxy_config.address == proxy_address


def test_get_api_configuration_returns_api_config_with_proxy_address_and_username_password(): # noqa
proxy_address = "http://www.example.com"
proxy_username = "user"
proxy_password = "pass"
mock_config_loader = EnvironmentVariablesConfigurationLoader()
mock_config_loader.load_config = mock.MagicMock(
return_value={"proxy_address": proxy_address,
"proxy_username": proxy_username,
"proxy_password": proxy_password}
)
api_config = get_api_configuration((mock_config_loader,))
assert api_config.proxy_config is not None
assert api_config.proxy_config.address == proxy_address
assert api_config.proxy_config.username == proxy_username
assert api_config.proxy_config.password == proxy_password