diff --git a/Makefile b/Makefile index b8b0f6ce..f5279550 100644 --- a/Makefile +++ b/Makefile @@ -114,16 +114,23 @@ tag-client-python: test-client-python .PHONY: build-client-python build-client-python: + make build-client sdk_language=python tmpdir=${TMP_DIR} package_name=openfga_sdk_sync + make run-in-docker sdk_language=python image=busybox:${BUSYBOX_DOCKER_TAG} command="/bin/sh -c 'patch -p1 /module/openfga_sdk_sync/api/open_fga_api.py /config/clients/python/patches/open_fga_sync_api.py.patch'" + make run-in-docker sdk_language=python image=busybox:${BUSYBOX_DOCKER_TAG} command="/bin/sh -c 'mv /module/openfga_sdk/* /module/openfga_sdk_sync/ && rmdir /module/openfga_sdk'" + make build-client sdk_language=python tmpdir=${TMP_DIR} library="asyncio" make run-in-docker sdk_language=python image=busybox:${BUSYBOX_DOCKER_TAG} command="/bin/sh -c 'patch -p1 /module/openfga_sdk/api/open_fga_api.py /config/clients/python/patches/open_fga_api.py.patch'" make run-in-docker sdk_language=python image=busybox:${BUSYBOX_DOCKER_TAG} command="/bin/sh -c 'patch -p1 /module/docs/OpenFgaApi.md /config/clients/python/patches/OpenFgaApi.md.patch'" + make run-in-docker sdk_language=python image=python:${PYTHON_DOCKER_TAG} command="/bin/sh -c 'python -m pip install pycodestyle==2.10.0 autopep8==2.0.2; autopep8 --in-place --ignore E402 --recursive openfga_sdk; autopep8 --in-place --recursive test'" + make run-in-docker sdk_language=python image=python:${PYTHON_DOCKER_TAG} command="/bin/sh -c 'python -m pip install pycodestyle==2.10.0 autopep8==2.0.2; autopep8 --in-place --ignore E402 --recursive openfga_sdk_sync; autopep8 --in-place --recursive test'" make run-in-docker sdk_language=python image=python:${PYTHON_DOCKER_TAG} command="/bin/sh -c 'pip install setuptools wheel && python setup.py sdist bdist_wheel'" .PHONY: test-client-python test-client-python: build-client-python make run-in-docker sdk_language=python image=python:${PYTHON_DOCKER_TAG} command="/bin/sh -c 'python -m pip install -r test-requirements.txt; python -m unittest test/*'" make run-in-docker sdk_language=python image=python:${PYTHON_DOCKER_TAG} command="/bin/sh -c 'python -m pip install -r test-requirements.txt; python -m flake8 --ignore F401,E402,E501,W504 openfga_sdk'" + make run-in-docker sdk_language=python image=python:${PYTHON_DOCKER_TAG} command="/bin/sh -c 'python -m pip install -r test-requirements.txt; python -m flake8 --ignore F401,E402,E501,W504 openfga_sdk_sync'" # Need to ignore E402 (import order) to avoid circular dependency make run-in-docker sdk_language=python image=python:${PYTHON_DOCKER_TAG} command="/bin/sh -c 'python -m pip install -r test-requirements.txt; python -m flake8 --ignore E501 test'" @@ -161,7 +168,7 @@ run-in-docker: .EXPORT_ALL_VARIABLES: .PHONY: build-client build-client: build-openapi - SDK_LANGUAGE="${sdk_language}" TMP_DIR="${tmpdir}" LIBRARY_TEMPLATE="${library}" \ + SDK_LANGUAGE="${sdk_language}" TMP_DIR="${tmpdir}" LIBRARY_TEMPLATE="${library}" PACKAGE_NAME="${package_name}"\ ./scripts/build_client.sh .PHONY: build-openapi diff --git a/config/clients/python/patches/open_fga_sync_api.py.patch b/config/clients/python/patches/open_fga_sync_api.py.patch new file mode 100644 index 00000000..50c5c846 --- /dev/null +++ b/config/clients/python/patches/open_fga_sync_api.py.patch @@ -0,0 +1,68 @@ +--- clients/fga-python-sdk/openfga_sdk_sync/api/open_fga_api.py 2022-09-13 14:15:46.000000000 -0400 ++++ open_fga_api.py 2022-09-13 14:14:01.000000000 -0400 +@@ -197,13 +197,15 @@ + collection_formats=collection_formats, + _request_auth=local_var_params.get('_request_auth')) + +- def create_store(self, **kwargs): # noqa: E501 ++ def create_store(self, body, **kwargs): # noqa: E501 + """Create a store # noqa: E501 + + Create a unique OpenFGA store which will be used to store authorization models and relationship tuples. # noqa: E501 + +- >>> thread = api.create_store() ++ >>> thread = api.create_store(body) + ++ :param body: (required) ++ :type body: CreateStoreRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the urllib3.HTTPResponse object will +@@ -216,15 +218,17 @@ + :rtype: CreateStoreResponse + """ + kwargs['_return_http_data_only'] = True +- return self.create_store_with_http_info(**kwargs) # noqa: E501 ++ return self.create_store_with_http_info(body, **kwargs) # noqa: E501 + +- def create_store_with_http_info(self, **kwargs): # noqa: E501 ++ def create_store_with_http_info(self, body, **kwargs): # noqa: E501 + """Create a store # noqa: E501 + + Create a unique OpenFGA store which will be used to store authorization models and relationship tuples. # noqa: E501 + +- >>> thread = api.create_store_with_http_info() ++ >>> thread = api.create_store_with_http_info(body) + ++ :param body: (required) ++ :type body: CreateStoreRequest + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _return_http_data_only: response data without head status code +@@ -253,6 +257,8 @@ + + all_params = [ + ++ 'body' ++ + ] + all_params.extend( + [ +@@ -312,7 +318,7 @@ + } + + return self.api_client.call_api( +- '/stores'.replace('{store_id}', store_id), 'POST', ++ '/stores', 'POST', + path_params, + query_params, + header_params, +@@ -998,7 +1004,7 @@ + } + + return self.api_client.call_api( +- '/stores'.replace('{store_id}', store_id), 'GET', ++ '/stores', 'GET', + path_params, + query_params, + header_params, diff --git a/config/clients/python/template/api.mustache b/config/clients/python/template/api.mustache index 6f3b88ed..4629aa60 100644 --- a/config/clients/python/template/api.mustache +++ b/config/clients/python/template/api.mustache @@ -28,7 +28,7 @@ class {{classname}}(object): api_client = ApiClient() self.api_client = api_client - {{#asyncio}} +{{#asyncio}} async def __aenter__(self): return self @@ -37,7 +37,17 @@ class {{classname}}(object): async def close(self): await self.api_client.close() - {{/asyncio}} +{{/asyncio}} +{{^asyncio}} + def __enter__(self): + return self + + def __exit__(self): + self.close() + + def close(self): + self.api_client.close() +{{/asyncio}} {{#operation}} @@ -49,10 +59,10 @@ class {{classname}}(object): {{/notes}} {{#sortParamsByRequiredFlag}} - >>> thread = await api.{{operationId}}({{#allParams}}{{#required}}{{^-first}}{{paramName}}{{^-last}}, {{/-last}}{{/-first}}{{/required}}{{/allParams}}) + >>> thread = {{#asyncio}}await {{/asyncio}}api.{{operationId}}({{#allParams}}{{#required}}{{^-first}}{{paramName}}{{^-last}}, {{/-last}}{{/-first}}{{/required}}{{/allParams}}) {{/sortParamsByRequiredFlag}} {{^sortParamsByRequiredFlag}} - >>> thread = await api.{{operationId}}({{#allParams}}{{#required}}{{^-first}}{{paramName}}={{paramName}}_value{{^-last}}, {{/-last}} {{/-first}}{{/required}}{{/allParams}}) + >>> thread = {{#asyncio}}await {{/asyncio}}api.{{operationId}}({{#allParams}}{{#required}}{{^-first}}{{paramName}}={{paramName}}_value{{^-last}}, {{/-last}} {{/-first}}{{/required}}{{/allParams}}) {{/sortParamsByRequiredFlag}} {{#requiredParams}} diff --git a/config/clients/python/template/api_client.mustache b/config/clients/python/template/api_client.mustache index 93c2c4c5..7592ad7d 100644 --- a/config/clients/python/template/api_client.mustache +++ b/config/clients/python/template/api_client.mustache @@ -4,6 +4,9 @@ {{#asyncio}} import asyncio {{/asyncio}} +{{^asyncio}} +import time +{{/asyncio}} import atexit import datetime from dateutil.parser import parse @@ -222,7 +225,8 @@ class ApiClient(object): _request_timeout=_request_timeout) except RateLimitExceededError as e: if x < max_retry: - {{#asyncio}}await asyncio{{/asyncio}}.sleep(random_time(x, min_wait_in_ms)) + {{#asyncio}}await asyncio.sleep(random_time(x, min_wait_in_ms)){{/asyncio}} + {{^asyncio}}time.sleep(random_time(x, min_wait_in_ms)){{/asyncio}} continue e.body = e.body.decode('utf-8') if six.PY3 else e.body response_type = response_types_map.get(e.status, None) diff --git a/config/clients/python/template/api_test.mustache b/config/clients/python/template/api_test.mustache index c81cf442..a3c0cdeb 100644 --- a/config/clients/python/template/api_test.mustache +++ b/config/clients/python/template/api_test.mustache @@ -10,7 +10,7 @@ from datetime import datetime import urllib3 -import {{packageName}} +import {{packageName}}{{^asyncio}} as openfga_sdk{{/asyncio}} from {{packageName}} import rest from {{packageName}}.api import open_fga_api from {{packageName}}.credentials import Credentials, CredentialConfiguration @@ -102,7 +102,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) body = CheckRequest( tuple_key=TupleKey( @@ -112,7 +112,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): ), authorization_model_id="01GXSA8YR785C4FYS3C0RTG7B1", ) - api_response = await api_instance.check( + api_response = {{#asyncio}}await {{/asyncio}}api_instance.check( body=body, ) self.assertIsInstance(api_response, CheckResponse) @@ -129,7 +129,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') async def test_create_store(self, mock_request): @@ -146,12 +146,12 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 201) configuration = self.configuration - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) body = CreateStoreRequest( name="test-store", ) - api_response = await api_instance.create_store( + api_response = {{#asyncio}}await {{/asyncio}}api_instance.create_store( body=body, ) self.assertIsInstance(api_response, CreateStoreResponse) @@ -166,7 +166,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') async def test_delete_store(self, mock_request): @@ -178,9 +178,9 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 201) configuration = self.configuration configuration.store_id = store_id - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) - await api_instance.delete_store() + {{#asyncio}}await {{/asyncio}}api_instance.delete_store() mock_request.assert_called_once_with( 'DELETE', 'http://api.{{sampleApiDomain}}/stores/01H0H015178Y2V4CX10C2KGHF4', @@ -190,7 +190,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') async def test_expand(self, mock_request): @@ -204,7 +204,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration configuration.store_id = store_id - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) body = ExpandRequest( tuple_key=TupleKey( @@ -213,7 +213,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): ), authorization_model_id="01GXSA8YR785C4FYS3C0RTG7B1", ) - api_response = await api_instance.expand( + api_response = {{#asyncio}}await {{/asyncio}}api_instance.expand( body=body, ) self.assertIsInstance(api_response, ExpandResponse) @@ -233,7 +233,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') async def test_get_store(self, mock_request): @@ -251,10 +251,10 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration configuration.store_id = store_id - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) # Get a store - api_response = await api_instance.get_store() + api_response = {{#asyncio}}await {{/asyncio}}api_instance.get_store() self.assertIsInstance(api_response, GetStoreResponse) self.assertEqual(api_response.id, '01H0H015178Y2V4CX10C2KGHF4') self.assertEqual(api_response.name, 'test_store') @@ -266,7 +266,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') async def test_list_objects(self, mock_request): @@ -284,7 +284,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration configuration.store_id = store_id - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) body = ListObjectsRequest( authorization_model_id="01G5JAVJ41T49E9TT3SKVS7X1J", @@ -293,7 +293,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): user="user:81684243-9356-4421-8fbf-a4f8d36aa31b", ) # Get all stores - api_response = await api_instance.list_objects(body) + api_response = {{#asyncio}}await {{/asyncio}}api_instance.list_objects(body) self.assertIsInstance(api_response, ListObjectsResponse) self.assertEqual(api_response.objects, ['document:abcd1234']) mock_request.assert_called_once_with( @@ -307,7 +307,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') async def test_list_stores(self, mock_request): @@ -338,10 +338,10 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): ''' mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) # Get all stores - api_response = await api_instance.list_stores( + api_response = {{#asyncio}}await {{/asyncio}}api_instance.list_stores( page_size=1, continuation_token="continuation_token_example", ) @@ -374,7 +374,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') async def test_read(self, mock_request): @@ -399,7 +399,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration configuration.store_id = store_id - async with openfga_sdk.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with openfga_sdk.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) body = ReadRequest( tuple_key=TupleKey( @@ -410,7 +410,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): page_size=50, continuation_token="eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==", ) - api_response = await api_instance.read( + api_response = {{#asyncio}}await {{/asyncio}}api_instance.read( body=body, ) self.assertIsInstance(api_response, ReadResponse) @@ -453,9 +453,9 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration configuration.store_id = store_id - async with openfga_sdk.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with openfga_sdk.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) - api_response = await api_instance.read_assertions( + api_response = {{#asyncio}}await {{/asyncio}}api_instance.read_assertions( "01G5JAVJ41T49E9TT3SKVS7X1J", ) self.assertIsInstance(api_response, ReadAssertionsResponse) @@ -521,12 +521,12 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id # Enter a context with an instance of the API client - async with openfga_sdk.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = open_fga_api.OpenFgaApi(api_client) # Return a particular version of an authorization model - api_response = await api_instance.read_authorization_model( + api_response = {{#asyncio}}await {{/asyncio}}api_instance.read_authorization_model( "01G5JAVJ41T49E9TT3SKVS7X1J", ) self.assertIsInstance(api_response, ReadAuthorizationModelResponse) @@ -589,12 +589,12 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id # Enter a context with an instance of the API client - async with openfga_sdk.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = open_fga_api.OpenFgaApi(api_client) # Return a particular version of an authorization model - api_response = await api_instance.read_changes( + api_response = {{#asyncio}}await {{/asyncio}}api_instance.read_changes( page_size=1, continuation_token="abcdefg", type="document" @@ -628,7 +628,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id # Enter a context with an instance of the API client - async with openfga_sdk.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = open_fga_api.OpenFgaApi(api_client) @@ -646,7 +646,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): ), authorization_model_id="01G5JAVJ41T49E9TT3SKVS7X1J", ) - await api_instance.write( + {{#asyncio}}await {{/asyncio}}api_instance.write( body, ) mock_request.assert_called_once_with( @@ -671,7 +671,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id # Enter a context with an instance of the API client - async with openfga_sdk.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = open_fga_api.OpenFgaApi(api_client) @@ -689,7 +689,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): ), authorization_model_id="01G5JAVJ41T49E9TT3SKVS7X1J", ) - await api_instance.write( + {{#asyncio}}await {{/asyncio}}api_instance.write( body, ) mock_request.assert_called_once_with( @@ -714,7 +714,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id # Enter a context with an instance of the API client - async with openfga_sdk.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = open_fga_api.OpenFgaApi(api_client) @@ -732,7 +732,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): ], ) # Upsert assertions for an authorization model ID - await api_instance.write_assertions( + {{#asyncio}}await {{/asyncio}}api_instance.write_assertions( authorization_model_id="xyz0123", body=body, ) @@ -757,7 +757,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 201) configuration = self.configuration configuration.store_id = store_id - async with openfga_sdk.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = open_fga_api.OpenFgaApi(api_client) @@ -787,7 +787,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): ], ) # Create a new authorization model - api_response = await api_instance.write_authorization_model( + api_response = {{#asyncio}}await {{/asyncio}}api_instance.write_authorization_model( body ) self.assertIsInstance(api_response, WriteAuthorizationModelResponse) @@ -905,13 +905,13 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): ) configuration.store_id = 'xyz123' # Enter a context with an instance of the API client - async with openfga_sdk.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = open_fga_api.OpenFgaApi(api_client) # expects FgaValidationException to be thrown because api_scheme is bad with self.assertRaises(ApiValueError): - await api_instance.read_authorization_models( + {{#asyncio}}await {{/asyncio}}api_instance.read_authorization_models( page_size= 1, continuation_token= "abcdefg" ) @@ -927,13 +927,13 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): ) # Notice the store_id is not set # Enter a context with an instance of the API client - async with openfga_sdk.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with openfga_sdk.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = open_fga_api.OpenFgaApi(api_client) # expects FgaValidationException to be thrown because store_id is not specified with self.assertRaises(FgaValidationException): - await api_instance.read_authorization_models( + {{#asyncio}}await {{/asyncio}}api_instance.read_authorization_models( page_size= 1, continuation_token= "abcdefg" ) @@ -953,7 +953,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) body = CheckRequest( tuple_key=TupleKey( @@ -963,7 +963,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): ), ) with self.assertRaises(ValidationException) as api_exception: - await api_instance.check( + {{#asyncio}}await {{/asyncio}}api_instance.check( body=body, ) self.assertIsInstance(api_exception.exception.parsed_exception, ValidationErrorMessageResponse) @@ -987,7 +987,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) body = CheckRequest( tuple_key=TupleKey( @@ -997,7 +997,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): ), ) with self.assertRaises(NotFoundException) as api_exception: - await api_instance.check( + {{#asyncio}}await {{/asyncio}}api_instance.check( body=body, ) self.assertIsInstance(api_exception.exception.parsed_exception, PathUnknownErrorMessageResponse) @@ -1022,7 +1022,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id configuration.retry_params = retry - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) body = CheckRequest( tuple_key=TupleKey( @@ -1032,7 +1032,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): ), ) with self.assertRaises(RateLimitExceededError) as api_exception: - await api_instance.check( + {{#asyncio}}await {{/asyncio}}api_instance.check( body=body, ) self.assertIsInstance(api_exception.exception, RateLimitExceededError) @@ -1058,7 +1058,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id configuration.retry_params = retry - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) body = CheckRequest( tuple_key=TupleKey( @@ -1067,7 +1067,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): user="user:81684243-9356-4421-8fbf-a4f8d36aa31b", ), ) - api_response = await api_instance.check( + api_response = {{#asyncio}}await {{/asyncio}}api_instance.check( body=body, ) self.assertIsInstance(api_response, CheckResponse) @@ -1091,7 +1091,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) body = CheckRequest( tuple_key=TupleKey( @@ -1101,7 +1101,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): ), ) with self.assertRaises(ServiceException) as api_exception: - await api_instance.check( + {{#asyncio}}await {{/asyncio}}api_instance.check( body=body, ) self.assertIsInstance(api_exception.exception.parsed_exception, InternalErrorMessageResponse) @@ -1122,7 +1122,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id configuration.credentials = Credentials(method='api_token', configuration=CredentialConfiguration(api_token='TOKEN1')) - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_instance = open_fga_api.OpenFgaApi(api_client) body = CheckRequest( tuple_key=TupleKey( @@ -1131,7 +1131,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): user="user:81684243-9356-4421-8fbf-a4f8d36aa31b", ), ) - api_response = await api_instance.check( + api_response = {{#asyncio}}await {{/asyncio}}api_instance.check( body=body, ) self.assertIsInstance(api_response, CheckResponse) @@ -1162,7 +1162,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id - async with {{packageName}}.ApiClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with {{packageName}}.ApiClient(configuration) as api_client: api_client.set_default_header("Custom Header", "custom value") api_instance = open_fga_api.OpenFgaApi(api_client) body = CheckRequest( @@ -1172,7 +1172,7 @@ class {{#operations}}Test{{classname}}(IsolatedAsyncioTestCase): user="user:81684243-9356-4421-8fbf-a4f8d36aa31b", ), ) - api_response = await api_instance.check( + api_response = {{#asyncio}}await {{/asyncio}}api_instance.check( body=body, ) self.assertIsInstance(api_response, CheckResponse) diff --git a/config/clients/python/template/client/client.mustache b/config/clients/python/template/client/client.mustache index 466c36cb..5ab18417 100644 --- a/config/clients/python/template/client/client.mustache +++ b/config/clients/python/template/client/client.mustache @@ -30,7 +30,12 @@ from {{packageName}}.models.write_authorization_model_request import WriteAuthor from {{packageName}}.models.write_request import WriteRequest from {{packageName}}.validation import is_well_formed_ulid_string +{{#asyncio}} import asyncio +{{/asyncio}} +{{^asyncio}} +import time +{{/asyncio}} import uuid from typing import List @@ -100,14 +105,23 @@ class OpenFgaClient(): self._api_client = ApiClient(configuration) self._api = OpenFgaApi(self._api_client) + {{#asyncio}} async def __aenter__(self): return self async def __aexit__(self, exc_type, exc_value, traceback): await self.close() + {{/asyncio}} + {{^asyncio}} + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + {{/asyncio}} - async def close(self): - await self._api.close() + {{#asyncio}}async {{/asyncio}}def close(self): + {{#asyncio}}await {{/asyncio}}self._api.close() def _get_authorization_model_id(self, options: object) -> str | None: """ @@ -148,21 +162,21 @@ class OpenFgaClient(): """ return self._client_configuration.authorization_model_id - async def _check_valid_api_connection(self, options: dict[str, int | str]): + {{#asyncio}}async {{/asyncio}}def _check_valid_api_connection(self, options: dict[str, int | str]): """ Checks that a connection with the given configuration can be established """ authorization_model_id = self._get_authorization_model_id(options) if authorization_model_id is not None and authorization_model_id != "": - await self.read_authorization_model(options) + {{#asyncio}}await {{/asyncio}}self.read_authorization_model(options) else: - await self.read_latest_authorization_model(options) + {{#asyncio}}await {{/asyncio}}self.read_latest_authorization_model(options) ################# # Stores ################# - async def list_stores(self, options: dict[str, int|str] = None): + {{#asyncio}}async {{/asyncio}}def list_stores(self, options: dict[str, int|str] = None): """ List the stores in the system :param page_size(options) - Number of items returned per request @@ -175,12 +189,12 @@ class OpenFgaClient(): # convert options to kargs options = set_heading_if_not_set(options, CLIENT_METHOD_HEADER, "ListStores") kwargs = options_to_kwargs(options) - api_response = await self._api.list_stores( + api_response = {{#asyncio}}await {{/asyncio}}self._api.list_stores( **kwargs, ) return api_response - async def create_store(self, body: CreateStoreRequest, options: dict[str, int|str] = None): + {{#asyncio}}async {{/asyncio}}def create_store(self, body: CreateStoreRequest, options: dict[str, int|str] = None): """ Create the stores in the system :param header(options) - Custom headers to send alongside the request @@ -190,13 +204,13 @@ class OpenFgaClient(): """ options = set_heading_if_not_set(options, CLIENT_METHOD_HEADER, "CreateStore") kwargs = options_to_kwargs(options) - api_response = await self._api.create_store( + api_response = {{#asyncio}}await {{/asyncio}}self._api.create_store( body, **kwargs ) return api_response - async def get_store(self, options: dict[str, int|str] = None): + {{#asyncio}}async {{/asyncio}}def get_store(self, options: dict[str, int|str] = None): """ Get the store info in the system. Store id is from the configuration. :param header(options) - Custom headers to send alongside the request @@ -206,12 +220,12 @@ class OpenFgaClient(): """ options = set_heading_if_not_set(options, CLIENT_METHOD_HEADER, "GetStore") kwargs = options_to_kwargs(options) - api_response = await self._api.get_store( + api_response = {{#asyncio}}await {{/asyncio}}self._api.get_store( **kwargs, ) return api_response - async def delete_store(self, options: dict[str, int|str] = None): + {{#asyncio}}async {{/asyncio}}def delete_store(self, options: dict[str, int|str] = None): """ Delete the store from the system. Store id is from the configuration. :param header(options) - Custom headers to send alongside the request @@ -221,7 +235,7 @@ class OpenFgaClient(): """ options = set_heading_if_not_set(options, CLIENT_METHOD_HEADER, "DeleteStore") kwargs = options_to_kwargs(options) - api_response = await self._api.delete_store( + api_response = {{#asyncio}}await {{/asyncio}}self._api.delete_store( **kwargs, ) return api_response @@ -230,7 +244,7 @@ class OpenFgaClient(): # Authorization Models ####################### - async def read_authorization_models(self, options: dict[str, int|str] = None): + {{#asyncio}}async {{/asyncio}}def read_authorization_models(self, options: dict[str, int|str] = None): """ Return all the authorization models for a particular store. :param header(options) - Custom headers to send alongside the request @@ -240,12 +254,12 @@ class OpenFgaClient(): """ options = set_heading_if_not_set(options, CLIENT_METHOD_HEADER, "ReadAuthorizationModels") kwargs = options_to_kwargs(options) - api_response = await self._api.read_authorization_models( + api_response = {{#asyncio}}await {{/asyncio}}self._api.read_authorization_models( **kwargs, ) return api_response - async def write_authorization_model(self, body: WriteAuthorizationModelRequest, options: dict[str, int|str] = None): + {{#asyncio}}async {{/asyncio}}def write_authorization_model(self, body: WriteAuthorizationModelRequest, options: dict[str, int|str] = None): """ Write authorization model. :param body - WriteAuthorizationModelRequest @@ -256,13 +270,13 @@ class OpenFgaClient(): """ options = set_heading_if_not_set(options, CLIENT_METHOD_HEADER, "WriteAuthorizationModel") kwargs = options_to_kwargs(options) - api_response = await self._api.write_authorization_model( + api_response = {{#asyncio}}await {{/asyncio}}self._api.write_authorization_model( body, **kwargs, ) return api_response - async def read_authorization_model(self, options: dict[str, int|str] = None): + {{#asyncio}}async {{/asyncio}}def read_authorization_model(self, options: dict[str, int|str] = None): """ Read an authorization model. :param header(options) - Custom headers to send alongside the request @@ -273,13 +287,13 @@ class OpenFgaClient(): options = set_heading_if_not_set(options, CLIENT_METHOD_HEADER, "ReadAuthorizationModel") kwargs = options_to_kwargs(options) authorization_model_id=self._get_authorization_model_id(options) - api_response = await self._api.read_authorization_model( + api_response = {{#asyncio}}await {{/asyncio}}self._api.read_authorization_model( authorization_model_id, **kwargs, ) return api_response - async def read_latest_authorization_model(self, options: dict[str, int|str] = None): + {{#asyncio}}async {{/asyncio}}def read_latest_authorization_model(self, options: dict[str, int|str] = None): """ Convenient method of reading the latest authorizaiton model :param header(options) - Custom headers to send alongside the request @@ -289,14 +303,14 @@ class OpenFgaClient(): """ options = set_heading_if_not_set(options, CLIENT_METHOD_HEADER, "ReadLatestAuthoriationModel") options["page_size"] = 1 - api_response = await self.read_authorization_models(options) + api_response = {{#asyncio}}await {{/asyncio}}self.read_authorization_models(options) return ReadAuthorizationModelResponse(api_response.authorization_models[0]) ####################### # Relationship Tuples ####################### - async def read_changes(self, body: ClientReadChangesRequest, options: dict[str, str] = None): + {{#asyncio}}async {{/asyncio}}def read_changes(self, body: ClientReadChangesRequest, options: dict[str, str] = None): """ Read changes for specified type :param body - the type we want to look for change @@ -310,12 +324,12 @@ class OpenFgaClient(): options = set_heading_if_not_set(options, CLIENT_METHOD_HEADER, "ReadChanges") kwargs = options_to_kwargs(options) kwargs["type"] = body.type - api_response = await self._api.read_changes( + api_response = {{#asyncio}}await {{/asyncio}}self._api.read_changes( **kwargs, ) return api_response - async def read(self, body: TupleKey, options: dict[str, str] = None): + {{#asyncio}}async {{/asyncio}}def read(self, body: TupleKey, options: dict[str, str] = None): """ Read changes for specified type :param body - the tuples we want to read @@ -338,7 +352,7 @@ class OpenFgaClient(): options.pop("continuation_token") kwargs = options_to_kwargs(options) - api_response = await self._api.read( + api_response = {{#asyncio}}await {{/asyncio}}self._api.read( ReadRequest( tuple_key=body, page_size=page_size, @@ -348,7 +362,7 @@ class OpenFgaClient(): ) return api_response - async def _write_single_batch(self, batch: List[ClientTuple], is_write: bool, options: dict[str, str] = None): + {{#asyncio}}async {{/asyncio}}def _write_single_batch(self, batch: List[ClientTuple], is_write: bool, options: dict[str, str] = None): try: write_batch = None delete_batch = None @@ -356,12 +370,12 @@ class OpenFgaClient(): write_batch = batch else: delete_batch = batch - await self._write_with_transaction(ClientWriteRequest(writes=write_batch, deletes=delete_batch), options) + {{#asyncio}}await {{/asyncio}}self._write_with_transaction(ClientWriteRequest(writes=write_batch, deletes=delete_batch), options) return [construct_write_single_response(i, True, None) for i in batch] except Exception as err: return [construct_write_single_response(i, False, err) for i in batch] - async def _write_batches(self, tuple_keys: List[ClientTuple], transaction: WriteTransactionOpts, is_write: bool, options: dict[str, str] = None): + {{#asyncio}}async {{/asyncio}}def _write_batches(self, tuple_keys: List[ClientTuple], transaction: WriteTransactionOpts, is_write: bool, options: dict[str, str] = None): """ Internal function for write/delete batches """ @@ -370,14 +384,19 @@ class OpenFgaClient(): write_batches = _chuck_array(chunks, transaction.max_parallel_requests) batch_write_responses = [] for write_batch in write_batches: + {{#asyncio}} request = [self._write_single_batch(i, is_write, options) for i in write_batch] response = await asyncio.gather(*request) + {{/asyncio}} + {{^asyncio}} + response = [self._write_single_batch(i, is_write, options) for i in write_batch] + {{/asyncio}} flatten_list = [item for batch_single_response in response for item in batch_single_response] batch_write_responses.extend(flatten_list) return batch_write_responses - async def _write_with_transaction(self, body: ClientWriteRequest, options: dict[str, str] = None): + {{#asyncio}}async {{/asyncio}}def _write_with_transaction(self, body: ClientWriteRequest, options: dict[str, str] = None): """ Write or deletes tuples """ @@ -389,7 +408,7 @@ class OpenFgaClient(): if body.deletes_tuple_keys: deletes_tuple_keys=body.deletes_tuple_keys - await self._api.write( + {{#asyncio}}await {{/asyncio}}self._api.write( WriteRequest( writes=writes_tuple_keys, deletes=deletes_tuple_keys, @@ -406,7 +425,7 @@ class OpenFgaClient(): deletes_response = [construct_write_single_response(i, True, None) for i in body.deletes] return ClientWriteResponse(writes=writes_response, deletes=deletes_response) - async def write(self, body: ClientWriteRequest, options: dict[str, str] = None): + {{#asyncio}}async {{/asyncio}}def write(self, body: ClientWriteRequest, options: dict[str, str] = None): """ Write or deletes tuples :param body - the write request @@ -418,23 +437,23 @@ class OpenFgaClient(): options = set_heading_if_not_set(options, CLIENT_METHOD_HEADER, "Writes") transaction = options_to_transaction_info(options) if not transaction.disabled: - results = await self._write_with_transaction(body, options) + results = {{#asyncio}}await {{/asyncio}}self._write_with_transaction(body, options) return results options = set_heading_if_not_set(options, CLIENT_BULK_REQUEST_ID_HEADER, str(uuid.uuid4())) # TODO: this should be run in parallel - await self._check_valid_api_connection(options) + {{#asyncio}}await {{/asyncio}}self._check_valid_api_connection(options) # otherwise, it is not a transaction and it is a batch write requests writes_response = None if body.writes: - writes_response = await self._write_batches(body.writes, transaction, True, options) + writes_response = {{#asyncio}}await {{/asyncio}}self._write_batches(body.writes, transaction, True, options) deletes_response = None if body.deletes: - deletes_response = await self._write_batches(body.deletes, transaction, False, options) + deletes_response = {{#asyncio}}await {{/asyncio}}self._write_batches(body.deletes, transaction, False, options) return ClientWriteResponse(writes=writes_response, deletes=deletes_response) - async def write_tuples(self, body: List[ClientTuple], options: dict[str, str] = None): + {{#asyncio}}async {{/asyncio}}def write_tuples(self, body: List[ClientTuple], options: dict[str, str] = None): """ Convenient method for writing tuples :param body - the list of tuples we want to write @@ -444,10 +463,10 @@ class OpenFgaClient(): :param retryParams.minWaitInMs(options) - Override the minimum wait before a retry is initiated """ options = set_heading_if_not_set(options, CLIENT_METHOD_HEADER, "WriteTuples") - result = await self.write(ClientWriteRequest(body, None), options) + result = {{#asyncio}}await {{/asyncio}}self.write(ClientWriteRequest(body, None), options) return result - async def delete_tuples(self, body: List[ClientTuple], options: dict[str, str] = None): + {{#asyncio}}async {{/asyncio}}def delete_tuples(self, body: List[ClientTuple], options: dict[str, str] = None): """ Convenient method for deleteing tuples :param body - the list of tuples we want to delete @@ -457,13 +476,13 @@ class OpenFgaClient(): :param retryParams.minWaitInMs(options) - Override the minimum wait before a retry is initiated """ options = set_heading_if_not_set(options, CLIENT_METHOD_HEADER, "DeleteTuples") - result = await self.write(ClientWriteRequest(None, body), options) + result = {{#asyncio}}await {{/asyncio}}self.write(ClientWriteRequest(None, body), options) return result ####################### # Relationship Queries ####################### - async def check(self, body: ClientCheckRequest, options: dict[str, str] = None): # noqa: E501 + {{#asyncio}}async {{/asyncio}}def check(self, body: ClientCheckRequest, options: dict[str, str] = None): # noqa: E501 """ Check whether a user is authorized to access an object :param body - ClientCheckRequest defining check request @@ -489,25 +508,25 @@ class OpenFgaClient(): req_body.contextual_tuples = ContextualTupleKeys( tuple_keys=convert_tuple_keys(body.contextual_tuples) ) - api_response = await self._api.check( + api_response = {{#asyncio}}await {{/asyncio}}self._api.check( body=req_body, **kwargs ) return api_response - async def _single_batch_check(self, body: ClientCheckRequest, options: dict[str, str] = None): # noqa: E501 + {{#asyncio}}async {{/asyncio}}def _single_batch_check(self, body: ClientCheckRequest, options: dict[str, str] = None): # noqa: E501 """ Run a single batch request and return body in a SingleBatchCheckResponse :param body - ClientCheckRequest defining check request :param authorization_model_id(options) - Overrides the authorization model id in the configuration """ try: - api_response = await self.check(body, options) + api_response = {{#asyncio}}await {{/asyncio}}self.check(body, options) return BatchCheckResponse(allowed=api_response.allowed, request=body, response=api_response, error=None) except Exception as err: return BatchCheckResponse(allowed=False, request=body, response=None, error=err) - async def batch_check(self, body: List[ClientCheckRequest], options: dict[str, str] = None): # noqa: E501 + {{#asyncio}}async {{/asyncio}}def batch_check(self, body: List[ClientCheckRequest], options: dict[str, str] = None): # noqa: E501 """ Run a set of checks :param body - list of ClientCheckRequest defining check request @@ -522,7 +541,7 @@ class OpenFgaClient(): options = set_heading_if_not_set(options, CLIENT_BULK_REQUEST_ID_HEADER, str(uuid.uuid4())) # TODO: this should be run in parallel - await self._check_valid_api_connection(options) + {{#asyncio}}await {{/asyncio}}self._check_valid_api_connection(options) max_parallel_requests = {{ clientMaxMethodParallelRequests }} if options is not None and "max_parallel_requests" in options: @@ -531,12 +550,17 @@ class OpenFgaClient(): request_batches = _chuck_array(body, max_parallel_requests) batch_check_response = [] for request_batch in request_batches: + {{#asyncio}} request = [self._single_batch_check(i, options) for i in request_batch] response = await asyncio.gather(*request) + {{/asyncio}} + {{^asyncio}} + response = [self._single_batch_check(i, options) for i in request_batch] + {{/asyncio}} batch_check_response.extend(response) return batch_check_response - async def expand(self, body: ClientExpandRequest, options: dict[str, str] = None): # noqa: E501 + {{#asyncio}}async {{/asyncio}}def expand(self, body: ClientExpandRequest, options: dict[str, str] = None): # noqa: E501 """ Run expand request :param body - list of ClientExpandRequest defining expand request @@ -556,13 +580,13 @@ class OpenFgaClient(): ), authorization_model_id=self._get_authorization_model_id(options), ) - api_response = await self._api.expand( + api_response = {{#asyncio}}await {{/asyncio}}self._api.expand( body=req_body, **kwargs ) return api_response - async def list_objects(self, body: ClientListObjectsRequest, options: dict[str, str] = None): # noqa: E501 + {{#asyncio}}async {{/asyncio}}def list_objects(self, body: ClientListObjectsRequest, options: dict[str, str] = None): # noqa: E501 """ Run list object request :param body - list object parameters @@ -585,13 +609,13 @@ class OpenFgaClient(): req_body.contextual_tuples = ContextualTupleKeys( tuple_keys=convert_tuple_keys(body.contextual_tuples) ) - api_response = await self._api.list_objects( + api_response = {{#asyncio}}await {{/asyncio}}self._api.list_objects( body=req_body, **kwargs ) return api_response - async def list_relations(self, body: ClientListObjectsRequest, options: dict[str, str] = None): # noqa: E501 + {{#asyncio}}async {{/asyncio}}def list_relations(self, body: ClientListObjectsRequest, options: dict[str, str] = None): # noqa: E501 """ Return all the relations for which user has a relationship with the object :param body - list relation request @@ -605,7 +629,7 @@ class OpenFgaClient(): options = set_heading_if_not_set(options, CLIENT_BULK_REQUEST_ID_HEADER, str(uuid.uuid4())) request_body = [construct_check_request(user=body.user, relation=i, object=body.object, contextual_tuples=body.contextual_tuples) for i in body.relations] - result = await self.batch_check(request_body, options) + result = {{#asyncio}}await {{/asyncio}}self.batch_check(request_body, options) # need to filter with the allowed response result_iterator = filter(_check_allowed, result) result_list = list(result_iterator) @@ -615,7 +639,7 @@ class OpenFgaClient(): ####################### # Assertions ####################### - async def read_assertions(self, options: dict[str, str] = None): # noqa: E501 + {{#asyncio}}async {{/asyncio}}def read_assertions(self, options: dict[str, str] = None): # noqa: E501 """ Return the assertions :param authorization_model_id(options) - Overrides the authorization model id in the configuration @@ -628,10 +652,10 @@ class OpenFgaClient(): kwargs = options_to_kwargs(options) authorization_model_id=self._get_authorization_model_id(options) - api_response = await self._api.read_assertions(authorization_model_id, **kwargs) + api_response = {{#asyncio}}await {{/asyncio}}self._api.read_assertions(authorization_model_id, **kwargs) return api_response - async def write_assertions(self, body:List[ClientAssertion], options: dict[str, str] = None): # noqa: E501 + {{#asyncio}}async {{/asyncio}}def write_assertions(self, body:List[ClientAssertion], options: dict[str, str] = None): # noqa: E501 """ Upsert the assertions :param body - Write assertion request @@ -653,5 +677,5 @@ class OpenFgaClient(): ), client_assertion.expectation) api_request_body = WriteAssertionsRequest([map_to_assertion(client_assertion) for client_assertion in body]) - api_response = await self._api.write_assertions(authorization_model_id, api_request_body, **kwargs) + api_response = {{#asyncio}}await {{/asyncio}}self._api.write_assertions(authorization_model_id, api_request_body, **kwargs) return api_response diff --git a/config/clients/python/template/client/test_client.mustache b/config/clients/python/template/client/test_client.mustache index a82a1df5..65549779 100644 --- a/config/clients/python/template/client/test_client.mustache +++ b/config/clients/python/template/client/test_client.mustache @@ -88,7 +88,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): @patch.object(rest.RESTClientObject, 'request') - async def test_list_stores(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_list_stores(self, mock_request): """Test case for list_stores Get all stores # noqa: E501 @@ -116,8 +116,8 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ''' mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration - async with OpenFgaClient(configuration) as api_client: - api_response = await api_client.list_stores( + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: + api_response = {{#asyncio}}await {{/asyncio}}api_client.list_stores( options={"page_size": 1, "continuation_token": "continuation_token_example"} ) self.assertIsInstance(api_response, ListStoresResponse) @@ -149,10 +149,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_create_store(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_create_store(self, mock_request): """Test case for create_store Create a store # noqa: E501 @@ -165,8 +165,8 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ''' mock_request.return_value = mock_response(response_body, 201) configuration = self.configuration - async with OpenFgaClient(configuration) as api_client: - api_response = await api_client.create_store( + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: + api_response = {{#asyncio}}await {{/asyncio}}api_client.create_store( CreateStoreRequest(name="test-store"), options={} ) @@ -182,11 +182,11 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_get_store(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_get_store(self, mock_request): """Test case for get_store Get all stores # noqa: E501 @@ -202,8 +202,8 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: - api_response = await api_client.get_store( + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: + api_response = {{#asyncio}}await {{/asyncio}}api_client.get_store( options={} ) self.assertIsInstance(api_response, GetStoreResponse) @@ -217,10 +217,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_delete_store(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_delete_store(self, mock_request): """Test case for delete_store Get all stores # noqa: E501 @@ -228,8 +228,8 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): mock_request.return_value = mock_response('', 201) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: - await api_client.delete_store( + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: + {{#asyncio}}await {{/asyncio}}api_client.delete_store( options={} ) mock_request.assert_called_once_with( @@ -241,10 +241,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_read_authorization_models(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_read_authorization_models(self, mock_request): """Test case for read_authorization_models Return all authorization models configured for the store # noqa: E501 @@ -287,10 +287,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id # Enter a context with an instance of the API client - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: # Return a particular version of an authorization model - api_response = await api_client.read_authorization_models( + api_response = {{#asyncio}}await {{/asyncio}}api_client.read_authorization_models( options={} ) self.assertIsInstance(api_response, ReadAuthorizationModelsResponse) @@ -329,7 +329,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_write_authorization_model(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_write_authorization_model(self, mock_request): """Test case for write_authorization_model Create a new authorization model # noqa: E501 @@ -338,7 +338,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 201) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: # example passing only required values which don't have defaults set body = WriteAuthorizationModelRequest( schema_version="1.1", @@ -365,7 +365,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ], ) # Create a new authorization model - api_response = await api_client.write_authorization_model( + api_response = {{#asyncio}}await {{/asyncio}}api_client.write_authorization_model( body, options={} ) @@ -388,7 +388,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): @patch.object(rest.RESTClientObject, 'request') - async def test_read_authorization_model(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_read_authorization_model(self, mock_request): """Test case for read_authorization_model Return a particular version of an authorization model # noqa: E501 @@ -430,10 +430,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id # Enter a context with an instance of the API client - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: # Return a particular version of an authorization model - api_response = await api_client.read_authorization_model( + api_response = {{#asyncio}}await {{/asyncio}}api_client.read_authorization_model( options={"authorization_model_id": "01G5JAVJ41T49E9TT3SKVS7X1J"} ) self.assertIsInstance(api_response, ReadAuthorizationModelResponse) @@ -471,7 +471,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_read_latest_authorization_model(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_read_latest_authorization_model(self, mock_request): """Test case for read_latest_authorization_model Return the latest authorization models configured for the store # noqa: E501 @@ -514,10 +514,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id # Enter a context with an instance of the API client - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: # Return a particular version of an authorization model - api_response = await api_client.read_latest_authorization_model( + api_response = {{#asyncio}}await {{/asyncio}}api_client.read_latest_authorization_model( options={} ) self.assertIsInstance(api_response, ReadAuthorizationModelResponse) @@ -556,7 +556,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): @patch.object(rest.RESTClientObject, 'request') - async def test_read_changes(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_read_changes(self, mock_request): """Test case for read_changes Return a list of all the tuple changes # noqa: E501 @@ -581,10 +581,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id # Enter a context with an instance of the API client - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: # Return a particular version of an authorization model - api_response = await api_client.read_changes( + api_response = {{#asyncio}}await {{/asyncio}}api_client.read_changes( ClientReadChangesRequest("document"), options={"page_size":1, "continuation_token":"abcdefg"} ) @@ -610,7 +610,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_read(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_read(self, mock_request): """Test case for read Get tuples from the store that matches a query, without following userset rewrite rules # noqa: E501 @@ -633,13 +633,13 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id # Enter a context with an instance of the API client - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: body = TupleKey( object="document:2021-budget", relation="reader", user="user:81684243-9356-4421-8fbf-a4f8d36aa31b", ) - api_response = await api_client.read( + api_response = {{#asyncio}}await {{/asyncio}}api_client.read( body=body, options={"page_size":50, "continuation_token":"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="} ) @@ -663,7 +663,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): @patch.object(rest.RESTClientObject, 'request') - async def test_read_empty_options(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_read_empty_options(self, mock_request): """Test case for read with empty options Get tuples from the store that matches a query, without following userset rewrite rules # noqa: E501 @@ -686,13 +686,13 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id # Enter a context with an instance of the API client - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: body = TupleKey( object="document:2021-budget", relation="reader", user="user:81684243-9356-4421-8fbf-a4f8d36aa31b", ) - api_response = await api_client.read( + api_response = {{#asyncio}}await {{/asyncio}}api_client.read( body=body, options={} ) @@ -714,7 +714,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_write(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_write(self, mock_request): """Test case for write Add tuples from the store with transaction enabled @@ -723,7 +723,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: body = ClientWriteRequest( writes= @@ -745,7 +745,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) ], ) - await api_client.write( + {{#asyncio}}await {{/asyncio}}api_client.write( body, options={"authorization_model_id": "01G5JAVJ41T49E9TT3SKVS7X1J"} ) @@ -761,7 +761,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_delete(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_delete(self, mock_request): """Test case for delete Delete tuples from the store with transaction enabled @@ -770,7 +770,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: body = ClientWriteRequest( deletes= @@ -782,7 +782,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) ], ) - await api_client.write( + {{#asyncio}}await {{/asyncio}}api_client.write( body, options={"authorization_model_id": "01G5JAVJ41T49E9TT3SKVS7X1J"} ) @@ -798,7 +798,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_write_batch(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_write_batch(self, mock_request): """Test case for write Add tuples from the store with transaction disabled @@ -811,7 +811,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ] configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: body = ClientWriteRequest( writes= @@ -834,7 +834,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ], ) transaction = WriteTransactionOpts(disabled=True, max_per_chunk=1, max_parallel_requests=10) - response = await api_client.write( + response = {{#asyncio}}await {{/asyncio}}api_client.write( body, options={"authorization_model_id": "01G5JAVJ41T49E9TT3SKVS7X1J", "transaction": transaction} ) @@ -909,7 +909,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_write_batch_min_parallel(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_write_batch_min_parallel(self, mock_request): """Test case for write Add tuples from the store with transaction disabled and minimum parallel request @@ -922,7 +922,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ] configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: body = ClientWriteRequest( writes= @@ -945,7 +945,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ], ) transaction = WriteTransactionOpts(disabled=True, max_per_chunk=1, max_parallel_requests=1) - response = await api_client.write( + response = {{#asyncio}}await {{/asyncio}}api_client.write( body, options={"authorization_model_id": "01G5JAVJ41T49E9TT3SKVS7X1J", "transaction": transaction} ) @@ -1021,7 +1021,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): @patch.object(rest.RESTClientObject, 'request') - async def test_write_batch_larger_chunk(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_write_batch_larger_chunk(self, mock_request): """Test case for write Add tuples from the store with transaction disabled and minimum parallel request @@ -1033,7 +1033,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ] configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: body = ClientWriteRequest( writes= @@ -1056,7 +1056,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ], ) transaction = WriteTransactionOpts(disabled=True, max_per_chunk=2, max_parallel_requests=2) - response = await api_client.write( + response = {{#asyncio}}await {{/asyncio}}api_client.write( body, options={"authorization_model_id": "01G5JAVJ41T49E9TT3SKVS7X1J", "transaction": transaction} ) @@ -1121,7 +1121,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_write_batch_failed(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_write_batch_failed(self, mock_request): """Test case for write Add tuples from the store with transaction disabled where one of the request failed @@ -1141,7 +1141,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ] configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: body = ClientWriteRequest( writes= @@ -1164,7 +1164,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ], ) transaction = WriteTransactionOpts(disabled=True, max_per_chunk=1, max_parallel_requests=10) - response = await api_client.write( + response = {{#asyncio}}await {{/asyncio}}api_client.write( body, options={"authorization_model_id": "01G5JAVJ41T49E9TT3SKVS7X1J", "transaction": transaction} ) @@ -1239,7 +1239,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_delete_batch(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_delete_batch(self, mock_request): """Test case for delete Delete tuples from the store with transaction disabled but there is only 1 relationship tuple @@ -1250,7 +1250,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ] configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: body = ClientWriteRequest( deletes= @@ -1263,7 +1263,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ], ) transaction = WriteTransactionOpts(disabled=True, max_per_chunk=1, max_parallel_requests=10) - await api_client.write( + {{#asyncio}}await {{/asyncio}}api_client.write( body, options={"authorization_model_id": "01G5JAVJ41T49E9TT3SKVS7X1J", "transaction": transaction} ) @@ -1287,7 +1287,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_write_tuples(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_write_tuples(self, mock_request): """Test case for write tuples Add tuples from the store with transaction enabled @@ -1296,9 +1296,9 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: - await api_client.write_tuples( + {{#asyncio}}await {{/asyncio}}api_client.write_tuples( [ ClientTuple( object="document:2021-budget", @@ -1330,7 +1330,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_delete_tuples(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_delete_tuples(self, mock_request): """Test case for delete tuples Add tuples from the store with transaction enabled @@ -1339,9 +1339,9 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: - await api_client.delete_tuples( + {{#asyncio}}await {{/asyncio}}api_client.delete_tuples( [ ClientTuple( object="document:2021-budget", @@ -1373,7 +1373,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_write_batch_unauthorized(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_write_batch_unauthorized(self, mock_request): """Test case for write with 401 response """ @@ -1382,7 +1382,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: with self.assertRaises(UnauthorizedException) as api_exception: body = ClientWriteRequest( writes=[ @@ -1395,7 +1395,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) transaction = WriteTransactionOpts( disabled=True, max_per_chunk=1, max_parallel_requests=10) - await api_client.write( + {{#asyncio}}await {{/asyncio}}api_client.write( body, options={"authorization_model_id": "01G5JAVJ41T49E9TT3SKVS7X1J", "transaction": transaction} @@ -1413,10 +1413,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_check(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_check(self, mock_request): """Test case for check Check whether a user is authorized to access an object # noqa: E501 @@ -1439,8 +1439,8 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: - api_response = await api_client.check( + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: + api_response = {{#asyncio}}await {{/asyncio}}api_client.check( body=body, options={"authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"} ) @@ -1459,10 +1459,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_check_config_auth_model(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_check_config_auth_model(self, mock_request): """Test case for check Check whether a user is authorized to access an object and the auth model is already encoded in store # noqa: E501 @@ -1479,8 +1479,8 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id configuration.authorization_model_id = "01GXSA8YR785C4FYS3C0RTG7B1" - async with OpenFgaClient(configuration) as api_client: - api_response = await api_client.check( + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: + api_response = {{#asyncio}}await {{/asyncio}}api_client.check( body=body, options={} ) @@ -1498,10 +1498,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_batch_check_single_request(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_batch_check_single_request(self, mock_request): """Test case for check with single request Check whether a user is authorized to access an object # noqa: E501 @@ -1520,8 +1520,8 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: - api_response = await api_client.batch_check( + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: + api_response = {{#asyncio}}await {{/asyncio}}api_client.batch_check( body=[body], options={"authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"} ) @@ -1550,10 +1550,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_batch_check_multiple_request(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_batch_check_multiple_request(self, mock_request): """Test case for check with multiple request Check whether a user is authorized to access an object # noqa: E501 @@ -1583,8 +1583,8 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: - api_response = await api_client.batch_check( + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: + api_response = {{#asyncio}}await {{/asyncio}}api_client.batch_check( body=[body1, body2, body3], options={"authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1", "max_parallel_requests": 2} ) @@ -1641,11 +1641,11 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_batch_check_multiple_request_fail(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_batch_check_multiple_request_fail(self, mock_request): """Test case for check with multiple request with one request failed Check whether a user is authorized to access an object # noqa: E501 @@ -1681,8 +1681,8 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: - api_response = await api_client.batch_check( + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: + api_response = {{#asyncio}}await {{/asyncio}}api_client.batch_check( body=[body1, body2, body3], options={"authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1", "max_parallel_requests": 2} ) @@ -1740,11 +1740,11 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_expand(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_expand(self, mock_request): """Test case for expand Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship # noqa: E501 @@ -1755,12 +1755,12 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: body = ClientExpandRequest( object="document:budget", relation="reader", ) - api_response = await api_client.expand( + api_response = {{#asyncio}}await {{/asyncio}}api_client.expand( body=body, options={"authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"} ) @@ -1782,10 +1782,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_list_objects(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_list_objects(self, mock_request): """Test case for list_objects List objects # noqa: E501 @@ -1800,14 +1800,14 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: body = ClientListObjectsRequest( type="document", relation="reader", user="user:81684243-9356-4421-8fbf-a4f8d36aa31b", ) # Get all stores - api_response = await api_client.list_objects(body, options={"authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"}) + api_response = {{#asyncio}}await {{/asyncio}}api_client.list_objects(body, options={"authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"}) self.assertIsInstance(api_response, ListObjectsResponse) self.assertEqual(api_response.objects, ['document:abcd1234']) mock_request.assert_called_once_with( @@ -1821,11 +1821,11 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_list_objects_contextual_tuples(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_list_objects_contextual_tuples(self, mock_request): """Test case for list_objects List objects # noqa: E501 @@ -1840,7 +1840,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): mock_request.return_value = mock_response(response_body, 200) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: body = ClientListObjectsRequest( type="document", relation="reader", @@ -1854,7 +1854,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ], ) # Get all stores - api_response = await api_client.list_objects(body, options={"authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"}) + api_response = {{#asyncio}}await {{/asyncio}}api_client.list_objects(body, options={"authorization_model_id": "01GXSA8YR785C4FYS3C0RTG7B1"}) self.assertIsInstance(api_response, ListObjectsResponse) self.assertEqual(api_response.objects, ['document:abcd1234']) mock_request.assert_called_once_with( @@ -1869,10 +1869,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_list_relations(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_list_relations(self, mock_request): """Test case for list relations Check whether a user is authorized to access an object # noqa: E501 @@ -1887,8 +1887,8 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ] configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: - api_response = await api_client.list_relations( + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: + api_response = {{#asyncio}}await {{/asyncio}}api_client.list_relations( body=ClientListRelationsRequest(user="user:81684243-9356-4421-8fbf-a4f8d36aa31b", relations=["reader", "owner", "viewer"], object="document:2021-budget"), @@ -1938,10 +1938,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_list_relations_unauthorized(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_list_relations_unauthorized(self, mock_request): """Test case for list relations with 401 response """ @@ -1950,9 +1950,9 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: with self.assertRaises(UnauthorizedException) as api_exception: - await api_client.list_relations( + {{#asyncio}}await {{/asyncio}}api_client.list_relations( body=ClientListRelationsRequest(user="user:81684243-9356-4421-8fbf-a4f8d36aa31b", relations=["reader", "owner", "viewer"], object="document:2021-budget"), @@ -1971,10 +1971,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): _preload_content=ANY, _request_timeout=None ) - await api_client.close() + {{#asyncio}}await {{/asyncio}}api_client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_read_assertions(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_read_assertions(self, mock_request): """Test case for read assertions """ @@ -1997,8 +1997,8 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id # Enter a context with an instance of the API client - async with OpenFgaClient(configuration) as api_client: - api_response = await api_client.read_assertions( + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: + api_response = {{#asyncio}}await {{/asyncio}}api_client.read_assertions( options={"authorization_model_id":"01G5JAVJ41T49E9TT3SKVS7X1J"} ) self.assertEqual(api_response, ReadAssertionsResponse( @@ -2019,7 +2019,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_write_assertions(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_write_assertions(self, mock_request): """Test case for write assertions Get all stores # noqa: E501 @@ -2027,8 +2027,8 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): mock_request.return_value = mock_response('', 204) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: - await api_client.write_assertions( + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: + {{#asyncio}}await {{/asyncio}}api_client.write_assertions( [ClientAssertion(user="user:anne", relation="reader", object="document:2021-budget", expectation=True)], options={"authorization_model_id":"01G5JAVJ41T49E9TT3SKVS7X1J"} ) @@ -2044,7 +2044,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): ) @patch.object(rest.RESTClientObject, 'request') - async def test_set_store_id(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_set_store_id(self, mock_request): """Test case for write assertions Get all stores # noqa: E501 @@ -2052,10 +2052,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): mock_request.return_value = mock_response('', 204) configuration = self.configuration configuration.store_id = store_id - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: api_client.set_store_id("01YCP46JKYM8FJCQ37NMBYHE5Y") - await api_client.write_assertions( + {{#asyncio}}await {{/asyncio}}api_client.write_assertions( [ClientAssertion(user="user:anne", relation="reader", object="document:2021-budget", expectation=True)], options={"authorization_model_id": "01G5JAVJ41T49E9TT3SKVS7X1J"} @@ -2074,7 +2074,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): @patch.object(rest.RESTClientObject, 'request') - async def test_config_auth_model(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_config_auth_model(self, mock_request): """Test case for write assertions Get all stores # noqa: E501 @@ -2083,8 +2083,8 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id configuration.authorization_model_id = "01G5JAVJ41T49E9TT3SKVS7X1J" - async with OpenFgaClient(configuration) as api_client: - await api_client.write_assertions( + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: + {{#asyncio}}await {{/asyncio}}api_client.write_assertions( [ClientAssertion(user="user:anne", relation="reader", object="document:2021-budget", expectation=True)], options={} @@ -2103,7 +2103,7 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): @patch.object(rest.RESTClientObject, 'request') - async def test_update_auth_model(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_update_auth_model(self, mock_request): """Test case for write assertions Get all stores # noqa: E501 @@ -2112,10 +2112,10 @@ class TestOpenFgaClient(IsolatedAsyncioTestCase): configuration = self.configuration configuration.store_id = store_id configuration.authorization_model_id = "01G5JAVJ41T49E9TT3SKVS7X1J" - async with OpenFgaClient(configuration) as api_client: + {{#asyncio}}async {{/asyncio}}with OpenFgaClient(configuration) as api_client: api_client.set_authorization_model_id("01G5JAVJ41T49E9TT3SKVS7X2J") - await api_client.write_assertions( + {{#asyncio}}await {{/asyncio}}api_client.write_assertions( [ClientAssertion(user="user:anne", relation="reader", object="document:2021-budget", expectation=True)], options={} diff --git a/config/clients/python/template/credentials.mustache b/config/clients/python/template/credentials.mustache index 9e73f536..3c93a0e4 100644 --- a/config/clients/python/template/credentials.mustache +++ b/config/clients/python/template/credentials.mustache @@ -188,7 +188,7 @@ class Credentials: return False return True - async def _obtain_token(self, client): + {{#asyncio}}async {{/asyncio}}def _obtain_token(self, client): """ Perform OAuth2 and obtain token """ @@ -200,7 +200,7 @@ class Credentials: 'grant_type': "client_credentials", } headers = urllib3.response.HTTPHeaderDict({'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'openfga-sdk (python) {{packageVersion}}'}) - raw_response = await client.POST(token_url, headers=headers, body=body); + raw_response = {{#asyncio}}await {{/asyncio}}client.POST(token_url, headers=headers, body=body); if 200 <= raw_response.status <= 299: try: api_response = json.loads(raw_response.data) @@ -213,7 +213,7 @@ class Credentials: else: raise AuthenticationError(http_resp=raw_response) - async def get_authentication_header(self, client): + {{#asyncio}}async {{/asyncio}}def get_authentication_header(self, client): """ If configured, return the header for authentication """ @@ -224,6 +224,6 @@ class Credentials: # check to see token is valid if not self._token_valid(): # In this case, the token is not valid, we need to get the refresh the token - await self._obtain_token(client) + {{#asyncio}}await {{/asyncio}}self._obtain_token(client) return {'Authorization': 'Bearer {}'.format(self._access_token)} diff --git a/config/clients/python/template/credentials_test.mustache b/config/clients/python/template/credentials_test.mustache index e635aff8..fa688a92 100644 --- a/config/clients/python/template/credentials_test.mustache +++ b/config/clients/python/template/credentials_test.mustache @@ -7,7 +7,7 @@ from unittest import IsolatedAsyncioTestCase from mock import patch from datetime import datetime, timedelta -import {{packageName}} +import {{packageName}}{{^asyncio}} as openfga_sdk{{/asyncio}} import urllib3 from {{packageName}} import rest @@ -154,23 +154,23 @@ class TestCredentials(IsolatedAsyncioTestCase): with self.assertRaises(openfga_sdk.ApiValueError): credential.validate_credentials_config() - async def test_get_authentication_header(self): + {{#asyncio}}async {{/asyncio}}def test_get_authentication_header(self): """ Test getting authentication header when method is none """ credential = Credentials() - auth_header = await credential.get_authentication_header(None) + auth_header = {{#asyncio}}await {{/asyncio}}credential.get_authentication_header(None) self.assertEqual(auth_header, {}) - async def test_get_authentication_api_token(self): + {{#asyncio}}async {{/asyncio}}def test_get_authentication_api_token(self): """ Test getting authentication header when method is api token """ credential = Credentials(method="api_token", configuration=CredentialConfiguration(api_token='ABCDEFG')) - auth_header = await credential.get_authentication_header(None) + auth_header = {{#asyncio}}await {{/asyncio}}credential.get_authentication_header(None) self.assertEqual(auth_header, {'Authorization': 'Bearer ABCDEFG'}) - async def test_get_authentication_valid_client_credentials(self): + {{#asyncio}}async {{/asyncio}}def test_get_authentication_valid_client_credentials(self): """ Test getting authentication header when method is client credentials """ @@ -179,11 +179,11 @@ class TestCredentials(IsolatedAsyncioTestCase): client_secret='mysecret', api_issuer='www.testme.com', api_audience='myaudience')) credential._access_token = 'XYZ123' credential._access_expiry_time = datetime.now() + timedelta(seconds=60) - auth_header = await credential.get_authentication_header(None) + auth_header = {{#asyncio}}await {{/asyncio}}credential.get_authentication_header(None) self.assertEqual(auth_header, {'Authorization': 'Bearer XYZ123'}) @patch.object(rest.RESTClientObject, 'request') - async def test_get_authentication_obtain_client_credentials(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_get_authentication_obtain_client_credentials(self, mock_request): """ Test getting authentication header when method is client credential and we need to obtain token """ @@ -200,7 +200,7 @@ class TestCredentials(IsolatedAsyncioTestCase): client_secret='mysecret', api_issuer='www.testme.com', api_audience='myaudience')) client = rest.RESTClientObject(Configuration()) current_time = datetime.now() - auth_header = await credential.get_authentication_header(client) + auth_header = {{#asyncio}}await {{/asyncio}}credential.get_authentication_header(client) self.assertEqual(auth_header, {'Authorization': 'Bearer AABBCCDD'}) self.assertEqual(credential._access_token, 'AABBCCDD') self.assertGreaterEqual(credential._access_expiry_time, current_time + timedelta(seconds=int(120))) @@ -212,10 +212,10 @@ class TestCredentials(IsolatedAsyncioTestCase): query_params=None, post_params=None, _preload_content=True, _request_timeout=None, body={"client_id": "myclientid", "client_secret": "mysecret", "audience": "myaudience", "grant_type": "client_credentials"} ) - await client.close() + {{#asyncio}}await {{/asyncio}}client.close() @patch.object(rest.RESTClientObject, 'request') - async def test_get_authentication_obtain_client_credentials_failed(self, mock_request): + {{#asyncio}}async {{/asyncio}}def test_get_authentication_obtain_client_credentials_failed(self, mock_request): """ Test getting authentication header when method is client credential and we fail to obtain token """ @@ -231,6 +231,6 @@ class TestCredentials(IsolatedAsyncioTestCase): client_secret='mysecret', api_issuer='www.testme.com', api_audience='myaudience')) client = rest.RESTClientObject(Configuration()) with self.assertRaises(AuthenticationError): - await credential.get_authentication_header(client) - await client.close() + {{#asyncio}}await {{/asyncio}}credential.get_authentication_header(client) + {{#asyncio}}await {{/asyncio}}client.close() diff --git a/config/clients/python/template/model_test.mustache b/config/clients/python/template/model_test.mustache index f5f4b415..4e669592 100644 --- a/config/clients/python/template/model_test.mustache +++ b/config/clients/python/template/model_test.mustache @@ -7,7 +7,7 @@ import datetime {{#models}} {{#model}} -import {{packageName}} +import {{packageName}}{{^asyncio}} as openfga_sdk{{/asyncio}} from {{modelPackage}}.{{classFilename}} import {{classname}} # noqa: E501 from {{packageName}}.rest import ApiException diff --git a/config/clients/python/template/rest.mustache b/config/clients/python/template/rest.mustache index 28332e13..980b3b95 100644 --- a/config/clients/python/template/rest.mustache +++ b/config/clients/python/template/rest.mustache @@ -13,7 +13,7 @@ import six from six.moves.urllib.parse import urlencode import urllib3 -from {{packageName}}.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError +from {{packageName}}.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError, ValidationException logger = logging.getLogger(__name__) @@ -21,15 +21,15 @@ logger = logging.getLogger(__name__) class RESTResponse(io.IOBase): - def __init__(self, resp): + def __init__(self, resp, data): self.urllib3_response = resp self.status = resp.status self.reason = resp.reason - self.data = resp.data + self.data = data def getheaders(self): """Returns a dictionary of the response headers.""" - return self.urllib3_response.getheaders() + return self.urllib3_response.headers def getheader(self, name, default=None): """Returns a given response header.""" @@ -91,6 +91,9 @@ class RESTClientObject(object): **addition_pool_args ) + def close(self): + self.pool_manager.clear() + def request(self, method, url, query_params=None, headers=None, body=None, post_params=None, _preload_content=True, _request_timeout=None): diff --git a/scripts/build_client.sh b/scripts/build_client.sh index a05beecf..34a9ef9f 100755 --- a/scripts/build_client.sh +++ b/scripts/build_client.sh @@ -38,6 +38,9 @@ cp "${CONFIG_DIR}/clients/${SDK_LANGUAGE}/.openapi-generator-ignore" "${CLIENTS_ library=() [[ -n "$LIBRARY_TEMPLATE" ]] && library=(--library "$LIBRARY_TEMPLATE") +package_name=() +[[ -n "$PACKAGE_NAME" ]] && package_name=(--package-name "$PACKAGE_NAME") + # Generate the SDK docker run --rm \ -u "${CURRENT_UID}:${CURRENT_GID}" \ @@ -49,6 +52,7 @@ docker run --rm \ -i /docs/openapi/openfga.openapiv2.json \ --http-user-agent="$http_user_agent" \ "${library[@]}" \ + "${package_name[@]}" \ -o "/clients/fga-${SDK_LANGUAGE}-sdk" \ -c /config/config.json \ -g "$(cat ./config/clients/"${SDK_LANGUAGE}"/generator.txt)"