From 8252ddacaa835c741990609294c5bd0da88eccc8 Mon Sep 17 00:00:00 2001 From: speakeasybot Date: Wed, 7 Aug 2024 00:25:12 +0000 Subject: [PATCH] ci: regenerated with OpenAPI Doc 1.0.0, Speakeasy CLI 1.355.0 --- template_variables/.gitattributes | 2 + template_variables/.gitignore | 8 + template_variables/.speakeasy/gen.lock | 107 ++ template_variables/.vscode/settings.json | 6 + template_variables/CONTRIBUTING.md | 26 + template_variables/README.md | 1282 ++++++++++++++++- template_variables/RELEASES.md | 10 +- template_variables/USAGE.md | 245 +++- .../docs/models/categoryresult.md | 9 + template_variables/docs/models/config.md | 9 + template_variables/docs/models/contextdata.md | 9 + .../docs/models/customvariable.md | 19 + .../models/deletecustomvariablerequest.md | 8 + .../docs/models/externalcustomvariable.md | 9 + .../docs/models/getcategoriesrequest.md | 8 + .../docs/models/getcustomvariablerequest.md | 8 + .../models/getvariablecontextrequestbody.md | 8 + .../models/replacetemplatesrequestbody.md | 9 + .../models/replacetemplatesresponsebody.md | 10 + .../docs/models/searchvariablesrequestbody.md | 13 + template_variables/docs/models/security.md | 9 + .../docs/models/templatetype.md | 9 + template_variables/docs/models/type.md | 11 + .../models/updatecustomvariablerequest.md | 9 + .../docs/models/utils/retryconfig.md | 24 + .../docs/models/variablecontext.md | 11 + .../docs/models/variableparameters.md | 18 + .../docs/models/variableresult.md | 12 + .../docs/models/variableresulttype.md | 9 + .../docs/sdks/customvariables/README.md | 488 +++++++ template_variables/docs/sdks/epilot/README.md | 9 + .../docs/sdks/variables/README.md | 229 +++ template_variables/gen.yaml | 43 +- template_variables/poetry.toml | 2 + template_variables/py.typed | 1 + template_variables/pylintrc | 68 +- template_variables/pyproject.toml | 55 + template_variables/scripts/compile.sh | 83 ++ template_variables/scripts/publish.sh | 5 + template_variables/setup.py | 39 - template_variables/src/epilot/__init__.py | 3 - .../src/epilot/custom_variables.py | 170 --- .../src/epilot/models/__init__.py | 2 - .../src/epilot/models/operations/__init__.py | 15 - .../models/operations/createcustomvariable.py | 15 - .../models/operations/deletecustomvariable.py | 22 - .../models/operations/generateqrcode.py | 22 - .../operations/getblueprinttableconfig.py | 18 - .../epilot/models/operations/getcategories.py | 31 - .../models/operations/getcustomvariable.py | 25 - .../models/operations/getcustomvariables.py | 18 - .../models/operations/getvariablecontext.py | 28 - .../models/operations/replacetemplates.py | 36 - .../models/operations/searchvariables.py | 39 - .../models/operations/updatecustomvariable.py | 24 - .../src/epilot/models/shared/__init__.py | 12 - .../epilot/models/shared/categoryresult.py | 16 - .../epilot/models/shared/customvariable.py | 45 - .../models/shared/externalcustomvariable.py | 16 - .../src/epilot/models/shared/security.py | 11 - .../epilot/models/shared/templatetype_enum.py | 8 - .../epilot/models/shared/variablecontext.py | 19 - .../models/shared/variableparameters.py | 37 - .../epilot/models/shared/variableresult.py | 28 - template_variables/src/epilot/sdk.py | 80 - .../src/epilot/utils/__init__.py | 4 - .../src/epilot/utils/retries.py | 118 -- template_variables/src/epilot/utils/utils.py | 735 ---------- template_variables/src/epilot/variables.py | 158 -- .../src/epilot_template_variables/__init__.py | 5 + .../_hooks/__init__.py | 5 + .../_hooks/registration.py | 13 + .../_hooks/sdkhooks.py | 57 + .../epilot_template_variables/_hooks/types.py | 76 + .../src/epilot_template_variables/basesdk.py | 253 ++++ .../custom_variables.py | 880 +++++++++++ .../epilot_template_variables/httpclient.py | 78 + .../models/__init__.py | 20 + .../models/categoryresult.py | 17 + .../models/customvariable.py | 77 + .../models/deletecustomvariableop.py | 18 + .../models/externalcustomvariable.py | 17 + .../models/getcategoriesop.py | 16 + .../models/getcustomvariableop.py | 18 + .../models/getvariablecontextop.py | 16 + .../models/replacetemplatesop.py | 30 + .../models/sdkerror.py | 22 + .../models/searchvariablesop.py | 31 + .../models/security.py | 18 + .../models/templatetype.py | 9 + .../models/updatecustomvariableop.py | 21 + .../models/variablecontext.py | 21 + .../models/variableparameters.py | 94 ++ .../models/variableresult.py | 36 + .../src/epilot_template_variables/py.typed | 1 + .../src/epilot_template_variables/sdk.py | 93 ++ .../sdkconfiguration.py | 48 + .../types/__init__.py | 21 + .../types/basemodel.py | 39 + .../utils/__init__.py | 84 ++ .../utils/annotations.py | 19 + .../epilot_template_variables/utils/enums.py | 34 + .../utils/eventstreaming.py | 178 +++ .../epilot_template_variables/utils/forms.py | 207 +++ .../utils/headers.py | 136 ++ .../epilot_template_variables/utils/logger.py | 16 + .../utils/metadata.py | 118 ++ .../utils/queryparams.py | 203 +++ .../utils/requestbodies.py | 66 + .../utils/retries.py | 216 +++ .../utils/security.py | 168 +++ .../utils/serializers.py | 181 +++ .../epilot_template_variables/utils/url.py | 150 ++ .../epilot_template_variables/utils/values.py | 128 ++ .../epilot_template_variables/variables.py | 621 ++++++++ 115 files changed, 7312 insertions(+), 1957 deletions(-) create mode 100644 template_variables/.gitattributes create mode 100644 template_variables/.gitignore create mode 100644 template_variables/.speakeasy/gen.lock create mode 100644 template_variables/.vscode/settings.json create mode 100644 template_variables/CONTRIBUTING.md mode change 100755 => 100644 template_variables/USAGE.md create mode 100644 template_variables/docs/models/categoryresult.md create mode 100644 template_variables/docs/models/config.md create mode 100644 template_variables/docs/models/contextdata.md create mode 100644 template_variables/docs/models/customvariable.md create mode 100644 template_variables/docs/models/deletecustomvariablerequest.md create mode 100644 template_variables/docs/models/externalcustomvariable.md create mode 100644 template_variables/docs/models/getcategoriesrequest.md create mode 100644 template_variables/docs/models/getcustomvariablerequest.md create mode 100644 template_variables/docs/models/getvariablecontextrequestbody.md create mode 100644 template_variables/docs/models/replacetemplatesrequestbody.md create mode 100644 template_variables/docs/models/replacetemplatesresponsebody.md create mode 100644 template_variables/docs/models/searchvariablesrequestbody.md create mode 100644 template_variables/docs/models/security.md create mode 100644 template_variables/docs/models/templatetype.md create mode 100644 template_variables/docs/models/type.md create mode 100644 template_variables/docs/models/updatecustomvariablerequest.md create mode 100644 template_variables/docs/models/utils/retryconfig.md create mode 100644 template_variables/docs/models/variablecontext.md create mode 100644 template_variables/docs/models/variableparameters.md create mode 100644 template_variables/docs/models/variableresult.md create mode 100644 template_variables/docs/models/variableresulttype.md create mode 100644 template_variables/docs/sdks/customvariables/README.md create mode 100644 template_variables/docs/sdks/epilot/README.md create mode 100644 template_variables/docs/sdks/variables/README.md create mode 100644 template_variables/poetry.toml create mode 100644 template_variables/py.typed mode change 100755 => 100644 template_variables/pylintrc create mode 100644 template_variables/pyproject.toml create mode 100755 template_variables/scripts/compile.sh create mode 100755 template_variables/scripts/publish.sh delete mode 100755 template_variables/setup.py delete mode 100755 template_variables/src/epilot/__init__.py delete mode 100755 template_variables/src/epilot/custom_variables.py delete mode 100755 template_variables/src/epilot/models/__init__.py delete mode 100755 template_variables/src/epilot/models/operations/__init__.py delete mode 100755 template_variables/src/epilot/models/operations/createcustomvariable.py delete mode 100755 template_variables/src/epilot/models/operations/deletecustomvariable.py delete mode 100755 template_variables/src/epilot/models/operations/generateqrcode.py delete mode 100755 template_variables/src/epilot/models/operations/getblueprinttableconfig.py delete mode 100755 template_variables/src/epilot/models/operations/getcategories.py delete mode 100755 template_variables/src/epilot/models/operations/getcustomvariable.py delete mode 100755 template_variables/src/epilot/models/operations/getcustomvariables.py delete mode 100755 template_variables/src/epilot/models/operations/getvariablecontext.py delete mode 100755 template_variables/src/epilot/models/operations/replacetemplates.py delete mode 100755 template_variables/src/epilot/models/operations/searchvariables.py delete mode 100755 template_variables/src/epilot/models/operations/updatecustomvariable.py delete mode 100755 template_variables/src/epilot/models/shared/__init__.py delete mode 100755 template_variables/src/epilot/models/shared/categoryresult.py delete mode 100755 template_variables/src/epilot/models/shared/customvariable.py delete mode 100755 template_variables/src/epilot/models/shared/externalcustomvariable.py delete mode 100755 template_variables/src/epilot/models/shared/security.py delete mode 100755 template_variables/src/epilot/models/shared/templatetype_enum.py delete mode 100755 template_variables/src/epilot/models/shared/variablecontext.py delete mode 100755 template_variables/src/epilot/models/shared/variableparameters.py delete mode 100755 template_variables/src/epilot/models/shared/variableresult.py delete mode 100755 template_variables/src/epilot/sdk.py delete mode 100755 template_variables/src/epilot/utils/__init__.py delete mode 100755 template_variables/src/epilot/utils/retries.py delete mode 100755 template_variables/src/epilot/utils/utils.py delete mode 100755 template_variables/src/epilot/variables.py create mode 100644 template_variables/src/epilot_template_variables/__init__.py create mode 100644 template_variables/src/epilot_template_variables/_hooks/__init__.py create mode 100644 template_variables/src/epilot_template_variables/_hooks/registration.py create mode 100644 template_variables/src/epilot_template_variables/_hooks/sdkhooks.py create mode 100644 template_variables/src/epilot_template_variables/_hooks/types.py create mode 100644 template_variables/src/epilot_template_variables/basesdk.py create mode 100644 template_variables/src/epilot_template_variables/custom_variables.py create mode 100644 template_variables/src/epilot_template_variables/httpclient.py create mode 100644 template_variables/src/epilot_template_variables/models/__init__.py create mode 100644 template_variables/src/epilot_template_variables/models/categoryresult.py create mode 100644 template_variables/src/epilot_template_variables/models/customvariable.py create mode 100644 template_variables/src/epilot_template_variables/models/deletecustomvariableop.py create mode 100644 template_variables/src/epilot_template_variables/models/externalcustomvariable.py create mode 100644 template_variables/src/epilot_template_variables/models/getcategoriesop.py create mode 100644 template_variables/src/epilot_template_variables/models/getcustomvariableop.py create mode 100644 template_variables/src/epilot_template_variables/models/getvariablecontextop.py create mode 100644 template_variables/src/epilot_template_variables/models/replacetemplatesop.py create mode 100644 template_variables/src/epilot_template_variables/models/sdkerror.py create mode 100644 template_variables/src/epilot_template_variables/models/searchvariablesop.py create mode 100644 template_variables/src/epilot_template_variables/models/security.py create mode 100644 template_variables/src/epilot_template_variables/models/templatetype.py create mode 100644 template_variables/src/epilot_template_variables/models/updatecustomvariableop.py create mode 100644 template_variables/src/epilot_template_variables/models/variablecontext.py create mode 100644 template_variables/src/epilot_template_variables/models/variableparameters.py create mode 100644 template_variables/src/epilot_template_variables/models/variableresult.py create mode 100644 template_variables/src/epilot_template_variables/py.typed create mode 100644 template_variables/src/epilot_template_variables/sdk.py create mode 100644 template_variables/src/epilot_template_variables/sdkconfiguration.py create mode 100644 template_variables/src/epilot_template_variables/types/__init__.py create mode 100644 template_variables/src/epilot_template_variables/types/basemodel.py create mode 100644 template_variables/src/epilot_template_variables/utils/__init__.py create mode 100644 template_variables/src/epilot_template_variables/utils/annotations.py create mode 100644 template_variables/src/epilot_template_variables/utils/enums.py create mode 100644 template_variables/src/epilot_template_variables/utils/eventstreaming.py create mode 100644 template_variables/src/epilot_template_variables/utils/forms.py create mode 100644 template_variables/src/epilot_template_variables/utils/headers.py create mode 100644 template_variables/src/epilot_template_variables/utils/logger.py create mode 100644 template_variables/src/epilot_template_variables/utils/metadata.py create mode 100644 template_variables/src/epilot_template_variables/utils/queryparams.py create mode 100644 template_variables/src/epilot_template_variables/utils/requestbodies.py create mode 100644 template_variables/src/epilot_template_variables/utils/retries.py create mode 100644 template_variables/src/epilot_template_variables/utils/security.py create mode 100644 template_variables/src/epilot_template_variables/utils/serializers.py create mode 100644 template_variables/src/epilot_template_variables/utils/url.py create mode 100644 template_variables/src/epilot_template_variables/utils/values.py create mode 100644 template_variables/src/epilot_template_variables/variables.py diff --git a/template_variables/.gitattributes b/template_variables/.gitattributes new file mode 100644 index 0000000000..4d75d59008 --- /dev/null +++ b/template_variables/.gitattributes @@ -0,0 +1,2 @@ +# This allows generated code to be indexed correctly +*.py linguist-generated=false \ No newline at end of file diff --git a/template_variables/.gitignore b/template_variables/.gitignore new file mode 100644 index 0000000000..477b772901 --- /dev/null +++ b/template_variables/.gitignore @@ -0,0 +1,8 @@ +.venv/ +venv/ +src/*.egg-info/ +__pycache__/ +.pytest_cache/ +.python-version +.DS_Store +pyrightconfig.json diff --git a/template_variables/.speakeasy/gen.lock b/template_variables/.speakeasy/gen.lock new file mode 100644 index 0000000000..58df5c3f7a --- /dev/null +++ b/template_variables/.speakeasy/gen.lock @@ -0,0 +1,107 @@ +lockVersion: 2.0.0 +id: aacc3d90-0959-4cd3-965e-514f5cc6b017 +management: + docChecksum: 9efe370082758b9cf2fd0a2bcf412e38 + docVersion: 1.0.0 + speakeasyVersion: 1.355.0 + generationVersion: 2.387.0 + releaseVersion: 1.3.0 + configChecksum: 0cff971353aeba857ecb67cfac173cd3 + repoURL: https://github.com/epilot-dev/sdk-python.git + repoSubDirectory: template_variables + installationURL: https://github.com/epilot-dev/sdk-python.git#subdirectory=template_variables +features: + python: + additionalDependencies: 1.0.0 + constsAndDefaults: 1.0.2 + core: 5.3.4 + defaultEnabledRetries: 0.2.0 + envVarSecurityUsage: 0.3.1 + flattening: 3.0.0 + globalSecurity: 3.0.1 + globalSecurityCallbacks: 1.0.0 + globalServerURLs: 3.0.0 + nullables: 1.0.0 + responseFormat: 1.0.0 + retries: 3.0.0 + sdkHooks: 1.0.0 +generatedFiles: + - src/epilot_template_variables/sdkconfiguration.py + - src/epilot_template_variables/custom_variables.py + - src/epilot_template_variables/variables.py + - src/epilot_template_variables/sdk.py + - .vscode/settings.json + - poetry.toml + - py.typed + - pylintrc + - pyproject.toml + - scripts/compile.sh + - scripts/publish.sh + - src/epilot_template_variables/__init__.py + - src/epilot_template_variables/basesdk.py + - src/epilot_template_variables/httpclient.py + - src/epilot_template_variables/py.typed + - src/epilot_template_variables/types/__init__.py + - src/epilot_template_variables/types/basemodel.py + - src/epilot_template_variables/utils/__init__.py + - src/epilot_template_variables/utils/annotations.py + - src/epilot_template_variables/utils/enums.py + - src/epilot_template_variables/utils/eventstreaming.py + - src/epilot_template_variables/utils/forms.py + - src/epilot_template_variables/utils/headers.py + - src/epilot_template_variables/utils/logger.py + - src/epilot_template_variables/utils/metadata.py + - src/epilot_template_variables/utils/queryparams.py + - src/epilot_template_variables/utils/requestbodies.py + - src/epilot_template_variables/utils/retries.py + - src/epilot_template_variables/utils/security.py + - src/epilot_template_variables/utils/serializers.py + - src/epilot_template_variables/utils/url.py + - src/epilot_template_variables/utils/values.py + - src/epilot_template_variables/models/sdkerror.py + - src/epilot_template_variables/models/customvariable.py + - src/epilot_template_variables/models/deletecustomvariableop.py + - src/epilot_template_variables/models/getcustomvariableop.py + - src/epilot_template_variables/models/updatecustomvariableop.py + - src/epilot_template_variables/models/categoryresult.py + - src/epilot_template_variables/models/getcategoriesop.py + - src/epilot_template_variables/models/variablecontext.py + - src/epilot_template_variables/models/getvariablecontextop.py + - src/epilot_template_variables/models/variableparameters.py + - src/epilot_template_variables/models/templatetype.py + - src/epilot_template_variables/models/externalcustomvariable.py + - src/epilot_template_variables/models/replacetemplatesop.py + - src/epilot_template_variables/models/variableresult.py + - src/epilot_template_variables/models/searchvariablesop.py + - src/epilot_template_variables/models/security.py + - src/epilot_template_variables/models/__init__.py + - docs/models/config.md + - docs/models/type.md + - docs/models/customvariable.md + - docs/models/deletecustomvariablerequest.md + - docs/models/getcustomvariablerequest.md + - docs/models/updatecustomvariablerequest.md + - docs/models/categoryresult.md + - docs/models/getcategoriesrequest.md + - docs/models/variablecontext.md + - docs/models/getvariablecontextrequestbody.md + - docs/models/contextdata.md + - docs/models/variableparameters.md + - docs/models/templatetype.md + - docs/models/externalcustomvariable.md + - docs/models/replacetemplatesrequestbody.md + - docs/models/replacetemplatesresponsebody.md + - docs/models/variableresulttype.md + - docs/models/variableresult.md + - docs/models/searchvariablesrequestbody.md + - docs/models/security.md + - docs/sdks/epilot/README.md + - docs/models/utils/retryconfig.md + - docs/sdks/customvariables/README.md + - docs/sdks/variables/README.md + - USAGE.md + - .gitattributes + - src/epilot_template_variables/_hooks/sdkhooks.py + - src/epilot_template_variables/_hooks/types.py + - src/epilot_template_variables/_hooks/__init__.py + - CONTRIBUTING.md diff --git a/template_variables/.vscode/settings.json b/template_variables/.vscode/settings.json new file mode 100644 index 0000000000..8d79f0abb7 --- /dev/null +++ b/template_variables/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "python.testing.pytestArgs": ["tests", "-vv"], + "python.testing.unittestEnabled": false, + "python.testing.pytestEnabled": true, + "pylint.args": ["--rcfile=pylintrc"] +} diff --git a/template_variables/CONTRIBUTING.md b/template_variables/CONTRIBUTING.md new file mode 100644 index 0000000000..d585717fca --- /dev/null +++ b/template_variables/CONTRIBUTING.md @@ -0,0 +1,26 @@ +# Contributing to This Repository + +Thank you for your interest in contributing to this repository. Please note that this repository contains generated code. As such, we do not accept direct changes or pull requests. Instead, we encourage you to follow the guidelines below to report issues and suggest improvements. + +## How to Report Issues + +If you encounter any bugs or have suggestions for improvements, please open an issue on GitHub. When reporting an issue, please provide as much detail as possible to help us reproduce the problem. This includes: + +- A clear and descriptive title +- Steps to reproduce the issue +- Expected and actual behavior +- Any relevant logs, screenshots, or error messages +- Information about your environment (e.g., operating system, software versions) + - For example can be collected using the `npx envinfo` command from your terminal if you have Node.js installed + +## Issue Triage and Upstream Fixes + +We will review and triage issues as quickly as possible. Our goal is to address bugs and incorporate improvements in the upstream source code. Fixes will be included in the next generation of the generated code. + +## Contact + +If you have any questions or need further assistance, please feel free to reach out by opening an issue. + +Thank you for your understanding and cooperation! + +The Maintainers diff --git a/template_variables/README.md b/template_variables/README.md index 39dbd896ef..28f15f5141 100755 --- a/template_variables/README.md +++ b/template_variables/README.md @@ -1,117 +1,430 @@ # epilot-template-variables - + ## SDK Installation +PIP ```bash pip install git+https://github.com/epilot-dev/sdk-python.git#subdirectory=template_variables ``` - +Poetry +```bash +poetry add git+https://github.com/epilot-dev/sdk-python.git#subdirectory=template_variables +``` + + + ## SDK Example Usage - + +### Example + +```python +# Synchronous Example +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +s.custom_variables.create_custom_variable(request={ + "config": {}, + "created_at": "2022-04-19T12:41:43.662Z", + "created_by": "100042", + "helper_logic": "return param1 * param2;", + "helper_params": [ + "param1", + "param2", + ], + "id": "rbse777b-3cf8-4bff-bb0c-253fd1123250", + "key": "my_custom_table", + "name": "My Custom table", + "template": " + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id 'item')}} + + + {{/if}} + {{#if (eq column.id 'quantity')}} + + + {{/if}} + {{#if (eq column.id 'tax')}} + + + {{/if}} + {{#if (eq column.id 'unit_amount')}} + + + {{/if}} + {{#if (eq column.id 'net_total')}} + + + {{/if}} + {{#if (eq column.id 'amount_tax')}} + + + {{/if}} + {{#if (eq column.id 'gross_total')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config 'net_total')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type 'recurring')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+", + "type": epilot_template_variables.Type.CUSTOM, + "updated_at": "2022-04-20T12:41:43.662Z", + "updated_by": "100042", +}) + +# Use the SDK ... +``` + +
+ +The same SDK client can also be used to make asychronous requests by importing asyncio. +```python +# Asynchronous Example +import asyncio +import epilot_template_variables +from epilot_template_variables import Epilot + +async def main(): + s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), + ) + await s.custom_variables.create_custom_variable_async(request={ + "config": {}, + "created_at": "2022-04-19T12:41:43.662Z", + "created_by": "100042", + "helper_logic": "return param1 * param2;", + "helper_params": [ + "param1", + "param2", + ], + "id": "rbse777b-3cf8-4bff-bb0c-253fd1123250", + "key": "my_custom_table", + "name": "My Custom table", + "template": " + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id 'item')}} + + + {{/if}} + {{#if (eq column.id 'quantity')}} + + + {{/if}} + {{#if (eq column.id 'tax')}} + + + {{/if}} + {{#if (eq column.id 'unit_amount')}} + + + {{/if}} + {{#if (eq column.id 'net_total')}} + + + {{/if}} + {{#if (eq column.id 'amount_tax')}} + + + {{/if}} + {{#if (eq column.id 'gross_total')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config 'net_total')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type 'recurring')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+ ", + "type": epilot_template_variables.Type.CUSTOM, + "updated_at": "2022-04-20T12:41:43.662Z", + "updated_by": "100042", + }) + # Use the SDK ... + +asyncio.run(main()) +``` + + + +## Available Resources and Operations + +### [custom_variables](docs/sdks/customvariables/README.md) + +* [create_custom_variable](docs/sdks/customvariables/README.md#create_custom_variable) - Create custom variable +* [delete_custom_variable](docs/sdks/customvariables/README.md#delete_custom_variable) - Delete custom variable +* [get_blue_print_table_config](docs/sdks/customvariables/README.md#get_blue_print_table_config) - Get default table config +* [get_custom_variable](docs/sdks/customvariables/README.md#get_custom_variable) - Get custom variable +* [get_custom_variables](docs/sdks/customvariables/README.md#get_custom_variables) - Get custom variables +* [update_custom_variable](docs/sdks/customvariables/README.md#update_custom_variable) - Update custom variable + +### [variables](docs/sdks/variables/README.md) + +* [get_categories](docs/sdks/variables/README.md#get_categories) - getCategories +* [get_variable_context](docs/sdks/variables/README.md#get_variable_context) - getVariableContext +* [replace_templates](docs/sdks/variables/README.md#replace_templates) - replaceTemplates +* [search_variables](docs/sdks/variables/README.md#search_variables) - searchVariables + + + +## Retries + +Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK. + +To change the default retry strategy for a single API call, simply provide a `RetryConfig` object to the call: ```python -import epilot -from epilot.models import operations, shared +from epilot.utils import BackoffStrategy, RetryConfig +import epilot_template_variables +from epilot_template_variables import Epilot -s = epilot.Epilot( - security=shared.Security( - epilot_auth="Bearer YOUR_BEARER_TOKEN_HERE", +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", ), ) -req = shared.CustomVariable( - config={ - "deserunt": "porro", - "nulla": "id", - "vero": "perspiciatis", - }, - created_at="2022-04-19T12:41:43.662Z", - created_by="100042", - helper_logic="return param1 * param2;", - helper_params=[ - "nihil", - "fuga", - "facilis", - "eum", +s.custom_variables.create_custom_variable(request={ + "config": {}, + "created_at": "2022-04-19T12:41:43.662Z", + "created_by": "100042", + "helper_logic": "return param1 * param2;", + "helper_params": [ + "param1", + "param2", ], - id="rbse777b-3cf8-4bff-bb0c-253fd1123250", - key="my_custom_table", - name="My Custom table", - template=" + "id": "rbse777b-3cf8-4bff-bb0c-253fd1123250", + "key": "my_custom_table", + "name": "My Custom table", + "template": "
- + {{#each table_config.header.columns as |column|}} {{#if column.enable}} - + {{/if}} {{/each}} - + {{#each order.products as |product|}} {{#if @last}} - + {{else}} - + {{/if}} {{#each @root.table_config.header.columns as |column|}} {{#if column.enable}} {{#if (eq column.id 'item')}} - {{/if}} {{#if (eq column.id 'quantity')}} - {{/if}} {{#if (eq column.id 'tax')}} - {{/if}} {{#if (eq column.id 'unit_amount')}} - {{/if}} {{#if (eq column.id 'net_total')}} - {{/if}} {{#if (eq column.id 'amount_tax')}} - {{/if}} {{#if (eq column.id 'gross_total')}} - @@ -123,61 +436,886 @@ req = shared.CustomVariable( {{#if table_config.footer.gross_total.enable}} {{#each order.total_details.recurrences as |item|}} - - + + {{#if @root.table_config.footer.payment_type.enable}} - + {{/if}} {{#if (isColumnEnabled @root.table_config 'net_total')}} {{#if @root.table_config.footer.net_total.enable}} - + {{/if}} {{/if}} - {{/each}} {{/if}} - +
{{column._label}}{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} {{product.name}} {{/if}} {{#if @root.table_config.body.price_description.enable}}
- {{product.price.description}} + {{product.price.description}} {{/if}} {{#if @root.table_config.body.product_description.enable}}
- {{product.description}} + {{product.description}} {{/if}}
{{product.price.quantity}} + {{product.price.quantity}} + {{product.price.tax_rate}} + {{product.price.unit_amount_net}} + {{product.price.amount_subtotal}} + {{product.price.amount_tax}} + {{product.price.amount_total}} {{#if @root.table_config.body.payment_type.enable}} {{#if (eq product.price.type 'recurring')}}
- {{product.price.billing_period}} + {{product.price.billing_period}} {{/if}} {{/if}}
{{item.billing_period}}{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_subtotal}}{{item.amount_total}} + {{item.amount_total}} {{#if @root.table_config.footer.amount_tax.enable}}
- {{item.full_amount_tax}} + {{item.full_amount_tax}} {{/if}}
", - type="order_table", - updated_at="2022-04-20T12:41:43.662Z", - updated_by="100042", + "type": epilot_template_variables.Type.CUSTOM, + "updated_at": "2022-04-20T12:41:43.662Z", + "updated_by": "100042", +}, + RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False)) + +# Use the SDK ... + +``` + +If you'd like to override the default retry strategy for all operations that support retries, you can use the `retry_config` optional parameter when initializing the SDK: +```python +from epilot.utils import BackoffStrategy, RetryConfig +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False), + security=epilot_template_variables.Security( + epilot_auth="", + ), ) - -res = s.custom_variables.create_custom_variable(req) -if res.status_code == 200: - # handle response + +s.custom_variables.create_custom_variable(request={ + "config": {}, + "created_at": "2022-04-19T12:41:43.662Z", + "created_by": "100042", + "helper_logic": "return param1 * param2;", + "helper_params": [ + "param1", + "param2", + ], + "id": "rbse777b-3cf8-4bff-bb0c-253fd1123250", + "key": "my_custom_table", + "name": "My Custom table", + "template": " + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id 'item')}} + + + {{/if}} + {{#if (eq column.id 'quantity')}} + + + {{/if}} + {{#if (eq column.id 'tax')}} + + + {{/if}} + {{#if (eq column.id 'unit_amount')}} + + + {{/if}} + {{#if (eq column.id 'net_total')}} + + + {{/if}} + {{#if (eq column.id 'amount_tax')}} + + + {{/if}} + {{#if (eq column.id 'gross_total')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config 'net_total')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type 'recurring')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+", + "type": epilot_template_variables.Type.CUSTOM, + "updated_at": "2022-04-20T12:41:43.662Z", + "updated_by": "100042", +}) + +# Use the SDK ... + ``` - + + + +## Error Handling - -## SDK Available Operations +Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an error. If Error objects are specified in your OpenAPI Spec, the SDK will raise the appropriate Error type. +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | -### custom_variables +### Example + +```python +import epilot_template_variables +from epilot_template_variables import Epilot, models + +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +try: + s.custom_variables.create_custom_variable(request={ + "config": {}, + "created_at": "2022-04-19T12:41:43.662Z", + "created_by": "100042", + "helper_logic": "return param1 * param2;", + "helper_params": [ + "param1", + "param2", + ], + "id": "rbse777b-3cf8-4bff-bb0c-253fd1123250", + "key": "my_custom_table", + "name": "My Custom table", + "template": " + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id 'item')}} + + + {{/if}} + {{#if (eq column.id 'quantity')}} + + + {{/if}} + {{#if (eq column.id 'tax')}} + + + {{/if}} + {{#if (eq column.id 'unit_amount')}} + + + {{/if}} + {{#if (eq column.id 'net_total')}} + + + {{/if}} + {{#if (eq column.id 'amount_tax')}} + + + {{/if}} + {{#if (eq column.id 'gross_total')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config 'net_total')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type 'recurring')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+", + "type": epilot_template_variables.Type.CUSTOM, + "updated_at": "2022-04-20T12:41:43.662Z", + "updated_by": "100042", +}) + +except models.SDKError as e: + # handle exception + raise(e) + +# Use the SDK ... + +``` + + + +## Server Selection + +### Select Server by Index + +You can override the default server globally by passing a server index to the `server_idx: int` optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers: + +| # | Server | Variables | +| - | ------ | --------- | +| 0 | `https://template-variables-api.sls.epilot.io` | None | + +#### Example + +```python +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + server_idx=0, + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +s.custom_variables.create_custom_variable(request={ + "config": {}, + "created_at": "2022-04-19T12:41:43.662Z", + "created_by": "100042", + "helper_logic": "return param1 * param2;", + "helper_params": [ + "param1", + "param2", + ], + "id": "rbse777b-3cf8-4bff-bb0c-253fd1123250", + "key": "my_custom_table", + "name": "My Custom table", + "template": " + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id 'item')}} + + + {{/if}} + {{#if (eq column.id 'quantity')}} + + + {{/if}} + {{#if (eq column.id 'tax')}} + + + {{/if}} + {{#if (eq column.id 'unit_amount')}} + + + {{/if}} + {{#if (eq column.id 'net_total')}} + + + {{/if}} + {{#if (eq column.id 'amount_tax')}} + + + {{/if}} + {{#if (eq column.id 'gross_total')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config 'net_total')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type 'recurring')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+", + "type": epilot_template_variables.Type.CUSTOM, + "updated_at": "2022-04-20T12:41:43.662Z", + "updated_by": "100042", +}) + +# Use the SDK ... + +``` + + +### Override Server URL Per-Client + +The default server can also be overridden globally by passing a URL to the `server_url: str` optional parameter when initializing the SDK client instance. For example: +```python +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + server_url="https://template-variables-api.sls.epilot.io", + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +s.custom_variables.create_custom_variable(request={ + "config": {}, + "created_at": "2022-04-19T12:41:43.662Z", + "created_by": "100042", + "helper_logic": "return param1 * param2;", + "helper_params": [ + "param1", + "param2", + ], + "id": "rbse777b-3cf8-4bff-bb0c-253fd1123250", + "key": "my_custom_table", + "name": "My Custom table", + "template": " + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id 'item')}} + + + {{/if}} + {{#if (eq column.id 'quantity')}} + + + {{/if}} + {{#if (eq column.id 'tax')}} + + + {{/if}} + {{#if (eq column.id 'unit_amount')}} + + + {{/if}} + {{#if (eq column.id 'net_total')}} + + + {{/if}} + {{#if (eq column.id 'amount_tax')}} + + + {{/if}} + {{#if (eq column.id 'gross_total')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config 'net_total')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type 'recurring')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+", + "type": epilot_template_variables.Type.CUSTOM, + "updated_at": "2022-04-20T12:41:43.662Z", + "updated_by": "100042", +}) + +# Use the SDK ... + +``` + + + +## Custom HTTP Client + +The Python SDK makes API calls using the [httpx](https://www.python-httpx.org/) HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance. +Depending on whether you are using the sync or async version of the SDK, you can pass an instance of `HttpClient` or `AsyncHttpClient` respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls. +This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of `httpx.Client` or `httpx.AsyncClient` directly. + +For example, you could specify a header for every request that this sdk makes as follows: +```python +from epilot_template_variables import Epilot +import httpx + +http_client = httpx.Client(headers={"x-custom-header": "someValue"}) +s = Epilot(client=http_client) +``` + +or you could wrap the client with your own custom logic: +```python +from epilot_template_variables import Epilot +from epilot_template_variables.httpclient import AsyncHttpClient +import httpx + +class CustomClient(AsyncHttpClient): + client: AsyncHttpClient + + def __init__(self, client: AsyncHttpClient): + self.client = client + + async def send( + self, + request: httpx.Request, + *, + stream: bool = False, + auth: Union[ + httpx._types.AuthTypes, httpx._client.UseClientDefault, None + ] = httpx.USE_CLIENT_DEFAULT, + follow_redirects: Union[ + bool, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + ) -> httpx.Response: + request.headers["Client-Level-Header"] = "added by client" + + return await self.client.send( + request, stream=stream, auth=auth, follow_redirects=follow_redirects + ) + + def build_request( + self, + method: str, + url: httpx._types.URLTypes, + *, + content: Optional[httpx._types.RequestContent] = None, + data: Optional[httpx._types.RequestData] = None, + files: Optional[httpx._types.RequestFiles] = None, + json: Optional[Any] = None, + params: Optional[httpx._types.QueryParamTypes] = None, + headers: Optional[httpx._types.HeaderTypes] = None, + cookies: Optional[httpx._types.CookieTypes] = None, + timeout: Union[ + httpx._types.TimeoutTypes, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + extensions: Optional[httpx._types.RequestExtensions] = None, + ) -> httpx.Request: + return self.client.build_request( + method, + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + +s = Epilot(async_client=CustomClient(httpx.AsyncClient())) +``` + + + +## Authentication + +### Per-Client Security Schemes + +This SDK supports the following security schemes globally: + +| Name | Type | Scheme | +| ------------- | ------------- | ------------- | +| `epilot_auth` | http | HTTP Bearer | +| `epilot_org` | apiKey | API key | + +You can set the security parameters through the `security` optional parameter when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example: +```python +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +s.custom_variables.create_custom_variable(request={ + "config": {}, + "created_at": "2022-04-19T12:41:43.662Z", + "created_by": "100042", + "helper_logic": "return param1 * param2;", + "helper_params": [ + "param1", + "param2", + ], + "id": "rbse777b-3cf8-4bff-bb0c-253fd1123250", + "key": "my_custom_table", + "name": "My Custom table", + "template": " + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id 'item')}} + + + {{/if}} + {{#if (eq column.id 'quantity')}} + + + {{/if}} + {{#if (eq column.id 'tax')}} + + + {{/if}} + {{#if (eq column.id 'unit_amount')}} + + + {{/if}} + {{#if (eq column.id 'net_total')}} + + + {{/if}} + {{#if (eq column.id 'amount_tax')}} + + + {{/if}} + {{#if (eq column.id 'gross_total')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config 'net_total')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type 'recurring')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+", + "type": epilot_template_variables.Type.CUSTOM, + "updated_at": "2022-04-20T12:41:43.662Z", + "updated_by": "100042", +}) + +# Use the SDK ... + +``` + + + +## Debugging + +To emit debug logs for SDK requests and responses you can pass a logger object directly into your SDK object. + +```python +from epilot_template_variables import Epilot +import logging + +logging.basicConfig(level=logging.DEBUG) +s = Epilot(debug_logger=logging.getLogger("epilot_template_variables")) +``` + -* `create_custom_variable` - Create custom variable -* `delete_custom_variable` - Delete custom variable -* `get_blue_print_table_config` - Get default table config -* `get_custom_variable` - Get custom variable -* `get_custom_variables` - Get custom variables -* `update_custom_variable` - Update custom variable + -### variables -* `generate_q_rcode` - generateQRcode -* `get_categories` - getCategories -* `get_variable_context` - getVariableContext -* `replace_templates` - replaceTemplates -* `search_variables` - searchVariables - ### SDK Generated by [Speakeasy](https://docs.speakeasyapi.dev/docs/using-speakeasy/client-sdks) diff --git a/template_variables/RELEASES.md b/template_variables/RELEASES.md index 6b443894da..cc266a05f8 100644 --- a/template_variables/RELEASES.md +++ b/template_variables/RELEASES.md @@ -34,4 +34,12 @@ Based on: ### Changes Based on: - OpenAPI Doc 1.0.0 https://docs.api.epilot.io/template-variables.yaml -- Speakeasy CLI 1.19.2 (2.16.5) https://github.com/speakeasy-api/speakeasy \ No newline at end of file +- Speakeasy CLI 1.19.2 (2.16.5) https://github.com/speakeasy-api/speakeasy + +## 2024-08-07 00:25:03 +### Changes +Based on: +- OpenAPI Doc 1.0.0 https://docs.api.epilot.io/template-variables.yaml +- Speakeasy CLI 1.355.0 (2.387.0) https://github.com/speakeasy-api/speakeasy +### Generated +- [python v1.3.0] template_variables \ No newline at end of file diff --git a/template_variables/USAGE.md b/template_variables/USAGE.md old mode 100755 new mode 100644 index abcb76fe36..901a7a9c2c --- a/template_variables/USAGE.md +++ b/template_variables/USAGE.md @@ -1,106 +1,101 @@ - + ```python -import epilot -from epilot.models import operations, shared +# Synchronous Example +import epilot_template_variables +from epilot_template_variables import Epilot -s = epilot.Epilot( - security=shared.Security( - epilot_auth="Bearer YOUR_BEARER_TOKEN_HERE", +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", ), ) -req = shared.CustomVariable( - config={ - "deserunt": "porro", - "nulla": "id", - "vero": "perspiciatis", - }, - created_at="2022-04-19T12:41:43.662Z", - created_by="100042", - helper_logic="return param1 * param2;", - helper_params=[ - "nihil", - "fuga", - "facilis", - "eum", +s.custom_variables.create_custom_variable(request={ + "config": {}, + "created_at": "2022-04-19T12:41:43.662Z", + "created_by": "100042", + "helper_logic": "return param1 * param2;", + "helper_params": [ + "param1", + "param2", ], - id="rbse777b-3cf8-4bff-bb0c-253fd1123250", - key="my_custom_table", - name="My Custom table", - template=" + "id": "rbse777b-3cf8-4bff-bb0c-253fd1123250", + "key": "my_custom_table", + "name": "My Custom table", + "template": "
- + {{#each table_config.header.columns as |column|}} {{#if column.enable}} - + {{/if}} {{/each}} - + {{#each order.products as |product|}} {{#if @last}} - + {{else}} - + {{/if}} {{#each @root.table_config.header.columns as |column|}} {{#if column.enable}} {{#if (eq column.id 'item')}} - {{/if}} {{#if (eq column.id 'quantity')}} - {{/if}} {{#if (eq column.id 'tax')}} - {{/if}} {{#if (eq column.id 'unit_amount')}} - {{/if}} {{#if (eq column.id 'net_total')}} - {{/if}} {{#if (eq column.id 'amount_tax')}} - {{/if}} {{#if (eq column.id 'gross_total')}} - @@ -112,37 +107,177 @@ req = shared.CustomVariable( {{#if table_config.footer.gross_total.enable}} {{#each order.total_details.recurrences as |item|}} - - + + {{#if @root.table_config.footer.payment_type.enable}} - + {{/if}} {{#if (isColumnEnabled @root.table_config 'net_total')}} {{#if @root.table_config.footer.net_total.enable}} - + {{/if}} {{/if}} - {{/each}} {{/if}} - +
{{column._label}}{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} {{product.name}} {{/if}} {{#if @root.table_config.body.price_description.enable}}
- {{product.price.description}} + {{product.price.description}} {{/if}} {{#if @root.table_config.body.product_description.enable}}
- {{product.description}} + {{product.description}} {{/if}}
{{product.price.quantity}} + {{product.price.quantity}} + {{product.price.tax_rate}} + {{product.price.unit_amount_net}} + {{product.price.amount_subtotal}} + {{product.price.amount_tax}} + {{product.price.amount_total}} {{#if @root.table_config.body.payment_type.enable}} {{#if (eq product.price.type 'recurring')}}
- {{product.price.billing_period}} + {{product.price.billing_period}} {{/if}} {{/if}}
{{item.billing_period}}{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_subtotal}}{{item.amount_total}} + {{item.amount_total}} {{#if @root.table_config.footer.amount_tax.enable}}
- {{item.full_amount_tax}} + {{item.full_amount_tax}} {{/if}}
", - type="order_table", - updated_at="2022-04-20T12:41:43.662Z", - updated_by="100042", -) - -res = s.custom_variables.create_custom_variable(req) + "type": epilot_template_variables.Type.CUSTOM, + "updated_at": "2022-04-20T12:41:43.662Z", + "updated_by": "100042", +}) + +# Use the SDK ... +``` + +
+ +The same SDK client can also be used to make asychronous requests by importing asyncio. +```python +# Asynchronous Example +import asyncio +import epilot_template_variables +from epilot_template_variables import Epilot + +async def main(): + s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), + ) + await s.custom_variables.create_custom_variable_async(request={ + "config": {}, + "created_at": "2022-04-19T12:41:43.662Z", + "created_by": "100042", + "helper_logic": "return param1 * param2;", + "helper_params": [ + "param1", + "param2", + ], + "id": "rbse777b-3cf8-4bff-bb0c-253fd1123250", + "key": "my_custom_table", + "name": "My Custom table", + "template": " + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id 'item')}} + + + {{/if}} + {{#if (eq column.id 'quantity')}} + + + {{/if}} + {{#if (eq column.id 'tax')}} + + + {{/if}} + {{#if (eq column.id 'unit_amount')}} + + + {{/if}} + {{#if (eq column.id 'net_total')}} + + + {{/if}} + {{#if (eq column.id 'amount_tax')}} + + + {{/if}} + {{#if (eq column.id 'gross_total')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config 'net_total')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type 'recurring')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+ ", + "type": epilot_template_variables.Type.CUSTOM, + "updated_at": "2022-04-20T12:41:43.662Z", + "updated_by": "100042", + }) + # Use the SDK ... -if res.status_code == 200: - # handle response +asyncio.run(main()) ``` - \ No newline at end of file + \ No newline at end of file diff --git a/template_variables/docs/models/categoryresult.md b/template_variables/docs/models/categoryresult.md new file mode 100644 index 0000000000..043c42d1c6 --- /dev/null +++ b/template_variables/docs/models/categoryresult.md @@ -0,0 +1,9 @@ +# CategoryResult + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------ | ------------------ | ------------------ | ------------------ | ------------------ | +| `category` | *Optional[str]* | :heavy_minus_sign: | N/A | contact | +| `description` | *Optional[str]* | :heavy_minus_sign: | N/A | Contact | \ No newline at end of file diff --git a/template_variables/docs/models/config.md b/template_variables/docs/models/config.md new file mode 100644 index 0000000000..4e902045dc --- /dev/null +++ b/template_variables/docs/models/config.md @@ -0,0 +1,9 @@ +# Config + +Variable configuration + + +## Fields + +| Field | Type | Required | Description | +| ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/template_variables/docs/models/contextdata.md b/template_variables/docs/models/contextdata.md new file mode 100644 index 0000000000..9e90c08fc8 --- /dev/null +++ b/template_variables/docs/models/contextdata.md @@ -0,0 +1,9 @@ +# ContextData + +If context data is avaialble, this data will be used for variable replace. + + +## Fields + +| Field | Type | Required | Description | +| ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/template_variables/docs/models/customvariable.md b/template_variables/docs/models/customvariable.md new file mode 100644 index 0000000000..8aee10685d --- /dev/null +++ b/template_variables/docs/models/customvariable.md @@ -0,0 +1,19 @@ +# CustomVariable + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `config` | [Optional[models.Config]](../models/config.md) | :heavy_minus_sign: | Variable configuration | {
"$ref": "#/components/examples/TableConfig/value"
} | +| `created_at` | *Optional[str]* | :heavy_minus_sign: | Creation time | 2022-04-19 12:41:43.662 +0000 UTC | +| `created_by` | *Optional[str]* | :heavy_minus_sign: | Created by | 100042 | +| `helper_logic` | *Optional[str]* | :heavy_minus_sign: | The helper function logic | return param1 * param2; | +| `helper_params` | List[*str*] | :heavy_minus_sign: | The helper function parameter's names | [
"param1",
"param2"
] | +| `id` | *Optional[str]* | :heavy_minus_sign: | ID | rbse777b-3cf8-4bff-bb0c-253fd1123250 | +| `key` | *Optional[str]* | :heavy_minus_sign: | The key which is used for Handlebar variable syntax {{key}} | my_custom_table | +| `name` | *Optional[str]* | :heavy_minus_sign: | Custom variable name | My Custom table | +| `template` | *Optional[str]* | :heavy_minus_sign: | Handlebar template that used to generate the variable content |


{{#each table_config.header.columns as \|column\|}}
{{#if column.enable}}

{{/if}}
{{/each}}




{{#each order.products as \|product\|}}
{{#if @last}}

{{else}}

{{/if}}
{{#each @root.table_config.header.columns as \|column\|}}
{{#if column.enable}}
{{#if (eq column.id 'item')}}


{{/if}}
{{#if (eq column.id 'quantity')}}


{{/if}}
{{#if (eq column.id 'tax')}}


{{/if}}
{{#if (eq column.id 'unit_amount')}}


{{/if}}
{{#if (eq column.id 'net_total')}}


{{/if}}
{{#if (eq column.id 'amount_tax')}}


{{/if}}
{{#if (eq column.id 'gross_total')}}


{{/if}}
{{/if}}
{{/each}}

{{/each}}

{{#if table_config.footer.gross_total.enable}}
{{#each order.total_details.recurrences as \|item\|}}


{{#if @root.table_config.footer.payment_type.enable}}

{{/if}}
{{#if (isColumnEnabled @root.table_config 'net_total')}}
{{#if @root.table_config.footer.net_total.enable}}

{{/if}}
{{/if}}


{{/each}}
{{/if}}


{{column._label}}

{{#if @root.table_config.body.product_name.enable}}
{{product.name}}
{{/if}}
{{#if @root.table_config.body.price_description.enable}}


{{product.price.description}}
{{/if}}
{{#if @root.table_config.body.product_description.enable}}


{{product.description}}
{{/if}}
{{product.price.quantity}}

{{product.price.tax_rate}}

{{product.price.unit_amount_net}}

{{product.price.amount_subtotal}}

{{product.price.amount_tax}}

{{product.price.amount_total}}
{{#if @root.table_config.body.payment_type.enable}}
{{#if (eq product.price.type 'recurring')}}


{{product.price.billing_period}}
{{/if}}
{{/if}}
{{item.billing_period}} {{item.amount_subtotal}} {{item.amount_total}}
{{#if @root.table_config.footer.amount_tax.enable}}


{{item.full_amount_tax}}
{{/if}}

| +| `type` | [Optional[models.Type]](../models/type.md) | :heavy_minus_sign: | Custom variable type | rbse777b-3cf8-4bff-bb0c-253fd1123250 | +| `updated_at` | *Optional[str]* | :heavy_minus_sign: | Last update time | 2022-04-20 12:41:43.662 +0000 UTC | +| `updated_by` | *Optional[str]* | :heavy_minus_sign: | Updated by | 100042 | \ No newline at end of file diff --git a/template_variables/docs/models/deletecustomvariablerequest.md b/template_variables/docs/models/deletecustomvariablerequest.md new file mode 100644 index 0000000000..21a774293f --- /dev/null +++ b/template_variables/docs/models/deletecustomvariablerequest.md @@ -0,0 +1,8 @@ +# DeleteCustomVariableRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +| `id` | *str* | :heavy_check_mark: | Custom vairable ID | rbse777b-3cf8-4bff-bb0c-253fd1123250 | \ No newline at end of file diff --git a/template_variables/docs/models/externalcustomvariable.md b/template_variables/docs/models/externalcustomvariable.md new file mode 100644 index 0000000000..3d08742ad3 --- /dev/null +++ b/template_variables/docs/models/externalcustomvariable.md @@ -0,0 +1,9 @@ +# ExternalCustomVariable + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | +| `value` | *Optional[str]* | :heavy_minus_sign: | N/A | https://partner.epilot.cloud/activate-account?user_name=htny.pct%2Btet%40gmail.com&confirmation_code=EdXPRW19 | +| `variable` | *Optional[str]* | :heavy_minus_sign: | N/A | {{craftsmen.invitation_link}} | \ No newline at end of file diff --git a/template_variables/docs/models/getcategoriesrequest.md b/template_variables/docs/models/getcategoriesrequest.md new file mode 100644 index 0000000000..02e735a7d0 --- /dev/null +++ b/template_variables/docs/models/getcategoriesrequest.md @@ -0,0 +1,8 @@ +# GetCategoriesRequest + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `lang` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/template_variables/docs/models/getcustomvariablerequest.md b/template_variables/docs/models/getcustomvariablerequest.md new file mode 100644 index 0000000000..9558f39d70 --- /dev/null +++ b/template_variables/docs/models/getcustomvariablerequest.md @@ -0,0 +1,8 @@ +# GetCustomVariableRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +| `id` | *str* | :heavy_check_mark: | Custom vairable ID | rbse777b-3cf8-4bff-bb0c-253fd1123250 | \ No newline at end of file diff --git a/template_variables/docs/models/getvariablecontextrequestbody.md b/template_variables/docs/models/getvariablecontextrequestbody.md new file mode 100644 index 0000000000..2bae960663 --- /dev/null +++ b/template_variables/docs/models/getvariablecontextrequestbody.md @@ -0,0 +1,8 @@ +# GetVariableContextRequestBody + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `parameters` | [Optional[models.VariableParameters]](../models/variableparameters.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/template_variables/docs/models/replacetemplatesrequestbody.md b/template_variables/docs/models/replacetemplatesrequestbody.md new file mode 100644 index 0000000000..7593ded957 --- /dev/null +++ b/template_variables/docs/models/replacetemplatesrequestbody.md @@ -0,0 +1,9 @@ +# ReplaceTemplatesRequestBody + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `inputs` | List[*str*] | :heavy_minus_sign: | N/A | +| `parameters` | [Optional[models.VariableParameters]](../models/variableparameters.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/template_variables/docs/models/replacetemplatesresponsebody.md b/template_variables/docs/models/replacetemplatesresponsebody.md new file mode 100644 index 0000000000..a247a94ffd --- /dev/null +++ b/template_variables/docs/models/replacetemplatesresponsebody.md @@ -0,0 +1,10 @@ +# ReplaceTemplatesResponseBody + +ok + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `outputs` | List[*str*] | :heavy_minus_sign: | N/A | "[Brand Name GmbH] Order confirmation",
"Hello Customer Name

Brand Name GmbH
Brand Name
imprint
"]
| \ No newline at end of file diff --git a/template_variables/docs/models/searchvariablesrequestbody.md b/template_variables/docs/models/searchvariablesrequestbody.md new file mode 100644 index 0000000000..1fcbbb2e69 --- /dev/null +++ b/template_variables/docs/models/searchvariablesrequestbody.md @@ -0,0 +1,13 @@ +# SearchVariablesRequestBody + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | +| `query` | *str* | :heavy_check_mark: | Search string | logo | +| `template_type` | [models.TemplateType](../models/templatetype.md) | :heavy_check_mark: | N/A | | +| `entity_schemas` | List[*str*] | :heavy_minus_sign: | N/A | | +| `from_` | *Optional[int]* | :heavy_minus_sign: | N/A | | +| `lang` | *Optional[str]* | :heavy_minus_sign: | 2-letter language code (ISO 639-1) | | +| `size` | *Optional[int]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/template_variables/docs/models/security.md b/template_variables/docs/models/security.md new file mode 100644 index 0000000000..c59fe377ff --- /dev/null +++ b/template_variables/docs/models/security.md @@ -0,0 +1,9 @@ +# Security + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `epilot_auth` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `epilot_org` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/template_variables/docs/models/templatetype.md b/template_variables/docs/models/templatetype.md new file mode 100644 index 0000000000..d6ed07125f --- /dev/null +++ b/template_variables/docs/models/templatetype.md @@ -0,0 +1,9 @@ +# TemplateType + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `EMAIL` | email | +| `DOCUMENT` | document | \ No newline at end of file diff --git a/template_variables/docs/models/type.md b/template_variables/docs/models/type.md new file mode 100644 index 0000000000..05dad8853e --- /dev/null +++ b/template_variables/docs/models/type.md @@ -0,0 +1,11 @@ +# Type + +Custom variable type + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `ORDER_TABLE` | order_table | +| `CUSTOM` | custom | \ No newline at end of file diff --git a/template_variables/docs/models/updatecustomvariablerequest.md b/template_variables/docs/models/updatecustomvariablerequest.md new file mode 100644 index 0000000000..46f05ed182 --- /dev/null +++ b/template_variables/docs/models/updatecustomvariablerequest.md @@ -0,0 +1,9 @@ +# UpdateCustomVariableRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | Custom variable ID | rbse777b-3cf8-4bff-bb0c-253fd1123250 | +| `custom_variable` | [Optional[models.CustomVariable]](../models/customvariable.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/template_variables/docs/models/utils/retryconfig.md b/template_variables/docs/models/utils/retryconfig.md new file mode 100644 index 0000000000..69dd549ec7 --- /dev/null +++ b/template_variables/docs/models/utils/retryconfig.md @@ -0,0 +1,24 @@ +# RetryConfig + +Allows customizing the default retry configuration. Only usable with methods that mention they support retries. + +## Fields + +| Name | Type | Description | Example | +| ------------------------- | ----------------------------------- | --------------------------------------- | --------- | +| `strategy` | `*str*` | The retry strategy to use. | `backoff` | +| `backoff` | [BackoffStrategy](#backoffstrategy) | Configuration for the backoff strategy. | | +| `retry_connection_errors` | `*bool*` | Whether to retry on connection errors. | `true` | + +## BackoffStrategy + +The backoff strategy allows retrying a request with an exponential backoff between each retry. + +### Fields + +| Name | Type | Description | Example | +| ------------------ | --------- | ----------------------------------------- | -------- | +| `initial_interval` | `*int*` | The initial interval in milliseconds. | `500` | +| `max_interval` | `*int*` | The maximum interval in milliseconds. | `60000` | +| `exponent` | `*float*` | The exponent to use for the backoff. | `1.5` | +| `max_elapsed_time` | `*int*` | The maximum elapsed time in milliseconds. | `300000` | \ No newline at end of file diff --git a/template_variables/docs/models/variablecontext.md b/template_variables/docs/models/variablecontext.md new file mode 100644 index 0000000000..caa83e2a86 --- /dev/null +++ b/template_variables/docs/models/variablecontext.md @@ -0,0 +1,11 @@ +# VariableContext + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | +| `brand` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | {
"$ref": "#/components/examples/ExampleBrand/value"
} | +| `contact` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | {
"$ref": "#/components/examples/ExampleContactEntity/value"
} | +| `main` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | {
"$ref": "#/components/examples/ExampleMain/value"
} | +| `unsubscribe_url` | *Optional[str]* | :heavy_minus_sign: | N/A | https://consent.sls.epilot.io/v1/unsubscribe?token=abc123 | \ No newline at end of file diff --git a/template_variables/docs/models/variableparameters.md b/template_variables/docs/models/variableparameters.md new file mode 100644 index 0000000000..56513e9b18 --- /dev/null +++ b/template_variables/docs/models/variableparameters.md @@ -0,0 +1,18 @@ +# VariableParameters + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `template_type` | [models.TemplateType](../models/templatetype.md) | :heavy_check_mark: | N/A | | +| `brand_id` | *OptionalNullable[float]* | :heavy_minus_sign: | Brand ID | 123451 | +| `context_data` | [Optional[models.ContextData]](../models/contextdata.md) | :heavy_minus_sign: | If context data is avaialble, this data will be used for variable replace. | | +| `custom_variables` | List[[models.ExternalCustomVariable](../models/externalcustomvariable.md)] | :heavy_minus_sign: | Custom variables with specified values form other services. | | +| `language` | *Optional[str]* | :heavy_minus_sign: | 2-letter language code (ISO 639-1) | | +| `main_entity_id` | *Optional[str]* | :heavy_minus_sign: | The main entity ID. Use main entity in order to use the variable without schema slug prefix - or just pass directly to other object ID. | 63753437-c9e2-4e83-82bb-b1c666514561 | +| `template_name` | *Optional[str]* | :heavy_minus_sign: | The name of email template | | +| `template_tags` | List[*str*] | :heavy_minus_sign: | The tags of email template | | +| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | User ID | 50001 | +| `user_org_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Organization ID of the user | 729224 | +| `variables_version` | *Optional[str]* | :heavy_minus_sign: | The version of the variables syntax supported. Default is 1.0 | 2 | \ No newline at end of file diff --git a/template_variables/docs/models/variableresult.md b/template_variables/docs/models/variableresult.md new file mode 100644 index 0000000000..c0f6f8ade6 --- /dev/null +++ b/template_variables/docs/models/variableresult.md @@ -0,0 +1,12 @@ +# VariableResult + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `description` | *Optional[str]* | :heavy_minus_sign: | Variable description | +| `group` | *Optional[str]* | :heavy_minus_sign: | Variable group | +| `insert` | *Optional[str]* | :heavy_minus_sign: | The value which is used to insert to template | +| `qrdata` | *Optional[str]* | :heavy_minus_sign: | Payload for the QR data | +| `type` | [Optional[models.VariableResultType]](../models/variableresulttype.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/template_variables/docs/models/variableresulttype.md b/template_variables/docs/models/variableresulttype.md new file mode 100644 index 0000000000..a4605a78b4 --- /dev/null +++ b/template_variables/docs/models/variableresulttype.md @@ -0,0 +1,9 @@ +# VariableResultType + + +## Values + +| Name | Value | +| --------- | --------- | +| `SIMPLE` | simple | +| `PARTIAL` | partial | \ No newline at end of file diff --git a/template_variables/docs/sdks/customvariables/README.md b/template_variables/docs/sdks/customvariables/README.md new file mode 100644 index 0000000000..4e133aee45 --- /dev/null +++ b/template_variables/docs/sdks/customvariables/README.md @@ -0,0 +1,488 @@ +# CustomVariables +(*custom_variables*) + +### Available Operations + +* [create_custom_variable](#create_custom_variable) - Create custom variable +* [delete_custom_variable](#delete_custom_variable) - Delete custom variable +* [get_blue_print_table_config](#get_blue_print_table_config) - Get default table config +* [get_custom_variable](#get_custom_variable) - Get custom variable +* [get_custom_variables](#get_custom_variables) - Get custom variables +* [update_custom_variable](#update_custom_variable) - Update custom variable + +## create_custom_variable + +Create custom variable + +### Example Usage + +```python +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +s.custom_variables.create_custom_variable(request={ + "config": {}, + "created_at": "2022-04-19T12:41:43.662Z", + "created_by": "100042", + "helper_logic": "return param1 * param2;", + "helper_params": [ + "param1", + "param2", + ], + "id": "rbse777b-3cf8-4bff-bb0c-253fd1123250", + "key": "my_custom_table", + "name": "My Custom table", + "template": " + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id 'item')}} + + + {{/if}} + {{#if (eq column.id 'quantity')}} + + + {{/if}} + {{#if (eq column.id 'tax')}} + + + {{/if}} + {{#if (eq column.id 'unit_amount')}} + + + {{/if}} + {{#if (eq column.id 'net_total')}} + + + {{/if}} + {{#if (eq column.id 'amount_tax')}} + + + {{/if}} + {{#if (eq column.id 'gross_total')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config 'net_total')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type 'recurring')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+", + "type": epilot_template_variables.Type.CUSTOM, + "updated_at": "2022-04-20T12:41:43.662Z", + "updated_by": "100042", +}) + +# Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `request` | [models.CustomVariable](../../models/customvariable.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | + +## delete_custom_variable + +Immediately and permanently deletes a custom variable + +### Example Usage + +```python +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +s.custom_variables.delete_custom_variable(id="rbse777b-3cf8-4bff-bb0c-253fd1123250") + +# Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | Example | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | Custom vairable ID | rbse777b-3cf8-4bff-bb0c-253fd1123250 | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | | + +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | + +## get_blue_print_table_config + +Get default table config + +### Example Usage + +```python +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +res = s.custom_variables.get_blue_print_table_config() + +if res is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + + +### Response + +**[models.CustomVariable](../../models/customvariable.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | + +## get_custom_variable + +Get custom variable + +### Example Usage + +```python +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +res = s.custom_variables.get_custom_variable(id="rbse777b-3cf8-4bff-bb0c-253fd1123250") + +if res is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | Example | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | Custom vairable ID | rbse777b-3cf8-4bff-bb0c-253fd1123250 | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | | + + +### Response + +**[models.CustomVariable](../../models/customvariable.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | + +## get_custom_variables + +Get all custom variables of organization + +### Example Usage + +```python +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +res = s.custom_variables.get_custom_variables() + +if res is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + + +### Response + +**[List[models.CustomVariable]](../../models/.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | + +## update_custom_variable + +Update custom variable + +### Example Usage + +```python +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +s.custom_variables.update_custom_variable(id="rbse777b-3cf8-4bff-bb0c-253fd1123250", custom_variable={ + "config": {}, + "created_at": "2022-04-19T12:41:43.662Z", + "created_by": "100042", + "helper_logic": "return param1 * param2;", + "helper_params": [ + "param1", + "param2", + ], + "id": "rbse777b-3cf8-4bff-bb0c-253fd1123250", + "key": "my_custom_table", + "name": "My Custom table", + "template": " + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id 'item')}} + + + {{/if}} + {{#if (eq column.id 'quantity')}} + + + {{/if}} + {{#if (eq column.id 'tax')}} + + + {{/if}} + {{#if (eq column.id 'unit_amount')}} + + + {{/if}} + {{#if (eq column.id 'net_total')}} + + + {{/if}} + {{#if (eq column.id 'amount_tax')}} + + + {{/if}} + {{#if (eq column.id 'gross_total')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config 'net_total')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type 'recurring')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+", + "type": epilot_template_variables.Type.CUSTOM, + "updated_at": "2022-04-20T12:41:43.662Z", + "updated_by": "100042", +}) + +# Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | Example | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | Custom variable ID | rbse777b-3cf8-4bff-bb0c-253fd1123250 | +| `custom_variable` | [Optional[models.CustomVariable]](../../models/customvariable.md) | :heavy_minus_sign: | N/A | | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | | + +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | diff --git a/template_variables/docs/sdks/epilot/README.md b/template_variables/docs/sdks/epilot/README.md new file mode 100644 index 0000000000..06007ebbc3 --- /dev/null +++ b/template_variables/docs/sdks/epilot/README.md @@ -0,0 +1,9 @@ +# Epilot SDK + + +## Overview + +Template Variables API: API to provide variables for email and document templates. + +### Available Operations + diff --git a/template_variables/docs/sdks/variables/README.md b/template_variables/docs/sdks/variables/README.md new file mode 100644 index 0000000000..1ed85e33ba --- /dev/null +++ b/template_variables/docs/sdks/variables/README.md @@ -0,0 +1,229 @@ +# Variables +(*variables*) + +## Overview + +Variables + +### Available Operations + +* [get_categories](#get_categories) - getCategories +* [get_variable_context](#get_variable_context) - getVariableContext +* [replace_templates](#replace_templates) - replaceTemplates +* [search_variables](#search_variables) - searchVariables + +## get_categories + +Get all template variable categories + +### Example Usage + +```python +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +res = s.variables.get_categories() + +if res is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `lang` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + + +### Response + +**[List[models.CategoryResult]](../../models/.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | + +## get_variable_context + +Get full variable context + +Calls Entity API, User API, Brand API and others to construct full context object used for template variable replace + + +### Example Usage + +```python +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +res = s.variables.get_variable_context(request={ + "parameters": { + "template_type": epilot_template_variables.TemplateType.EMAIL, + "brand_id": 123451, + "custom_variables": [ + { + "value": "https://partner.epilot.cloud/activate-account?user_name=htny.pct%2Btet%40gmail.com&confirmation_code=EdXPRW19", + "variable": "{{craftsmen.invitation_link}}", + }, + ], + "main_entity_id": "63753437-c9e2-4e83-82bb-b1c666514561", + "user_id": "50001", + "user_org_id": "729224", + "variables_version": "2", + }, +}) + +if res is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | +| `request` | [models.GetVariableContextRequestBody](../../models/getvariablecontextrequestbody.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + + +### Response + +**[models.VariableContext](../../models/variablecontext.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | + +## replace_templates + +Replace variables in handlebars templates + +Takes in an array of input templates and outputs the output text with replaced variables + + +### Example Usage + +```python +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +res = s.variables.replace_templates(request={ + "inputs": [ + "Hello, {{contact.first_name}}! + + {{{brand.signature}}} + ", + ], + "parameters": { + "template_type": epilot_template_variables.TemplateType.EMAIL, + "brand_id": 123451, + "custom_variables": [ + { + "value": "https://partner.epilot.cloud/activate-account?user_name=htny.pct%2Btet%40gmail.com&confirmation_code=EdXPRW19", + "variable": "{{craftsmen.invitation_link}}", + }, + ], + "main_entity_id": "63753437-c9e2-4e83-82bb-b1c666514561", + "user_id": "50001", + "user_org_id": "729224", + "variables_version": "2", + }, +}) + +if res is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | +| `request` | [models.ReplaceTemplatesRequestBody](../../models/replacetemplatesrequestbody.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + + +### Response + +**[models.ReplaceTemplatesResponseBody](../../models/replacetemplatesresponsebody.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | + +## search_variables + +Search variables + +### Example Usage + +```python +import epilot_template_variables +from epilot_template_variables import Epilot + +s = Epilot( + security=epilot_template_variables.Security( + epilot_auth="", + ), +) + + +res = s.variables.search_variables(request={ + "query": "logo", + "template_type": epilot_template_variables.TemplateType.DOCUMENT, + "entity_schemas": [ + "contact", + ], +}) + +if res is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | +| `request` | [models.SearchVariablesRequestBody](../../models/searchvariablesrequestbody.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + + +### Response + +**[List[models.VariableResult]](../../models/.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| models.SDKError | 4xx-5xx | */* | diff --git a/template_variables/gen.yaml b/template_variables/gen.yaml index e2cd3c1a98..a20030f7f3 100644 --- a/template_variables/gen.yaml +++ b/template_variables/gen.yaml @@ -1,16 +1,41 @@ -configVersion: 1.0.0 -management: - docChecksum: 14e2961bd134888671409e73ce503882 - docVersion: 1.0.0 - speakeasyVersion: 1.19.2 - generationVersion: 2.16.5 +configVersion: 2.0.0 generation: - telemetryEnabled: false sdkClassName: epilot + usageSnippets: + optionalPropertyRendering: withExample + fixes: + nameResolutionDec2023: false + parameterOrderingFeb2024: false + requestResponseComponentNamesFeb2024: false + auth: + oAuth2ClientCredentialsEnabled: false sdkFlattening: true - singleTagPerOp: false + telemetryEnabled: false python: - version: 1.2.2 + version: 1.3.0 + additionalDependencies: + dev: {} + main: {} author: epilot + authors: + - Speakeasy + clientServerStatusCodesAsErrors: true description: Python Client SDK for Epilot + enumFormat: enum + flattenGlobalSecurity: true + flattenRequests: false + imports: + option: openapi + paths: + callbacks: "" + errors: "" + operations: "" + shared: "" + webhooks: "" + inputModelSuffix: input + maxMethodParams: 4 + methodArguments: infer-optional-args + outputModelSuffix: output packageName: epilot-template-variables + responseFormat: flat + templateVersion: v2 diff --git a/template_variables/poetry.toml b/template_variables/poetry.toml new file mode 100644 index 0000000000..ab1033bd37 --- /dev/null +++ b/template_variables/poetry.toml @@ -0,0 +1,2 @@ +[virtualenvs] +in-project = true diff --git a/template_variables/py.typed b/template_variables/py.typed new file mode 100644 index 0000000000..3e38f1a929 --- /dev/null +++ b/template_variables/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. The package enables type hints. diff --git a/template_variables/pylintrc b/template_variables/pylintrc old mode 100755 new mode 100644 index 79b8008d09..5080038628 --- a/template_variables/pylintrc +++ b/template_variables/pylintrc @@ -59,10 +59,11 @@ ignore-paths= # Emacs file locks ignore-patterns=^\.# -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis). It -# supports qualified module names, as well as Unix pattern matching. +# List of module names for which member attributes should not be checked and +# will not be imported (useful for modules/projects where namespaces are +# manipulated during runtime and thus existing member attributes cannot be +# deduced by static analysis). It supports qualified module names, as well as +# Unix pattern matching. ignored-modules= # Python code to execute, usually for sys.path manipulation such as @@ -88,11 +89,17 @@ persistent=yes # Minimum Python version to use for version dependent checks. Will default to # the version used to run pylint. -py-version=3.9 +py-version=3.8 # Discover python modules and packages in the file system subtree. recursive=no +# Add paths to the list of the source roots. Supports globbing patterns. The +# source root is an absolute path or a path relative to the current working +# directory used to determine a package namespace for modules located under the +# source root. +source-roots=src + # When enabled, pylint would attempt to guess common misconfiguration and emit # user-friendly hints instead of false-positive error messages. suggestion-mode=yes @@ -116,20 +123,15 @@ argument-naming-style=snake_case #argument-rgx= # Naming style matching correct attribute names. -attr-naming-style=snake_case +#attr-naming-style=snake_case # Regular expression matching correct attribute names. Overrides attr-naming- # style. If left empty, attribute names will be checked with the set naming # style. -#attr-rgx= +attr-rgx=[^\W\d][^\W]*|__.*__$ # Bad variable names which should always be refused, separated by a comma. -bad-names=foo, - bar, - baz, - toto, - tutu, - tata +bad-names= # Bad variable names regexes, separated by a comma. If names match any regex, # they will always be refused @@ -185,6 +187,7 @@ good-names=i, ex, Run, _, + e, id # Good variable names regexes, separated by a comma. If names match any regex, @@ -229,6 +232,10 @@ no-docstring-rgx=^_ # These decorators are taken in consideration only for invalid-name. property-classes=abc.abstractproperty +# Regular expression matching correct type alias names. If left empty, type +# alias names will be checked with the set naming style. +typealias-rgx=.* + # Regular expression matching correct type variable names. If left empty, type # variable names will be checked with the set naming style. #typevar-rgx= @@ -251,15 +258,12 @@ check-protected-access-in-special-methods=no defining-attr-methods=__init__, __new__, setUp, + asyncSetUp, __post_init__ # List of member names, which should be excluded from the protected access # warning. -exclude-protected=_asdict, - _fields, - _replace, - _source, - _make +exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls @@ -422,6 +426,8 @@ disable=raw-checker-failed, suppressed-message, useless-suppression, deprecated-pragma, + use-implicit-booleaness-not-comparison-to-string, + use-implicit-booleaness-not-comparison-to-zero, use-symbolic-message-instead, trailing-whitespace, line-too-long, @@ -434,18 +440,27 @@ disable=raw-checker-failed, broad-exception-raised, too-few-public-methods, too-many-branches, - chained-comparison, duplicate-code, trailing-newlines, too-many-public-methods, too-many-locals, - too-many-lines + too-many-lines, + using-constant-test, + too-many-statements, + cyclic-import, + too-many-nested-blocks, + too-many-boolean-expressions, + no-else-raise, + bare-except, + broad-exception-caught, + fixme, + relative-beyond-top-level # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). See also the "--disable" option for examples. -enable=c-extension-no-member +enable= [METHOD_ARGS] @@ -491,8 +506,9 @@ evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor # used to format the message information. See doc for all details. msg-template= -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio). You can also give a reporter class, e.g. +# Set the output format. Available formats are: text, parseable, colorized, +# json2 (improved json format), json (old json format) and msvs (visual +# studio). You can also give a reporter class, e.g. # mypackage.mymodule.MyReporterClass. #output-format= @@ -526,8 +542,8 @@ min-similarity-lines=4 # Limits count of emitted suggestions for spelling mistakes. max-spelling-suggestions=4 -# Spelling dictionary name. Available dictionaries: none. To make it work, -# install the 'python-enchant' package. +# Spelling dictionary name. No available dictionaries : You need to install +# both the python package and the system dependency for enchant to work. spelling-dict= # List of comma separated words that should be considered directives if they @@ -620,7 +636,7 @@ additional-builtins= allow-global-unused-variables=yes # List of names allowed to shadow builtins -allowed-redefined-builtins= +allowed-redefined-builtins=id,object # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. diff --git a/template_variables/pyproject.toml b/template_variables/pyproject.toml new file mode 100644 index 0000000000..5d8e14fd71 --- /dev/null +++ b/template_variables/pyproject.toml @@ -0,0 +1,55 @@ +[tool.poetry] +name = "epilot-template-variables" +version = "1.3.0" +description = "Python Client SDK for Epilot" +authors = ["Speakeasy",] +readme = "README.md" +repository = "https://github.com/epilot-dev/sdk-python.git" +packages = [ + { include = "epilot_template_variables", from = "src" } +] +include = ["py.typed", "src/epilot_template_variables/py.typed"] + +[tool.setuptools.package-data] +"*" = ["py.typed", "src/epilot_template_variables/py.typed"] + +[virtualenvs] +in-project = true + +[tool.poetry.dependencies] +python = "^3.8" +httpx = "^0.27.0" +jsonpath-python = "^1.0.6" +pydantic = "~2.8.2" +python-dateutil = "^2.9.0.post0" +typing-inspect = "^0.9.0" + +[tool.poetry.group.dev.dependencies] +mypy = "==1.10.1" +pylint = "==3.2.3" +pyright = "==1.1.374" +types-python-dateutil = "^2.9.0.20240316" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" + +[tool.pytest.ini_options] +pythonpath = ["src"] + +[tool.mypy] +disable_error_code = "misc" + +[[tool.mypy.overrides]] +module = "typing_inspect" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "jsonpath" +ignore_missing_imports = true + +[tool.pyright] +venvPath = "." +venv = ".venv" + + diff --git a/template_variables/scripts/compile.sh b/template_variables/scripts/compile.sh new file mode 100755 index 0000000000..aa49772e2a --- /dev/null +++ b/template_variables/scripts/compile.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash + +set -o pipefail # Ensure pipeline failures are propagated + +# Use temporary files to store outputs and exit statuses +declare -A output_files +declare -A status_files + +# Function to run a command with temporary output and status files +run_command() { + local cmd="$1" + local key="$2" + local output_file="$3" + local status_file="$4" + + # Run the command and store output and exit status + { + eval "$cmd" + echo $? > "$status_file" + } &> "$output_file" & +} + +# Create temporary files for outputs and statuses +for cmd in compileall pylint mypy pyright; do + output_files[$cmd]=$(mktemp) + status_files[$cmd]=$(mktemp) +done + +# Collect PIDs for background processes +declare -a pids + +# Run commands in parallel using temporary files +echo "Running python -m compileall" +run_command 'poetry run python -m compileall -q . && echo "Success"' 'compileall' "${output_files[compileall]}" "${status_files[compileall]}" +pids+=($!) + +echo "Running pylint" +run_command 'poetry run pylint src' 'pylint' "${output_files[pylint]}" "${status_files[pylint]}" +pids+=($!) + +echo "Running mypy" +run_command 'poetry run mypy src' 'mypy' "${output_files[mypy]}" "${status_files[mypy]}" +pids+=($!) + +echo "Running pyright (optional)" +run_command 'if command -v pyright > /dev/null 2>&1; then pyright src; else echo "pyright not found, skipping"; fi' 'pyright' "${output_files[pyright]}" "${status_files[pyright]}" +pids+=($!) + +# Wait for all processes to complete +echo "Waiting for processes to complete" +for pid in "${pids[@]}"; do + wait "$pid" +done + +# Print output sequentially and check for failures +failed=false +for key in "${!output_files[@]}"; do + echo "--- Output from Command: $key ---" + echo + cat "${output_files[$key]}" + echo # Empty line for separation + echo "--- End of Output from Command: $key ---" + echo + + exit_status=$(cat "${status_files[$key]}") + if [ "$exit_status" -ne 0 ]; then + echo "Command $key failed with exit status $exit_status" >&2 + failed=true + fi +done + +# Clean up temporary files +for tmp_file in "${output_files[@]}" "${status_files[@]}"; do + rm -f "$tmp_file" +done + +if $failed; then + echo "One or more commands failed." >&2 + exit 1 +else + echo "All commands completed successfully." + exit 0 +fi diff --git a/template_variables/scripts/publish.sh b/template_variables/scripts/publish.sh new file mode 100755 index 0000000000..1ee7194cd7 --- /dev/null +++ b/template_variables/scripts/publish.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +export POETRY_PYPI_TOKEN_PYPI=${PYPI_TOKEN} + +poetry publish --build --skip-existing diff --git a/template_variables/setup.py b/template_variables/setup.py deleted file mode 100755 index 59b02d8467..0000000000 --- a/template_variables/setup.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -import setuptools - -try: - with open("README.md", "r") as fh: - long_description = fh.read() -except FileNotFoundError: - long_description = "" - -setuptools.setup( - name="epilot-template-variables", - version="1.2.2", - author="epilot", - description="Python Client SDK for Epilot", - long_description=long_description, - long_description_content_type="text/markdown", - packages=setuptools.find_packages(where="src"), - install_requires=[ - "certifi==2022.12.07", - "charset-normalizer==2.1.1", - "dataclasses-json-speakeasy==0.5.8", - "idna==3.3", - "marshmallow==3.17.1", - "marshmallow-enum==1.5.1", - "mypy-extensions==0.4.3", - "packaging==21.3", - "pyparsing==3.0.9", - "python-dateutil==2.8.2", - "requests==2.28.1", - "six==1.16.0", - "typing-inspect==0.8.0", - "typing_extensions==4.3.0", - "urllib3==1.26.12", - "pylint==2.16.2", - ], - package_dir={'': 'src'}, - python_requires='>=3.9' -) diff --git a/template_variables/src/epilot/__init__.py b/template_variables/src/epilot/__init__.py deleted file mode 100755 index b9e232018a..0000000000 --- a/template_variables/src/epilot/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from .sdk import * diff --git a/template_variables/src/epilot/custom_variables.py b/template_variables/src/epilot/custom_variables.py deleted file mode 100755 index 694b427797..0000000000 --- a/template_variables/src/epilot/custom_variables.py +++ /dev/null @@ -1,170 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -import requests as requests_http -from . import utils -from epilot.models import operations, shared -from typing import Optional - -class CustomVariables: - _client: requests_http.Session - _security_client: requests_http.Session - _server_url: str - _language: str - _sdk_version: str - _gen_version: str - - def __init__(self, client: requests_http.Session, security_client: requests_http.Session, server_url: str, language: str, sdk_version: str, gen_version: str) -> None: - self._client = client - self._security_client = security_client - self._server_url = server_url - self._language = language - self._sdk_version = sdk_version - self._gen_version = gen_version - - def create_custom_variable(self, request: shared.CustomVariable) -> operations.CreateCustomVariableResponse: - r"""Create custom variable - Create custom variable - """ - base_url = self._server_url - - url = base_url.removesuffix('/') + '/v1/custom-variables' - - headers = {} - req_content_type, data, form = utils.serialize_request_body(request, "request", 'json') - if req_content_type not in ('multipart/form-data', 'multipart/mixed'): - headers['content-type'] = req_content_type - - client = self._security_client - - http_res = client.request('POST', url, data=data, files=form, headers=headers) - content_type = http_res.headers.get('Content-Type') - - res = operations.CreateCustomVariableResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) - - if http_res.status_code in [201, 403]: - pass - - return res - - def delete_custom_variable(self, request: operations.DeleteCustomVariableRequest) -> operations.DeleteCustomVariableResponse: - r"""Delete custom variable - Immediately and permanently deletes a custom variable - """ - base_url = self._server_url - - url = utils.generate_url(operations.DeleteCustomVariableRequest, base_url, '/v1/custom-variables/{id}', request) - - - client = self._security_client - - http_res = client.request('DELETE', url) - content_type = http_res.headers.get('Content-Type') - - res = operations.DeleteCustomVariableResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) - - if http_res.status_code in [204, 403]: - pass - - return res - - def get_blue_print_table_config(self) -> operations.GetBluePrintTableConfigResponse: - r"""Get default table config - Get default table config - """ - base_url = self._server_url - - url = base_url.removesuffix('/') + '/v1/custom-variables/order-table-blueprint' - - - client = self._security_client - - http_res = client.request('GET', url) - content_type = http_res.headers.get('Content-Type') - - res = operations.GetBluePrintTableConfigResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) - - if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[shared.CustomVariable]) - res.custom_variable = out - elif http_res.status_code == 403: - pass - - return res - - def get_custom_variable(self, request: operations.GetCustomVariableRequest) -> operations.GetCustomVariableResponse: - r"""Get custom variable - Get custom variable - """ - base_url = self._server_url - - url = utils.generate_url(operations.GetCustomVariableRequest, base_url, '/v1/custom-variables/{id}', request) - - - client = self._security_client - - http_res = client.request('GET', url) - content_type = http_res.headers.get('Content-Type') - - res = operations.GetCustomVariableResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) - - if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[shared.CustomVariable]) - res.custom_variable = out - elif http_res.status_code in [403, 404]: - pass - - return res - - def get_custom_variables(self) -> operations.GetCustomVariablesResponse: - r"""Get custom variables - Get all custom variables of organization - """ - base_url = self._server_url - - url = base_url.removesuffix('/') + '/v1/custom-variables' - - - client = self._security_client - - http_res = client.request('GET', url) - content_type = http_res.headers.get('Content-Type') - - res = operations.GetCustomVariablesResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) - - if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[list[shared.CustomVariable]]) - res.custom_variables = out - elif http_res.status_code == 403: - pass - - return res - - def update_custom_variable(self, request: operations.UpdateCustomVariableRequest) -> operations.UpdateCustomVariableResponse: - r"""Update custom variable - Update custom variable - """ - base_url = self._server_url - - url = utils.generate_url(operations.UpdateCustomVariableRequest, base_url, '/v1/custom-variables/{id}', request) - - headers = {} - req_content_type, data, form = utils.serialize_request_body(request, "custom_variable", 'json') - if req_content_type not in ('multipart/form-data', 'multipart/mixed'): - headers['content-type'] = req_content_type - - client = self._security_client - - http_res = client.request('PUT', url, data=data, files=form, headers=headers) - content_type = http_res.headers.get('Content-Type') - - res = operations.UpdateCustomVariableResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) - - if http_res.status_code in [200, 403]: - pass - - return res - - \ No newline at end of file diff --git a/template_variables/src/epilot/models/__init__.py b/template_variables/src/epilot/models/__init__.py deleted file mode 100755 index 889f8adcf4..0000000000 --- a/template_variables/src/epilot/models/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - diff --git a/template_variables/src/epilot/models/operations/__init__.py b/template_variables/src/epilot/models/operations/__init__.py deleted file mode 100755 index 7a31970483..0000000000 --- a/template_variables/src/epilot/models/operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from .createcustomvariable import * -from .deletecustomvariable import * -from .generateqrcode import * -from .getblueprinttableconfig import * -from .getcategories import * -from .getcustomvariable import * -from .getcustomvariables import * -from .getvariablecontext import * -from .replacetemplates import * -from .searchvariables import * -from .updatecustomvariable import * - -__all__ = ["CreateCustomVariableResponse","DeleteCustomVariableRequest","DeleteCustomVariableResponse","GenerateQRcodeRequest","GenerateQRcodeResponse","GetBluePrintTableConfigResponse","GetCategoriesLangEnum","GetCategoriesRequest","GetCategoriesResponse","GetCustomVariableRequest","GetCustomVariableResponse","GetCustomVariablesResponse","GetVariableContextRequestBody","GetVariableContextResponse","ReplaceTemplates200ApplicationJSON","ReplaceTemplatesRequestBody","ReplaceTemplatesResponse","SearchVariablesRequestBody","SearchVariablesRequestBodyLangEnum","SearchVariablesResponse","UpdateCustomVariableRequest","UpdateCustomVariableResponse"] diff --git a/template_variables/src/epilot/models/operations/createcustomvariable.py b/template_variables/src/epilot/models/operations/createcustomvariable.py deleted file mode 100755 index 8adbc8008e..0000000000 --- a/template_variables/src/epilot/models/operations/createcustomvariable.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -import requests as requests_http -from typing import Optional - - -@dataclasses.dataclass -class CreateCustomVariableResponse: - - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/operations/deletecustomvariable.py b/template_variables/src/epilot/models/operations/deletecustomvariable.py deleted file mode 100755 index 9915f50a3e..0000000000 --- a/template_variables/src/epilot/models/operations/deletecustomvariable.py +++ /dev/null @@ -1,22 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -import requests as requests_http -from typing import Optional - - -@dataclasses.dataclass -class DeleteCustomVariableRequest: - - id: str = dataclasses.field(metadata={'path_param': { 'field_name': 'id', 'style': 'simple', 'explode': False }}) - r"""Custom vairable ID""" - - -@dataclasses.dataclass -class DeleteCustomVariableResponse: - - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/operations/generateqrcode.py b/template_variables/src/epilot/models/operations/generateqrcode.py deleted file mode 100755 index 8e360c8858..0000000000 --- a/template_variables/src/epilot/models/operations/generateqrcode.py +++ /dev/null @@ -1,22 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -import requests as requests_http -from typing import Optional - - -@dataclasses.dataclass -class GenerateQRcodeRequest: - - qrdata: Optional[str] = dataclasses.field(default=None, metadata={'query_param': { 'field_name': 'qrdata', 'style': 'form', 'explode': True }}) - r"""Payload of the QR code""" - - -@dataclasses.dataclass -class GenerateQRcodeResponse: - - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/operations/getblueprinttableconfig.py b/template_variables/src/epilot/models/operations/getblueprinttableconfig.py deleted file mode 100755 index 25afa8caf9..0000000000 --- a/template_variables/src/epilot/models/operations/getblueprinttableconfig.py +++ /dev/null @@ -1,18 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -import requests as requests_http -from ..shared import customvariable as shared_customvariable -from typing import Optional - - -@dataclasses.dataclass -class GetBluePrintTableConfigResponse: - - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - custom_variable: Optional[shared_customvariable.CustomVariable] = dataclasses.field(default=None) - r"""Success""" - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/operations/getcategories.py b/template_variables/src/epilot/models/operations/getcategories.py deleted file mode 100755 index 2dd603e8eb..0000000000 --- a/template_variables/src/epilot/models/operations/getcategories.py +++ /dev/null @@ -1,31 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -import requests as requests_http -from ..shared import categoryresult as shared_categoryresult -from enum import Enum -from typing import Optional - -class GetCategoriesLangEnum(str, Enum): - r"""Language""" - EN = "en" - DE = "de" - - -@dataclasses.dataclass -class GetCategoriesRequest: - - lang: Optional[GetCategoriesLangEnum] = dataclasses.field(default=None, metadata={'query_param': { 'field_name': 'lang', 'style': 'form', 'explode': True }}) - r"""Language""" - - -@dataclasses.dataclass -class GetCategoriesResponse: - - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - category_results: Optional[list[shared_categoryresult.CategoryResult]] = dataclasses.field(default=None) - r"""ok""" - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/operations/getcustomvariable.py b/template_variables/src/epilot/models/operations/getcustomvariable.py deleted file mode 100755 index 7478f617ae..0000000000 --- a/template_variables/src/epilot/models/operations/getcustomvariable.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -import requests as requests_http -from ..shared import customvariable as shared_customvariable -from typing import Optional - - -@dataclasses.dataclass -class GetCustomVariableRequest: - - id: str = dataclasses.field(metadata={'path_param': { 'field_name': 'id', 'style': 'simple', 'explode': False }}) - r"""Custom vairable ID""" - - -@dataclasses.dataclass -class GetCustomVariableResponse: - - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - custom_variable: Optional[shared_customvariable.CustomVariable] = dataclasses.field(default=None) - r"""Success""" - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/operations/getcustomvariables.py b/template_variables/src/epilot/models/operations/getcustomvariables.py deleted file mode 100755 index e3c0c1017f..0000000000 --- a/template_variables/src/epilot/models/operations/getcustomvariables.py +++ /dev/null @@ -1,18 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -import requests as requests_http -from ..shared import customvariable as shared_customvariable -from typing import Optional - - -@dataclasses.dataclass -class GetCustomVariablesResponse: - - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - custom_variables: Optional[list[shared_customvariable.CustomVariable]] = dataclasses.field(default=None) - r"""Success""" - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/operations/getvariablecontext.py b/template_variables/src/epilot/models/operations/getvariablecontext.py deleted file mode 100755 index 2583cc5844..0000000000 --- a/template_variables/src/epilot/models/operations/getvariablecontext.py +++ /dev/null @@ -1,28 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -import requests as requests_http -from ..shared import variablecontext as shared_variablecontext -from ..shared import variableparameters as shared_variableparameters -from dataclasses_json import Undefined, dataclass_json -from epilot import utils -from typing import Optional - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class GetVariableContextRequestBody: - - parameters: Optional[shared_variableparameters.VariableParameters] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('parameters'), 'exclude': lambda f: f is None }}) - - -@dataclasses.dataclass -class GetVariableContextResponse: - - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - variable_context: Optional[shared_variablecontext.VariableContext] = dataclasses.field(default=None) - r"""ok""" - \ No newline at end of file diff --git a/template_variables/src/epilot/models/operations/replacetemplates.py b/template_variables/src/epilot/models/operations/replacetemplates.py deleted file mode 100755 index c8a02e00c1..0000000000 --- a/template_variables/src/epilot/models/operations/replacetemplates.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -import requests as requests_http -from ..shared import variableparameters as shared_variableparameters -from dataclasses_json import Undefined, dataclass_json -from epilot import utils -from typing import Optional - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class ReplaceTemplatesRequestBody: - - inputs: Optional[list[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('inputs'), 'exclude': lambda f: f is None }}) - parameters: Optional[shared_variableparameters.VariableParameters] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('parameters'), 'exclude': lambda f: f is None }}) - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class ReplaceTemplates200ApplicationJSON: - r"""ok""" - - outputs: Optional[list[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('outputs'), 'exclude': lambda f: f is None }}) - - -@dataclasses.dataclass -class ReplaceTemplatesResponse: - - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - replace_templates_200_application_json_object: Optional[ReplaceTemplates200ApplicationJSON] = dataclasses.field(default=None) - r"""ok""" - \ No newline at end of file diff --git a/template_variables/src/epilot/models/operations/searchvariables.py b/template_variables/src/epilot/models/operations/searchvariables.py deleted file mode 100755 index 26ceb11e96..0000000000 --- a/template_variables/src/epilot/models/operations/searchvariables.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -import requests as requests_http -from ..shared import templatetype_enum as shared_templatetype_enum -from ..shared import variableresult as shared_variableresult -from dataclasses_json import Undefined, dataclass_json -from enum import Enum -from epilot import utils -from typing import Optional - -class SearchVariablesRequestBodyLangEnum(str, Enum): - EN = "en" - DE = "de" - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class SearchVariablesRequestBody: - - query: str = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('query') }}) - r"""Search string""" - template_type: shared_templatetype_enum.TemplateTypeEnum = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template_type') }}) - entity_schemas: Optional[list[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('entity_schemas'), 'exclude': lambda f: f is None }}) - from_: Optional[int] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('from'), 'exclude': lambda f: f is None }}) - lang: Optional[SearchVariablesRequestBodyLangEnum] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('lang'), 'exclude': lambda f: f is None }}) - size: Optional[int] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('size'), 'exclude': lambda f: f is None }}) - - -@dataclasses.dataclass -class SearchVariablesResponse: - - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - variable_results: Optional[list[shared_variableresult.VariableResult]] = dataclasses.field(default=None) - r"""ok""" - \ No newline at end of file diff --git a/template_variables/src/epilot/models/operations/updatecustomvariable.py b/template_variables/src/epilot/models/operations/updatecustomvariable.py deleted file mode 100755 index ddc0124e09..0000000000 --- a/template_variables/src/epilot/models/operations/updatecustomvariable.py +++ /dev/null @@ -1,24 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -import requests as requests_http -from ..shared import customvariable as shared_customvariable -from typing import Optional - - -@dataclasses.dataclass -class UpdateCustomVariableRequest: - - id: str = dataclasses.field(metadata={'path_param': { 'field_name': 'id', 'style': 'simple', 'explode': False }}) - r"""Custom variable ID""" - custom_variable: Optional[shared_customvariable.CustomVariable] = dataclasses.field(default=None, metadata={'request': { 'media_type': 'application/json' }}) - - -@dataclasses.dataclass -class UpdateCustomVariableResponse: - - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/shared/__init__.py b/template_variables/src/epilot/models/shared/__init__.py deleted file mode 100755 index ec472dceb4..0000000000 --- a/template_variables/src/epilot/models/shared/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from .categoryresult import * -from .customvariable import * -from .externalcustomvariable import * -from .security import * -from .templatetype_enum import * -from .variablecontext import * -from .variableparameters import * -from .variableresult import * - -__all__ = ["CategoryResult","CustomVariable","CustomVariableTypeEnum","ExternalCustomVariable","Security","TemplateTypeEnum","VariableContext","VariableParameters","VariableParametersLanguageEnum","VariableResult","VariableResultTypeEnum"] diff --git a/template_variables/src/epilot/models/shared/categoryresult.py b/template_variables/src/epilot/models/shared/categoryresult.py deleted file mode 100755 index 77ca5f503c..0000000000 --- a/template_variables/src/epilot/models/shared/categoryresult.py +++ /dev/null @@ -1,16 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -from dataclasses_json import Undefined, dataclass_json -from epilot import utils -from typing import Optional - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class CategoryResult: - - category: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('category'), 'exclude': lambda f: f is None }}) - description: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('description'), 'exclude': lambda f: f is None }}) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/shared/customvariable.py b/template_variables/src/epilot/models/shared/customvariable.py deleted file mode 100755 index 77da1887fb..0000000000 --- a/template_variables/src/epilot/models/shared/customvariable.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -from dataclasses_json import Undefined, dataclass_json -from enum import Enum -from epilot import utils -from typing import Any, Optional - -class CustomVariableTypeEnum(str, Enum): - r"""Custom variable type""" - ORDER_TABLE = "order_table" - CUSTOM = "custom" - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class CustomVariable: - r"""Success""" - - config: Optional[dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('config'), 'exclude': lambda f: f is None }}) - r"""Variable configuration""" - created_at: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('created_at'), 'exclude': lambda f: f is None }}) - r"""Creation time""" - created_by: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('created_by'), 'exclude': lambda f: f is None }}) - r"""Created by""" - helper_logic: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('helper_logic'), 'exclude': lambda f: f is None }}) - r"""The helper function logic""" - helper_params: Optional[list[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('helper_params'), 'exclude': lambda f: f is None }}) - r"""The helper function parameter's names""" - id: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('id'), 'exclude': lambda f: f is None }}) - r"""ID""" - key: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('key'), 'exclude': lambda f: f is None }}) - r"""The key which is used for Handlebar variable syntax {{key}}""" - name: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('name'), 'exclude': lambda f: f is None }}) - r"""Custom variable name""" - template: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template'), 'exclude': lambda f: f is None }}) - r"""Handlebar template that used to generate the variable content""" - type: Optional[CustomVariableTypeEnum] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('type'), 'exclude': lambda f: f is None }}) - r"""Custom variable type""" - updated_at: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('updated_at'), 'exclude': lambda f: f is None }}) - r"""Last update time""" - updated_by: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('updated_by'), 'exclude': lambda f: f is None }}) - r"""Updated by""" - \ No newline at end of file diff --git a/template_variables/src/epilot/models/shared/externalcustomvariable.py b/template_variables/src/epilot/models/shared/externalcustomvariable.py deleted file mode 100755 index fe478c518a..0000000000 --- a/template_variables/src/epilot/models/shared/externalcustomvariable.py +++ /dev/null @@ -1,16 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -from dataclasses_json import Undefined, dataclass_json -from epilot import utils -from typing import Optional - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class ExternalCustomVariable: - - value: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('value'), 'exclude': lambda f: f is None }}) - variable: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('variable'), 'exclude': lambda f: f is None }}) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/shared/security.py b/template_variables/src/epilot/models/shared/security.py deleted file mode 100755 index cca0d01c8a..0000000000 --- a/template_variables/src/epilot/models/shared/security.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses - - -@dataclasses.dataclass -class Security: - - epilot_auth: str = dataclasses.field(metadata={'security': { 'scheme': True, 'type': 'http', 'sub_type': 'bearer', 'field_name': 'Authorization' }}) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/shared/templatetype_enum.py b/template_variables/src/epilot/models/shared/templatetype_enum.py deleted file mode 100755 index b584f7dcbb..0000000000 --- a/template_variables/src/epilot/models/shared/templatetype_enum.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -from enum import Enum - -class TemplateTypeEnum(str, Enum): - EMAIL = "email" - DOCUMENT = "document" diff --git a/template_variables/src/epilot/models/shared/variablecontext.py b/template_variables/src/epilot/models/shared/variablecontext.py deleted file mode 100755 index c1b1dfb924..0000000000 --- a/template_variables/src/epilot/models/shared/variablecontext.py +++ /dev/null @@ -1,19 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -from dataclasses_json import Undefined, dataclass_json -from epilot import utils -from typing import Any, Optional - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class VariableContext: - r"""ok""" - - brand: Optional[dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('brand'), 'exclude': lambda f: f is None }}) - contact: Optional[dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('contact'), 'exclude': lambda f: f is None }}) - main: Optional[dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('main'), 'exclude': lambda f: f is None }}) - unsubscribe_url: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('unsubscribe_url'), 'exclude': lambda f: f is None }}) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/shared/variableparameters.py b/template_variables/src/epilot/models/shared/variableparameters.py deleted file mode 100755 index 46b36be3f1..0000000000 --- a/template_variables/src/epilot/models/shared/variableparameters.py +++ /dev/null @@ -1,37 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -from ..shared import externalcustomvariable as shared_externalcustomvariable -from ..shared import templatetype_enum as shared_templatetype_enum -from dataclasses_json import Undefined, dataclass_json -from enum import Enum -from epilot import utils -from typing import Any, Optional - -class VariableParametersLanguageEnum(str, Enum): - EN = "en" - DE = "de" - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class VariableParameters: - - template_type: shared_templatetype_enum.TemplateTypeEnum = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template_type') }}) - brand_id: Optional[float] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('brand_id'), 'exclude': lambda f: f is None }}) - r"""Brand ID""" - context_data: Optional[dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('context_data'), 'exclude': lambda f: f is None }}) - r"""If context data is avaialble, this data will be used for variable replace.""" - custom_variables: Optional[list[shared_externalcustomvariable.ExternalCustomVariable]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('custom_variables'), 'exclude': lambda f: f is None }}) - r"""Custom variables with specified values form other services.""" - language: Optional[VariableParametersLanguageEnum] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('language'), 'exclude': lambda f: f is None }}) - main_entity_id: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('main_entity_id'), 'exclude': lambda f: f is None }}) - r"""The main entity ID. Use main entity in order to use the variable without schema slug prefix - or just pass directly to other object ID.""" - template_name: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template_name'), 'exclude': lambda f: f is None }}) - r"""The name of email template""" - template_tags: Optional[list[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template_tags'), 'exclude': lambda f: f is None }}) - r"""The tags of email template""" - user_id: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('user_id'), 'exclude': lambda f: f is None }}) - r"""User ID""" - \ No newline at end of file diff --git a/template_variables/src/epilot/models/shared/variableresult.py b/template_variables/src/epilot/models/shared/variableresult.py deleted file mode 100755 index d616a0d89d..0000000000 --- a/template_variables/src/epilot/models/shared/variableresult.py +++ /dev/null @@ -1,28 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -from dataclasses_json import Undefined, dataclass_json -from enum import Enum -from epilot import utils -from typing import Optional - -class VariableResultTypeEnum(str, Enum): - SIMPLE = "simple" - PARTIAL = "partial" - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class VariableResult: - - description: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('description'), 'exclude': lambda f: f is None }}) - r"""Variable description""" - group: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('group'), 'exclude': lambda f: f is None }}) - r"""Variable group""" - insert: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('insert'), 'exclude': lambda f: f is None }}) - r"""The value which is used to insert to template""" - qrdata: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('qrdata'), 'exclude': lambda f: f is None }}) - r"""Payload for the QR data""" - type: Optional[VariableResultTypeEnum] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('type'), 'exclude': lambda f: f is None }}) - \ No newline at end of file diff --git a/template_variables/src/epilot/sdk.py b/template_variables/src/epilot/sdk.py deleted file mode 100755 index 53ea97cd11..0000000000 --- a/template_variables/src/epilot/sdk.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -import requests as requests_http -from . import utils -from .custom_variables import CustomVariables -from .variables import Variables -from epilot.models import shared - -SERVERS = [ - "https://template-variables-api.sls.epilot.io", -] -"""Contains the list of servers available to the SDK""" - -class Epilot: - r"""API to provide variables for email and document templates.""" - custom_variables: CustomVariables - variables: Variables - r"""Variables""" - - _client: requests_http.Session - _security_client: requests_http.Session - _server_url: str = SERVERS[0] - _language: str = "python" - _sdk_version: str = "1.2.2" - _gen_version: str = "2.16.5" - - def __init__(self, - security: shared.Security = None, - server_url: str = None, - url_params: dict[str, str] = None, - client: requests_http.Session = None - ) -> None: - """Instantiates the SDK configuring it with the provided parameters. - - :param security: The security details required for authentication - :type security: shared.Security - :param server_url: The server URL to use for all operations - :type server_url: str - :param url_params: Parameters to optionally template the server URL with - :type url_params: dict[str, str] - :param client: The requests.Session HTTP client to use for all operations - :type client: requests_http.Session - """ - self._client = requests_http.Session() - - - if server_url is not None: - if url_params is not None: - self._server_url = utils.template_url(server_url, url_params) - else: - self._server_url = server_url - - if client is not None: - self._client = client - - self._security_client = utils.configure_security_client(self._client, security) - - - self._init_sdks() - - def _init_sdks(self): - self.custom_variables = CustomVariables( - self._client, - self._security_client, - self._server_url, - self._language, - self._sdk_version, - self._gen_version - ) - - self.variables = Variables( - self._client, - self._security_client, - self._server_url, - self._language, - self._sdk_version, - self._gen_version - ) - - \ No newline at end of file diff --git a/template_variables/src/epilot/utils/__init__.py b/template_variables/src/epilot/utils/__init__.py deleted file mode 100755 index 94b739857f..0000000000 --- a/template_variables/src/epilot/utils/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from .retries import * -from .utils import * diff --git a/template_variables/src/epilot/utils/retries.py b/template_variables/src/epilot/utils/retries.py deleted file mode 100755 index c6251d948e..0000000000 --- a/template_variables/src/epilot/utils/retries.py +++ /dev/null @@ -1,118 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -import random -import time - -import requests - - -class BackoffStrategy: - initial_interval: int - max_interval: int - exponent: float - max_elapsed_time: int - - def __init__(self, initial_interval: int, max_interval: int, exponent: float, max_elapsed_time: int): - self.initial_interval = initial_interval - self.max_interval = max_interval - self.exponent = exponent - self.max_elapsed_time = max_elapsed_time - - -class RetryConfig: - strategy: str - backoff: BackoffStrategy - retry_connection_errors: bool - - def __init__(self, strategy: str, retry_connection_errors: bool): - self.strategy = strategy - self.retry_connection_errors = retry_connection_errors - - -class Retries: - config: RetryConfig - status_codes: list[str] - - def __init__(self, config: RetryConfig, status_codes: list[str]): - self.config = config - self.status_codes = status_codes - - -class TemporaryError(Exception): - response: requests.Response - - def __init__(self, response: requests.Response): - self.response = response - - -class PermanentError(Exception): - inner: Exception - - def __init__(self, inner: Exception): - self.inner = inner - - -def retry(func, retries: Retries): - if retries.config.strategy == 'backoff': - def do_request(): - res: requests.Response - try: - res = func() - - for code in retries.status_codes: - if "X" in code.upper(): - code_range = int(code[0]) - - status_major = res.status_code / 100 - - if status_major >= code_range and status_major < code_range + 1: - raise TemporaryError(res) - else: - parsed_code = int(code) - - if res.status_code == parsed_code: - raise TemporaryError(res) - except requests.exceptions.ConnectionError as exception: - if not retries.config.config.retry_connection_errors: - raise - - raise PermanentError(exception) from exception - except requests.exceptions.Timeout as exception: - if not retries.config.config.retry_connection_errors: - raise - - raise PermanentError(exception) from exception - except TemporaryError: - raise - except Exception as exception: - raise PermanentError(exception) from exception - - return res - - return retry_with_backoff(do_request, retries.config.backoff.initial_interval, retries.config.backoff.max_interval, retries.config.backoff.exponent, retries.config.backoff.max_elapsed_time) - - return func() - - -def retry_with_backoff(func, initial_interval=500, max_interval=60000, exponent=1.5, max_elapsed_time=3600000): - start = round(time.time()*1000) - retries = 0 - - while True: - try: - return func() - except PermanentError as exception: - raise exception.inner - except Exception as exception: # pylint: disable=broad-exception-caught - now = round(time.time()*1000) - if now - start > max_elapsed_time: - if isinstance(exception, TemporaryError): - return exception.response - - raise - sleep = ((initial_interval/1000) * - exponent**retries + random.uniform(0, 1)) - if sleep > max_interval/1000: - sleep = max_interval/1000 - time.sleep(sleep) - retries += 1 diff --git a/template_variables/src/epilot/utils/utils.py b/template_variables/src/epilot/utils/utils.py deleted file mode 100755 index 9d4fba3248..0000000000 --- a/template_variables/src/epilot/utils/utils.py +++ /dev/null @@ -1,735 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -import base64 -import json -import re -from dataclasses import Field, dataclass, fields, is_dataclass, make_dataclass -from datetime import date, datetime -from email.message import Message -from enum import Enum -from typing import Any, Callable, Optional, Tuple, Union, get_args, get_origin -from xmlrpc.client import boolean - -import dateutil.parser -import requests -from dataclasses_json import DataClassJsonMixin - - -class SecurityClient: - client: requests.Session - query_params: dict[str, str] = {} - - def __init__(self, client: requests.Session): - self.client = client - - def request(self, method, url, **kwargs): - params = kwargs.get('params', {}) - kwargs["params"] = self.query_params | params - - return self.client.request(method, url, **kwargs) - - -def configure_security_client(client: requests.Session, security: dataclass): - client = SecurityClient(client) - - if security is None: - return client - - sec_fields: Tuple[Field, ...] = fields(security) - for sec_field in sec_fields: - value = getattr(security, sec_field.name) - if value is None: - continue - - metadata = sec_field.metadata.get('security') - if metadata is None: - continue - if metadata.get('option'): - _parse_security_option(client, value) - return client - if metadata.get('scheme'): - # Special case for basic auth which could be a flattened struct - if metadata.get("sub_type") == "basic" and not is_dataclass(value): - _parse_security_scheme(client, metadata, security) - else: - _parse_security_scheme(client, metadata, value) - - return client - - -def _parse_security_option(client: SecurityClient, option: dataclass): - opt_fields: Tuple[Field, ...] = fields(option) - for opt_field in opt_fields: - metadata = opt_field.metadata.get('security') - if metadata is None or metadata.get('scheme') is None: - continue - _parse_security_scheme( - client, metadata, getattr(option, opt_field.name)) - - -def _parse_security_scheme(client: SecurityClient, scheme_metadata: dict, scheme: any): - scheme_type = scheme_metadata.get('type') - sub_type = scheme_metadata.get('sub_type') - - if is_dataclass(scheme): - if scheme_type == 'http' and sub_type == 'basic': - _parse_basic_auth_scheme(client, scheme) - return - - scheme_fields: Tuple[Field, ...] = fields(scheme) - for scheme_field in scheme_fields: - metadata = scheme_field.metadata.get('security') - if metadata is None or metadata.get('field_name') is None: - continue - - value = getattr(scheme, scheme_field.name) - - _parse_security_scheme_value( - client, scheme_metadata, metadata, value) - else: - _parse_security_scheme_value( - client, scheme_metadata, scheme_metadata, scheme) - - -def _parse_security_scheme_value(client: SecurityClient, scheme_metadata: dict, security_metadata: dict, value: any): - scheme_type = scheme_metadata.get('type') - sub_type = scheme_metadata.get('sub_type') - - header_name = security_metadata.get('field_name') - - if scheme_type == "apiKey": - if sub_type == 'header': - client.client.headers[header_name] = value - elif sub_type == 'query': - client.query_params[header_name] = value - elif sub_type == 'cookie': - client.client.cookies[header_name] = value - else: - raise Exception('not supported') - elif scheme_type == "openIdConnect": - client.client.headers[header_name] = value - elif scheme_type == 'oauth2': - client.client.headers[header_name] = value - elif scheme_type == 'http': - if sub_type == 'bearer': - client.client.headers[header_name] = value - else: - raise Exception('not supported') - else: - raise Exception('not supported') - - -def _parse_basic_auth_scheme(client: SecurityClient, scheme: dataclass): - username = "" - password = "" - - scheme_fields: Tuple[Field, ...] = fields(scheme) - for scheme_field in scheme_fields: - metadata = scheme_field.metadata.get('security') - if metadata is None or metadata.get('field_name') is None: - continue - - field_name = metadata.get('field_name') - value = getattr(scheme, scheme_field.name) - - if field_name == 'username': - username = value - if field_name == 'password': - password = value - - data = f'{username}:{password}'.encode() - client.client.headers['Authorization'] = f'Basic {base64.b64encode(data).decode()}' - - -def generate_url(clazz: type, server_url: str, path: str, path_params: dataclass, gbls: dict[str, dict[str, dict[str, Any]]] = None) -> str: - path_param_fields: Tuple[Field, ...] = fields(clazz) - for field in path_param_fields: - request_metadata = field.metadata.get('request') - if request_metadata is not None: - continue - - param_metadata = field.metadata.get('path_param') - if param_metadata is None: - continue - - if param_metadata.get('style', 'simple') == 'simple': - param = getattr( - path_params, field.name) if path_params is not None else None - param = _populate_from_globals( - field.name, param, 'pathParam', gbls) - - if param is None: - continue - - if isinstance(param, list): - pp_vals: list[str] = [] - for pp_val in param: - if pp_val is None: - continue - pp_vals.append(_val_to_string(pp_val)) - path = path.replace( - '{' + param_metadata.get('field_name', field.name) + '}', ",".join(pp_vals), 1) - elif isinstance(param, dict): - pp_vals: list[str] = [] - for pp_key in param: - if param[pp_key] is None: - continue - if param_metadata.get('explode'): - pp_vals.append( - f"{pp_key}={_val_to_string(param[pp_key])}") - else: - pp_vals.append( - f"{pp_key},{_val_to_string(param[pp_key])}") - path = path.replace( - '{' + param_metadata.get('field_name', field.name) + '}', ",".join(pp_vals), 1) - elif not isinstance(param, (str, int, float, complex, bool)): - pp_vals: list[str] = [] - param_fields: Tuple[Field, ...] = fields(param) - for param_field in param_fields: - param_value_metadata = param_field.metadata.get( - 'path_param') - if not param_value_metadata: - continue - - parm_name = param_value_metadata.get( - 'field_name', field.name) - - param_field_val = getattr(param, param_field.name) - if param_field_val is None: - continue - if param_metadata.get('explode'): - pp_vals.append( - f"{parm_name}={_val_to_string(param_field_val)}") - else: - pp_vals.append( - f"{parm_name},{_val_to_string(param_field_val)}") - path = path.replace( - '{' + param_metadata.get('field_name', field.name) + '}', ",".join(pp_vals), 1) - else: - path = path.replace( - '{' + param_metadata.get('field_name', field.name) + '}', _val_to_string(param), 1) - - return server_url.removesuffix("/") + path - - -def is_optional(field): - return get_origin(field) is Union and type(None) in get_args(field) - - -def template_url(url_with_params: str, params: dict[str, str]) -> str: - for key, value in params.items(): - url_with_params = url_with_params.replace( - '{' + key + '}', value) - - return url_with_params - - -def get_query_params(clazz: type, query_params: dataclass, gbls: dict[str, dict[str, dict[str, Any]]] = None) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} - - param_fields: Tuple[Field, ...] = fields(clazz) - for field in param_fields: - request_metadata = field.metadata.get('request') - if request_metadata is not None: - continue - - metadata = field.metadata.get('query_param') - if not metadata: - continue - - param_name = field.name - value = getattr( - query_params, param_name) if query_params is not None else None - - value = _populate_from_globals(param_name, value, 'queryParam', gbls) - - f_name = metadata.get("field_name") - serialization = metadata.get('serialization', '') - if serialization != '': - params = params | _get_serialized_query_params( - metadata, f_name, value) - else: - style = metadata.get('style', 'form') - if style == 'deepObject': - params = params | _get_deep_object_query_params( - metadata, f_name, value) - elif style == 'form': - params = params | _get_form_query_params( - metadata, f_name, value) - else: - raise Exception('not yet implemented') - return params - - -def get_headers(headers_params: dataclass) -> dict[str, str]: - if headers_params is None: - return {} - - headers: dict[str, str] = {} - - param_fields: Tuple[Field, ...] = fields(headers_params) - for field in param_fields: - metadata = field.metadata.get('header') - if not metadata: - continue - - value = _serialize_header(metadata.get( - 'explode', False), getattr(headers_params, field.name)) - - if value != '': - headers[metadata.get('field_name', field.name)] = value - - return headers - - -def _get_serialized_query_params(metadata: dict, field_name: str, obj: any) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} - - serialization = metadata.get('serialization', '') - if serialization == 'json': - params[metadata.get("field_name", field_name)] = marshal_json(obj) - - return params - - -def _get_deep_object_query_params(metadata: dict, field_name: str, obj: any) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} - - if obj is None: - return params - - if is_dataclass(obj): - obj_fields: Tuple[Field, ...] = fields(obj) - for obj_field in obj_fields: - obj_param_metadata = obj_field.metadata.get('query_param') - if not obj_param_metadata: - continue - - obj_val = getattr(obj, obj_field.name) - if obj_val is None: - continue - - if isinstance(obj_val, list): - for val in obj_val: - if val is None: - continue - - if params.get(f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]') is None: - params[f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]'] = [ - ] - - params[ - f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]'].append(_val_to_string(val)) - else: - params[ - f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]'] = [ - _val_to_string(obj_val)] - elif isinstance(obj, dict): - for key, value in obj.items(): - if value is None: - continue - - if isinstance(value, list): - for val in value: - if val is None: - continue - - if params.get(f'{metadata.get("field_name", field_name)}[{key}]') is None: - params[f'{metadata.get("field_name", field_name)}[{key}]'] = [ - ] - - params[ - f'{metadata.get("field_name", field_name)}[{key}]'].append(_val_to_string(val)) - else: - params[f'{metadata.get("field_name", field_name)}[{key}]'] = [ - _val_to_string(value)] - return params - - -def _get_query_param_field_name(obj_field: Field) -> str: - obj_param_metadata = obj_field.metadata.get('query_param') - - if not obj_param_metadata: - return "" - - return obj_param_metadata.get("field_name", obj_field.name) - - -def _get_form_query_params(metadata: dict, field_name: str, obj: any) -> dict[str, list[str]]: - return _populate_form(field_name, metadata.get("explode", True), obj, _get_query_param_field_name) - - -SERIALIZATION_METHOD_TO_CONTENT_TYPE = { - 'json': 'application/json', - 'form': 'application/x-www-form-urlencoded', - 'multipart': 'multipart/form-data', - 'raw': 'application/octet-stream', - 'string': 'text/plain', -} - - -def serialize_request_body(request: dataclass, request_field_name: str, serialization_method: str) -> Tuple[str, any, any]: - if request is None: - return None, None, None, None - - if not is_dataclass(request) or not hasattr(request, request_field_name): - return serialize_content_type(request_field_name, SERIALIZATION_METHOD_TO_CONTENT_TYPE[serialization_method], request) - - request_val = getattr(request, request_field_name) - - request_fields: Tuple[Field, ...] = fields(request) - request_metadata = None - - for field in request_fields: - if field.name == request_field_name: - request_metadata = field.metadata.get('request') - break - - if request_metadata is None: - raise Exception('invalid request type') - - return serialize_content_type(request_field_name, request_metadata.get('media_type', 'application/octet-stream'), request_val) - - -def serialize_content_type(field_name: str, media_type: str, request: dataclass) -> Tuple[str, any, list[list[any]]]: - if re.match(r'(application|text)\/.*?\+*json.*', media_type) is not None: - return media_type, marshal_json(request), None - if re.match(r'multipart\/.*', media_type) is not None: - return serialize_multipart_form(media_type, request) - if re.match(r'application\/x-www-form-urlencoded.*', media_type) is not None: - return media_type, serialize_form_data(field_name, request), None - if isinstance(request, (bytes, bytearray)): - return media_type, request, None - if isinstance(request, str): - return media_type, request, None - - raise Exception( - f"invalid request body type {type(request)} for mediaType {media_type}") - - -def serialize_multipart_form(media_type: str, request: dataclass) -> Tuple[str, any, list[list[any]]]: - form: list[list[any]] = [] - request_fields = fields(request) - - for field in request_fields: - val = getattr(request, field.name) - if val is None: - continue - - field_metadata = field.metadata.get('multipart_form') - if not field_metadata: - continue - - if field_metadata.get("file") is True: - file_fields = fields(val) - - file_name = "" - field_name = "" - content = bytes() - - for file_field in file_fields: - file_metadata = file_field.metadata.get('multipart_form') - if file_metadata is None: - continue - - if file_metadata.get("content") is True: - content = getattr(val, file_field.name) - else: - field_name = file_metadata.get( - "field_name", file_field.name) - file_name = getattr(val, file_field.name) - if field_name == "" or file_name == "" or content == bytes(): - raise Exception('invalid multipart/form-data file') - - form.append([field_name, [file_name, content]]) - elif field_metadata.get("json") is True: - to_append = [field_metadata.get("field_name", field.name), [ - None, marshal_json(val), "application/json"]] - form.append(to_append) - else: - field_name = field_metadata.get( - "field_name", field.name) - if isinstance(val, list): - for value in val: - if value is None: - continue - form.append( - [field_name + "[]", [None, _val_to_string(value)]]) - else: - form.append([field_name, [None, _val_to_string(val)]]) - return media_type, None, form - - -def serialize_dict(original: dict, explode: bool, field_name, existing: Optional[dict[str, list[str]]]) -> dict[ - str, list[str]]: - if existing is None: - existing = [] - - if explode is True: - for key, val in original.items(): - if key not in existing: - existing[key] = [] - existing[key].append(val) - else: - temp = [] - for key, val in original.items(): - temp.append(str(key)) - temp.append(str(val)) - if field_name not in existing: - existing[field_name] = [] - existing[field_name].append(",".join(temp)) - return existing - - -def serialize_form_data(field_name: str, data: dataclass) -> dict[str, any]: - form: dict[str, list[str]] = {} - - if is_dataclass(data): - for field in fields(data): - val = getattr(data, field.name) - if val is None: - continue - - metadata = field.metadata.get('form') - if metadata is None: - continue - - field_name = metadata.get('field_name', field.name) - - if metadata.get('json'): - form[field_name] = [marshal_json(val)] - else: - if metadata.get('style', 'form') == 'form': - form = form | _populate_form( - field_name, metadata.get('explode', True), val, _get_form_field_name) - else: - raise Exception( - f'Invalid form style for field {field.name}') - elif isinstance(data, dict): - for key, value in data.items(): - form[key] = [_val_to_string(value)] - else: - raise Exception(f'Invalid request body type for field {field_name}') - - return form - - -def _get_form_field_name(obj_field: Field) -> str: - obj_param_metadata = obj_field.metadata.get('form') - - if not obj_param_metadata: - return "" - - return obj_param_metadata.get("field_name", obj_field.name) - - -def _populate_form(field_name: str, explode: boolean, obj: any, get_field_name_func: Callable) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} - - if obj is None: - return params - - if is_dataclass(obj): - items = [] - - obj_fields: Tuple[Field, ...] = fields(obj) - for obj_field in obj_fields: - obj_field_name = get_field_name_func(obj_field) - if obj_field_name == '': - continue - - val = getattr(obj, obj_field.name) - if val is None: - continue - - if explode: - params[obj_field_name] = [_val_to_string(val)] - else: - items.append( - f'{obj_field_name},{_val_to_string(val)}') - - if len(items) > 0: - params[field_name] = [','.join(items)] - elif isinstance(obj, dict): - items = [] - for key, value in obj.items(): - if value is None: - continue - - if explode: - params[key] = _val_to_string(value) - else: - items.append(f'{key},{_val_to_string(value)}') - - if len(items) > 0: - params[field_name] = [','.join(items)] - elif isinstance(obj, list): - items = [] - - for value in obj: - if value is None: - continue - - if explode: - if not field_name in params: - params[field_name] = [] - params[field_name].append(_val_to_string(value)) - else: - items.append(_val_to_string(value)) - - if len(items) > 0: - params[field_name] = [','.join([str(item) for item in items])] - else: - params[field_name] = [_val_to_string(obj)] - - return params - - -def _serialize_header(explode: bool, obj: any) -> str: - if obj is None: - return '' - - if is_dataclass(obj): - items = [] - obj_fields: Tuple[Field, ...] = fields(obj) - for obj_field in obj_fields: - obj_param_metadata = obj_field.metadata.get('header') - - if not obj_param_metadata: - continue - - obj_field_name = obj_param_metadata.get( - 'field_name', obj_field.name) - if obj_field_name == '': - continue - - val = getattr(obj, obj_field.name) - if val is None: - continue - - if explode: - items.append( - f'{obj_field_name}={_val_to_string(val)}') - else: - items.append(obj_field_name) - items.append(_val_to_string(val)) - - if len(items) > 0: - return ','.join(items) - elif isinstance(obj, dict): - items = [] - - for key, value in obj.items(): - if value is None: - continue - - if explode: - items.append(f'{key}={_val_to_string(value)}') - else: - items.append(key) - items.append(_val_to_string(value)) - - if len(items) > 0: - return ','.join([str(item) for item in items]) - elif isinstance(obj, list): - items = [] - - for value in obj: - if value is None: - continue - - items.append(_val_to_string(value)) - - if len(items) > 0: - return ','.join(items) - else: - return f'{_val_to_string(obj)}' - - return '' - - -def unmarshal_json(data, typ): - unmarhsal = make_dataclass('Unmarhsal', [('res', typ)], - bases=(DataClassJsonMixin,)) - json_dict = json.loads(data) - out = unmarhsal.from_dict({"res": json_dict}) - return out.res - - -def marshal_json(val): - marshal = make_dataclass('Marshal', [('res', type(val))], - bases=(DataClassJsonMixin,)) - marshaller = marshal(res=val) - json_dict = marshaller.to_dict() - return json.dumps(json_dict["res"]) - - -def match_content_type(content_type: str, pattern: str) -> boolean: - if pattern in (content_type, "*", "*/*"): - return True - - msg = Message() - msg['content-type'] = content_type - media_type = msg.get_content_type() - - if media_type == pattern: - return True - - parts = media_type.split("/") - if len(parts) == 2: - if pattern in (f'{parts[0]}/*', f'*/{parts[1]}'): - return True - - return False - - -def datetimeisoformat(optional: bool): - def isoformatoptional(val): - if optional and val is None: - return None - return _val_to_string(val) - - return isoformatoptional - - -def dateisoformat(optional: bool): - def isoformatoptional(val): - if optional and val is None: - return None - return date.isoformat(val) - - return isoformatoptional - - -def datefromisoformat(date_str: str): - return dateutil.parser.parse(date_str).date() - - -def get_field_name(name): - def override(_, _field_name=name): - return _field_name - - return override - - -def _val_to_string(val): - if isinstance(val, bool): - return str(val).lower() - if isinstance(val, datetime): - return val.isoformat().replace('+00:00', 'Z') - if isinstance(val, Enum): - return val.value - - return str(val) - - -def _populate_from_globals(param_name: str, value: any, param_type: str, gbls: dict[str, dict[str, dict[str, Any]]]): - if value is None and gbls is not None: - if 'parameters' in gbls: - if param_type in gbls['parameters']: - if param_name in gbls['parameters'][param_type]: - global_value = gbls['parameters'][param_type][param_name] - if global_value is not None: - value = global_value - - return value diff --git a/template_variables/src/epilot/variables.py b/template_variables/src/epilot/variables.py deleted file mode 100755 index 0158755ddd..0000000000 --- a/template_variables/src/epilot/variables.py +++ /dev/null @@ -1,158 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -import requests as requests_http -from . import utils -from epilot.models import operations, shared -from typing import Optional - -class Variables: - r"""Variables""" - _client: requests_http.Session - _security_client: requests_http.Session - _server_url: str - _language: str - _sdk_version: str - _gen_version: str - - def __init__(self, client: requests_http.Session, security_client: requests_http.Session, server_url: str, language: str, sdk_version: str, gen_version: str) -> None: - self._client = client - self._security_client = security_client - self._server_url = server_url - self._language = language - self._sdk_version = sdk_version - self._gen_version = gen_version - - def generate_q_rcode(self, request: operations.GenerateQRcodeRequest) -> operations.GenerateQRcodeResponse: - r"""generateQRcode - Generate QR Code for the given payload - """ - base_url = self._server_url - - url = base_url.removesuffix('/') + '/v1/template-variables/qrcode:generate' - - query_params = utils.get_query_params(operations.GenerateQRcodeRequest, request) - - client = self._security_client - - http_res = client.request('GET', url, params=query_params) - content_type = http_res.headers.get('Content-Type') - - res = operations.GenerateQRcodeResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) - - if http_res.status_code == 200: - pass - - return res - - def get_categories(self, request: operations.GetCategoriesRequest) -> operations.GetCategoriesResponse: - r"""getCategories - Get all template variable categories - """ - base_url = self._server_url - - url = base_url.removesuffix('/') + '/v1/template-variables/categories' - - query_params = utils.get_query_params(operations.GetCategoriesRequest, request) - - client = self._security_client - - http_res = client.request('GET', url, params=query_params) - content_type = http_res.headers.get('Content-Type') - - res = operations.GetCategoriesResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) - - if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[list[shared.CategoryResult]]) - res.category_results = out - - return res - - def get_variable_context(self, request: operations.GetVariableContextRequestBody) -> operations.GetVariableContextResponse: - r"""getVariableContext - Get full variable context - - Calls Entity API, User API, Brand API and others to construct full context object used for template variable replace - - """ - base_url = self._server_url - - url = base_url.removesuffix('/') + '/v1/template-variables:context' - - headers = {} - req_content_type, data, form = utils.serialize_request_body(request, "request", 'json') - if req_content_type not in ('multipart/form-data', 'multipart/mixed'): - headers['content-type'] = req_content_type - - client = self._security_client - - http_res = client.request('POST', url, data=data, files=form, headers=headers) - content_type = http_res.headers.get('Content-Type') - - res = operations.GetVariableContextResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) - - if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[shared.VariableContext]) - res.variable_context = out - - return res - - def replace_templates(self, request: operations.ReplaceTemplatesRequestBody) -> operations.ReplaceTemplatesResponse: - r"""replaceTemplates - Replace variables in handlebars templates - - Takes in an array of input templates and outputs the output text with replaced variables - - """ - base_url = self._server_url - - url = base_url.removesuffix('/') + '/v1/template-variables:replace' - - headers = {} - req_content_type, data, form = utils.serialize_request_body(request, "request", 'json') - if req_content_type not in ('multipart/form-data', 'multipart/mixed'): - headers['content-type'] = req_content_type - - client = self._security_client - - http_res = client.request('POST', url, data=data, files=form, headers=headers) - content_type = http_res.headers.get('Content-Type') - - res = operations.ReplaceTemplatesResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) - - if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[operations.ReplaceTemplates200ApplicationJSON]) - res.replace_templates_200_application_json_object = out - - return res - - def search_variables(self, request: operations.SearchVariablesRequestBody) -> operations.SearchVariablesResponse: - r"""searchVariables - Search variables - """ - base_url = self._server_url - - url = base_url.removesuffix('/') + '/v1/template-variables:search' - - headers = {} - req_content_type, data, form = utils.serialize_request_body(request, "request", 'json') - if req_content_type not in ('multipart/form-data', 'multipart/mixed'): - headers['content-type'] = req_content_type - - client = self._security_client - - http_res = client.request('POST', url, data=data, files=form, headers=headers) - content_type = http_res.headers.get('Content-Type') - - res = operations.SearchVariablesResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) - - if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[list[shared.VariableResult]]) - res.variable_results = out - - return res - - \ No newline at end of file diff --git a/template_variables/src/epilot_template_variables/__init__.py b/template_variables/src/epilot_template_variables/__init__.py new file mode 100644 index 0000000000..68138c477e --- /dev/null +++ b/template_variables/src/epilot_template_variables/__init__.py @@ -0,0 +1,5 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .sdk import * +from .sdkconfiguration import * +from .models import * diff --git a/template_variables/src/epilot_template_variables/_hooks/__init__.py b/template_variables/src/epilot_template_variables/_hooks/__init__.py new file mode 100644 index 0000000000..2ee66cdd59 --- /dev/null +++ b/template_variables/src/epilot_template_variables/_hooks/__init__.py @@ -0,0 +1,5 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .sdkhooks import * +from .types import * +from .registration import * diff --git a/template_variables/src/epilot_template_variables/_hooks/registration.py b/template_variables/src/epilot_template_variables/_hooks/registration.py new file mode 100644 index 0000000000..1db6a52934 --- /dev/null +++ b/template_variables/src/epilot_template_variables/_hooks/registration.py @@ -0,0 +1,13 @@ +from .types import Hooks + + +# This file is only ever generated once on the first generation and then is free to be modified. +# Any hooks you wish to add should be registered in the init_hooks function. Feel free to define them +# in this file or in separate files in the hooks folder. + + +def init_hooks(hooks: Hooks): + # pylint: disable=unused-argument + """Add hooks by calling hooks.register{sdk_init/before_request/after_success/after_error}Hook + with an instance of a hook that implements that specific Hook interface + Hooks are registered per SDK instance, and are valid for the lifetime of the SDK instance""" diff --git a/template_variables/src/epilot_template_variables/_hooks/sdkhooks.py b/template_variables/src/epilot_template_variables/_hooks/sdkhooks.py new file mode 100644 index 0000000000..82d421140b --- /dev/null +++ b/template_variables/src/epilot_template_variables/_hooks/sdkhooks.py @@ -0,0 +1,57 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import httpx +from .types import SDKInitHook, BeforeRequestContext, BeforeRequestHook, AfterSuccessContext, AfterSuccessHook, AfterErrorContext, AfterErrorHook, Hooks +from .registration import init_hooks +from typing import List, Optional, Tuple +from epilot_template_variables.httpclient import HttpClient + +class SDKHooks(Hooks): + def __init__(self) -> None: + self.sdk_init_hooks: List[SDKInitHook] = [] + self.before_request_hooks: List[BeforeRequestHook] = [] + self.after_success_hooks: List[AfterSuccessHook] = [] + self.after_error_hooks: List[AfterErrorHook] = [] + init_hooks(self) + + def register_sdk_init_hook(self, hook: SDKInitHook) -> None: + self.sdk_init_hooks.append(hook) + + def register_before_request_hook(self, hook: BeforeRequestHook) -> None: + self.before_request_hooks.append(hook) + + def register_after_success_hook(self, hook: AfterSuccessHook) -> None: + self.after_success_hooks.append(hook) + + def register_after_error_hook(self, hook: AfterErrorHook) -> None: + self.after_error_hooks.append(hook) + + def sdk_init(self, base_url: str, client: HttpClient) -> Tuple[str, HttpClient]: + for hook in self.sdk_init_hooks: + base_url, client = hook.sdk_init(base_url, client) + return base_url, client + + def before_request(self, hook_ctx: BeforeRequestContext, request: httpx.Request) -> httpx.Request: + for hook in self.before_request_hooks: + out = hook.before_request(hook_ctx, request) + if isinstance(out, Exception): + raise out + request = out + + return request + + def after_success(self, hook_ctx: AfterSuccessContext, response: httpx.Response) -> httpx.Response: + for hook in self.after_success_hooks: + out = hook.after_success(hook_ctx, response) + if isinstance(out, Exception): + raise out + response = out + return response + + def after_error(self, hook_ctx: AfterErrorContext, response: Optional[httpx.Response], error: Optional[Exception]) -> Tuple[Optional[httpx.Response], Optional[Exception]]: + for hook in self.after_error_hooks: + result = hook.after_error(hook_ctx, response, error) + if isinstance(result, Exception): + raise result + response, error = result + return response, error diff --git a/template_variables/src/epilot_template_variables/_hooks/types.py b/template_variables/src/epilot_template_variables/_hooks/types.py new file mode 100644 index 0000000000..bb52425e37 --- /dev/null +++ b/template_variables/src/epilot_template_variables/_hooks/types.py @@ -0,0 +1,76 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + + +from abc import ABC, abstractmethod +from epilot_template_variables.httpclient import HttpClient +import httpx +from typing import Any, Callable, List, Optional, Tuple, Union + + +class HookContext: + operation_id: str + oauth2_scopes: Optional[List[str]] = None + security_source: Optional[Union[Any, Callable[[], Any]]] = None + + def __init__(self, operation_id: str, oauth2_scopes: Optional[List[str]], security_source: Optional[Union[Any, Callable[[], Any]]]): + self.operation_id = operation_id + self.oauth2_scopes = oauth2_scopes + self.security_source = security_source + + +class BeforeRequestContext(HookContext): + def __init__(self, hook_ctx: HookContext): + super().__init__(hook_ctx.operation_id, hook_ctx.oauth2_scopes, hook_ctx.security_source) + + +class AfterSuccessContext(HookContext): + def __init__(self, hook_ctx: HookContext): + super().__init__(hook_ctx.operation_id, hook_ctx.oauth2_scopes, hook_ctx.security_source) + + + +class AfterErrorContext(HookContext): + def __init__(self, hook_ctx: HookContext): + super().__init__(hook_ctx.operation_id, hook_ctx.oauth2_scopes, hook_ctx.security_source) + + +class SDKInitHook(ABC): + @abstractmethod + def sdk_init(self, base_url: str, client: HttpClient) -> Tuple[str, HttpClient]: + pass + + +class BeforeRequestHook(ABC): + @abstractmethod + def before_request(self, hook_ctx: BeforeRequestContext, request: httpx.Request) -> Union[httpx.Request, Exception]: + pass + + +class AfterSuccessHook(ABC): + @abstractmethod + def after_success(self, hook_ctx: AfterSuccessContext, response: httpx.Response) -> Union[httpx.Response, Exception]: + pass + + +class AfterErrorHook(ABC): + @abstractmethod + def after_error(self, hook_ctx: AfterErrorContext, response: Optional[httpx.Response], error: Optional[Exception]) -> Union[Tuple[Optional[httpx.Response], Optional[Exception]], Exception]: + pass + + +class Hooks(ABC): + @abstractmethod + def register_sdk_init_hook(self, hook: SDKInitHook): + pass + + @abstractmethod + def register_before_request_hook(self, hook: BeforeRequestHook): + pass + + @abstractmethod + def register_after_success_hook(self, hook: AfterSuccessHook): + pass + + @abstractmethod + def register_after_error_hook(self, hook: AfterErrorHook): + pass diff --git a/template_variables/src/epilot_template_variables/basesdk.py b/template_variables/src/epilot_template_variables/basesdk.py new file mode 100644 index 0000000000..140f58cf58 --- /dev/null +++ b/template_variables/src/epilot_template_variables/basesdk.py @@ -0,0 +1,253 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .sdkconfiguration import SDKConfiguration +from epilot_template_variables import models, utils +from epilot_template_variables._hooks import AfterErrorContext, AfterSuccessContext, BeforeRequestContext +from epilot_template_variables.utils import RetryConfig, SerializedRequestBody, get_body_content +import httpx +from typing import Callable, List, Optional, Tuple + +class BaseSDK: + sdk_configuration: SDKConfiguration + + def __init__(self, sdk_config: SDKConfiguration) -> None: + self.sdk_configuration = sdk_config + + def get_url(self, base_url, url_variables): + sdk_url, sdk_variables = self.sdk_configuration.get_server_details() + + if base_url is None: + base_url = sdk_url + + if url_variables is None: + url_variables = sdk_variables + + return utils.template_url(base_url, url_variables) + + def build_request( + self, + method, + path, + base_url, + url_variables, + request, + request_body_required, + request_has_path_params, + request_has_query_params, + user_agent_header, + accept_header_value, + _globals=None, + security=None, + timeout_ms: Optional[int] = None, + get_serialized_body: Optional[ + Callable[[], Optional[SerializedRequestBody]] + ] = None, + url_override: Optional[str] = None, + ) -> httpx.Request: + client = self.sdk_configuration.client + + query_params = {} + + url = url_override + if url is None: + url = utils.generate_url( + self.get_url(base_url, url_variables), + path, + request if request_has_path_params else None, + _globals if request_has_path_params else None, + ) + + query_params = utils.get_query_params( + request if request_has_query_params else None, + _globals if request_has_query_params else None, + ) + + headers = utils.get_headers(request, _globals) + headers["Accept"] = accept_header_value + headers[user_agent_header] = self.sdk_configuration.user_agent + + if security is not None: + if callable(security): + security = security() + + if security is not None: + security_headers, security_query_params = utils.get_security(security) + headers = {**headers, **security_headers} + query_params = {**query_params, **security_query_params} + + serialized_request_body = SerializedRequestBody("application/octet-stream") + if get_serialized_body is not None: + rb = get_serialized_body() + if request_body_required and rb is None: + raise ValueError("request body is required") + + if rb is not None: + serialized_request_body = rb + + if ( + serialized_request_body.media_type is not None + and serialized_request_body.media_type + not in ( + "multipart/form-data", + "multipart/mixed", + ) + ): + headers["content-type"] = serialized_request_body.media_type + + timeout = timeout_ms / 1000 if timeout_ms is not None else None + + return client.build_request( + method, + url, + params=query_params, + content=serialized_request_body.content, + data=serialized_request_body.data, + files=serialized_request_body.files, + headers=headers, + timeout=timeout, + ) + + def do_request( + self, + hook_ctx, + request, + error_status_codes, + stream=False, + retry_config: Optional[Tuple[RetryConfig, List[str]]] = None, + ) -> httpx.Response: + client = self.sdk_configuration.client + logger = self.sdk_configuration.debug_logger + + def do(): + http_res = None + try: + req = self.sdk_configuration.get_hooks().before_request( + BeforeRequestContext(hook_ctx), request + ) + logger.debug( + "Request:\nMethod: %s\nURL: %s\nHeaders: %s\nBody: %s", + req.method, + req.url, + req.headers, + get_body_content(req) + ) + http_res = client.send(req, stream=stream) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error( + AfterErrorContext(hook_ctx), None, e + ) + if e is not None: + logger.debug("Request Exception", exc_info=True) + raise e + + if http_res is None: + logger.debug("Raising no response SDK error") + raise models.SDKError("No response received") + + logger.debug( + "Response:\nStatus Code: %s\nURL: %s\nHeaders: %s\nBody: %s", + http_res.status_code, + http_res.url, + http_res.headers, + "" if stream else http_res.text + ) + + if utils.match_status_codes(error_status_codes, http_res.status_code): + result, err = self.sdk_configuration.get_hooks().after_error( + AfterErrorContext(hook_ctx), http_res, None + ) + if err is not None: + logger.debug("Request Exception", exc_info=True) + raise err + if result is not None: + http_res = result + else: + logger.debug("Raising unexpected SDK error") + raise models.SDKError("Unexpected error occurred") + + return http_res + + if retry_config is not None: + http_res = utils.retry(do, utils.Retries(retry_config[0], retry_config[1])) + else: + http_res = do() + + if not utils.match_status_codes(error_status_codes, http_res.status_code): + http_res = self.sdk_configuration.get_hooks().after_success( + AfterSuccessContext(hook_ctx), http_res + ) + + return http_res + + async def do_request_async( + self, + hook_ctx, + request, + error_status_codes, + stream=False, + retry_config: Optional[Tuple[RetryConfig, List[str]]] = None, + ) -> httpx.Response: + client = self.sdk_configuration.async_client + logger = self.sdk_configuration.debug_logger + async def do(): + http_res = None + try: + req = self.sdk_configuration.get_hooks().before_request( + BeforeRequestContext(hook_ctx), request + ) + logger.debug( + "Request:\nMethod: %s\nURL: %s\nHeaders: %s\nBody: %s", + req.method, + req.url, + req.headers, + get_body_content(req) + ) + http_res = await client.send(req, stream=stream) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error( + AfterErrorContext(hook_ctx), None, e + ) + if e is not None: + logger.debug("Request Exception", exc_info=True) + raise e + + if http_res is None: + logger.debug("Raising no response SDK error") + raise models.SDKError("No response received") + + logger.debug( + "Response:\nStatus Code: %s\nURL: %s\nHeaders: %s\nBody: %s", + http_res.status_code, + http_res.url, + http_res.headers, + "" if stream else http_res.text + ) + + if utils.match_status_codes(error_status_codes, http_res.status_code): + result, err = self.sdk_configuration.get_hooks().after_error( + AfterErrorContext(hook_ctx), http_res, None + ) + if err is not None: + logger.debug("Request Exception", exc_info=True) + raise err + if result is not None: + http_res = result + else: + logger.debug("Raising unexpected SDK error") + raise models.SDKError("Unexpected error occurred") + + return http_res + + if retry_config is not None: + http_res = await utils.retry_async( + do, utils.Retries(retry_config[0], retry_config[1]) + ) + else: + http_res = await do() + + if not utils.match_status_codes(error_status_codes, http_res.status_code): + http_res = self.sdk_configuration.get_hooks().after_success( + AfterSuccessContext(hook_ctx), http_res + ) + + return http_res diff --git a/template_variables/src/epilot_template_variables/custom_variables.py b/template_variables/src/epilot_template_variables/custom_variables.py new file mode 100644 index 0000000000..ae91783a41 --- /dev/null +++ b/template_variables/src/epilot_template_variables/custom_variables.py @@ -0,0 +1,880 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from epilot_template_variables import models, utils +from epilot_template_variables._hooks import HookContext +from epilot_template_variables.types import BaseModel, OptionalNullable, UNSET +from typing import List, Optional, Union, cast + +class CustomVariables(BaseSDK): + + + def create_custom_variable( + self, *, + request: Optional[Union[models.CustomVariable, models.CustomVariableTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ): + r"""Create custom variable + + Create custom variable + + :param request: The request object to send. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + if not isinstance(request, BaseModel) and request is not None: + request = utils.unmarshal(request, models.CustomVariable) + request = cast(models.CustomVariable, request) + + req = self.build_request( + method="POST", + path="/v1/custom-variables", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="*/*", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request, False, True, "json", Optional[models.CustomVariable]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = self.do_request( + hook_ctx=HookContext(operation_id="createCustomVariable", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["403","4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "201", "*"): + return + if utils.match_response(http_res, ["403","4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + async def create_custom_variable_async( + self, *, + request: Optional[Union[models.CustomVariable, models.CustomVariableTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ): + r"""Create custom variable + + Create custom variable + + :param request: The request object to send. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + if not isinstance(request, BaseModel) and request is not None: + request = utils.unmarshal(request, models.CustomVariable) + request = cast(models.CustomVariable, request) + + req = self.build_request( + method="POST", + path="/v1/custom-variables", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="*/*", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request, False, True, "json", Optional[models.CustomVariable]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = await self.do_request_async( + hook_ctx=HookContext(operation_id="createCustomVariable", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["403","4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "201", "*"): + return + if utils.match_response(http_res, ["403","4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + def delete_custom_variable( + self, *, + id: str, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ): + r"""Delete custom variable + + Immediately and permanently deletes a custom variable + + :param id: Custom vairable ID + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + request = models.DeleteCustomVariableRequest( + id=id, + ) + + req = self.build_request( + method="DELETE", + path="/v1/custom-variables/{id}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="*/*", + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = self.do_request( + hook_ctx=HookContext(operation_id="deleteCustomVariable", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["403","4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "204", "*"): + return + if utils.match_response(http_res, ["403","4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + async def delete_custom_variable_async( + self, *, + id: str, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ): + r"""Delete custom variable + + Immediately and permanently deletes a custom variable + + :param id: Custom vairable ID + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + request = models.DeleteCustomVariableRequest( + id=id, + ) + + req = self.build_request( + method="DELETE", + path="/v1/custom-variables/{id}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="*/*", + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = await self.do_request_async( + hook_ctx=HookContext(operation_id="deleteCustomVariable", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["403","4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "204", "*"): + return + if utils.match_response(http_res, ["403","4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + def get_blue_print_table_config( + self, *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[models.CustomVariable]: + r"""Get default table config + + Get default table config + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + req = self.build_request( + method="GET", + path="/v1/custom-variables/order-table-blueprint", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = self.do_request( + hook_ctx=HookContext(operation_id="getBluePrintTableConfig", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["403","4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[models.CustomVariable]) + if utils.match_response(http_res, ["403","4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + async def get_blue_print_table_config_async( + self, *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[models.CustomVariable]: + r"""Get default table config + + Get default table config + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + req = self.build_request( + method="GET", + path="/v1/custom-variables/order-table-blueprint", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = await self.do_request_async( + hook_ctx=HookContext(operation_id="getBluePrintTableConfig", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["403","4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[models.CustomVariable]) + if utils.match_response(http_res, ["403","4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + def get_custom_variable( + self, *, + id: str, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[models.CustomVariable]: + r"""Get custom variable + + Get custom variable + + :param id: Custom vairable ID + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + request = models.GetCustomVariableRequest( + id=id, + ) + + req = self.build_request( + method="GET", + path="/v1/custom-variables/{id}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = self.do_request( + hook_ctx=HookContext(operation_id="getCustomVariable", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["403","404","4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[models.CustomVariable]) + if utils.match_response(http_res, ["403","404","4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + async def get_custom_variable_async( + self, *, + id: str, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[models.CustomVariable]: + r"""Get custom variable + + Get custom variable + + :param id: Custom vairable ID + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + request = models.GetCustomVariableRequest( + id=id, + ) + + req = self.build_request( + method="GET", + path="/v1/custom-variables/{id}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = await self.do_request_async( + hook_ctx=HookContext(operation_id="getCustomVariable", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["403","404","4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[models.CustomVariable]) + if utils.match_response(http_res, ["403","404","4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + def get_custom_variables( + self, *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[List[models.CustomVariable]]: + r"""Get custom variables + + Get all custom variables of organization + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + req = self.build_request( + method="GET", + path="/v1/custom-variables", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = self.do_request( + hook_ctx=HookContext(operation_id="getCustomVariables", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["403","4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[List[models.CustomVariable]]) + if utils.match_response(http_res, ["403","4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + async def get_custom_variables_async( + self, *, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[List[models.CustomVariable]]: + r"""Get custom variables + + Get all custom variables of organization + + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + req = self.build_request( + method="GET", + path="/v1/custom-variables", + base_url=base_url, + url_variables=url_variables, + request=None, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = await self.do_request_async( + hook_ctx=HookContext(operation_id="getCustomVariables", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["403","4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[List[models.CustomVariable]]) + if utils.match_response(http_res, ["403","4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + def update_custom_variable( + self, *, + id: str, + custom_variable: Optional[Union[models.CustomVariable, models.CustomVariableTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ): + r"""Update custom variable + + Update custom variable + + :param id: Custom variable ID + :param custom_variable: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + request = models.UpdateCustomVariableRequest( + id=id, + custom_variable=utils.get_pydantic_model(custom_variable, Optional[models.CustomVariable]), + ) + + req = self.build_request( + method="PUT", + path="/v1/custom-variables/{id}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="*/*", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request.custom_variable, False, True, "json", Optional[models.CustomVariable]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = self.do_request( + hook_ctx=HookContext(operation_id="updateCustomVariable", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["403","4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "*"): + return + if utils.match_response(http_res, ["403","4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + async def update_custom_variable_async( + self, *, + id: str, + custom_variable: Optional[Union[models.CustomVariable, models.CustomVariableTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ): + r"""Update custom variable + + Update custom variable + + :param id: Custom variable ID + :param custom_variable: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + request = models.UpdateCustomVariableRequest( + id=id, + custom_variable=utils.get_pydantic_model(custom_variable, Optional[models.CustomVariable]), + ) + + req = self.build_request( + method="PUT", + path="/v1/custom-variables/{id}", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="*/*", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request.custom_variable, False, True, "json", Optional[models.CustomVariable]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = await self.do_request_async( + hook_ctx=HookContext(operation_id="updateCustomVariable", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["403","4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "*"): + return + if utils.match_response(http_res, ["403","4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + diff --git a/template_variables/src/epilot_template_variables/httpclient.py b/template_variables/src/epilot_template_variables/httpclient.py new file mode 100644 index 0000000000..36b642a0eb --- /dev/null +++ b/template_variables/src/epilot_template_variables/httpclient.py @@ -0,0 +1,78 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +# pyright: reportReturnType = false +from typing_extensions import Protocol, runtime_checkable +import httpx +from typing import Any, Optional, Union + + +@runtime_checkable +class HttpClient(Protocol): + def send( + self, + request: httpx.Request, + *, + stream: bool = False, + auth: Union[ + httpx._types.AuthTypes, httpx._client.UseClientDefault, None + ] = httpx.USE_CLIENT_DEFAULT, + follow_redirects: Union[ + bool, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + ) -> httpx.Response: + pass + + def build_request( + self, + method: str, + url: httpx._types.URLTypes, + *, + content: Optional[httpx._types.RequestContent] = None, + data: Optional[httpx._types.RequestData] = None, + files: Optional[httpx._types.RequestFiles] = None, + json: Optional[Any] = None, + params: Optional[httpx._types.QueryParamTypes] = None, + headers: Optional[httpx._types.HeaderTypes] = None, + cookies: Optional[httpx._types.CookieTypes] = None, + timeout: Union[ + httpx._types.TimeoutTypes, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + extensions: Optional[httpx._types.RequestExtensions] = None, + ) -> httpx.Request: + pass + + +@runtime_checkable +class AsyncHttpClient(Protocol): + async def send( + self, + request: httpx.Request, + *, + stream: bool = False, + auth: Union[ + httpx._types.AuthTypes, httpx._client.UseClientDefault, None + ] = httpx.USE_CLIENT_DEFAULT, + follow_redirects: Union[ + bool, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + ) -> httpx.Response: + pass + + def build_request( + self, + method: str, + url: httpx._types.URLTypes, + *, + content: Optional[httpx._types.RequestContent] = None, + data: Optional[httpx._types.RequestData] = None, + files: Optional[httpx._types.RequestFiles] = None, + json: Optional[Any] = None, + params: Optional[httpx._types.QueryParamTypes] = None, + headers: Optional[httpx._types.HeaderTypes] = None, + cookies: Optional[httpx._types.CookieTypes] = None, + timeout: Union[ + httpx._types.TimeoutTypes, httpx._client.UseClientDefault + ] = httpx.USE_CLIENT_DEFAULT, + extensions: Optional[httpx._types.RequestExtensions] = None, + ) -> httpx.Request: + pass diff --git a/template_variables/src/epilot_template_variables/models/__init__.py b/template_variables/src/epilot_template_variables/models/__init__.py new file mode 100644 index 0000000000..836d014c5a --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/__init__.py @@ -0,0 +1,20 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .categoryresult import CategoryResult, CategoryResultTypedDict +from .customvariable import Config, ConfigTypedDict, CustomVariable, CustomVariableTypedDict, Type +from .deletecustomvariableop import DeleteCustomVariableRequest, DeleteCustomVariableRequestTypedDict +from .externalcustomvariable import ExternalCustomVariable, ExternalCustomVariableTypedDict +from .getcategoriesop import GetCategoriesRequest, GetCategoriesRequestTypedDict +from .getcustomvariableop import GetCustomVariableRequest, GetCustomVariableRequestTypedDict +from .getvariablecontextop import GetVariableContextRequestBody, GetVariableContextRequestBodyTypedDict +from .replacetemplatesop import ReplaceTemplatesRequestBody, ReplaceTemplatesRequestBodyTypedDict, ReplaceTemplatesResponseBody, ReplaceTemplatesResponseBodyTypedDict +from .sdkerror import SDKError +from .searchvariablesop import SearchVariablesRequestBody, SearchVariablesRequestBodyTypedDict +from .security import Security, SecurityTypedDict +from .templatetype import TemplateType +from .updatecustomvariableop import UpdateCustomVariableRequest, UpdateCustomVariableRequestTypedDict +from .variablecontext import VariableContext, VariableContextTypedDict +from .variableparameters import ContextData, ContextDataTypedDict, VariableParameters, VariableParametersTypedDict +from .variableresult import VariableResult, VariableResultType, VariableResultTypedDict + +__all__ = ["CategoryResult", "CategoryResultTypedDict", "Config", "ConfigTypedDict", "ContextData", "ContextDataTypedDict", "CustomVariable", "CustomVariableTypedDict", "DeleteCustomVariableRequest", "DeleteCustomVariableRequestTypedDict", "ExternalCustomVariable", "ExternalCustomVariableTypedDict", "GetCategoriesRequest", "GetCategoriesRequestTypedDict", "GetCustomVariableRequest", "GetCustomVariableRequestTypedDict", "GetVariableContextRequestBody", "GetVariableContextRequestBodyTypedDict", "ReplaceTemplatesRequestBody", "ReplaceTemplatesRequestBodyTypedDict", "ReplaceTemplatesResponseBody", "ReplaceTemplatesResponseBodyTypedDict", "SDKError", "SearchVariablesRequestBody", "SearchVariablesRequestBodyTypedDict", "Security", "SecurityTypedDict", "TemplateType", "Type", "UpdateCustomVariableRequest", "UpdateCustomVariableRequestTypedDict", "VariableContext", "VariableContextTypedDict", "VariableParameters", "VariableParametersTypedDict", "VariableResult", "VariableResultType", "VariableResultTypedDict"] diff --git a/template_variables/src/epilot_template_variables/models/categoryresult.py b/template_variables/src/epilot_template_variables/models/categoryresult.py new file mode 100644 index 0000000000..82cdf2d83d --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/categoryresult.py @@ -0,0 +1,17 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from epilot_template_variables.types import BaseModel +from typing import Optional, TypedDict +from typing_extensions import NotRequired + + +class CategoryResultTypedDict(TypedDict): + category: NotRequired[str] + description: NotRequired[str] + + +class CategoryResult(BaseModel): + category: Optional[str] = None + description: Optional[str] = None + diff --git a/template_variables/src/epilot_template_variables/models/customvariable.py b/template_variables/src/epilot_template_variables/models/customvariable.py new file mode 100644 index 0000000000..a604c84af2 --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/customvariable.py @@ -0,0 +1,77 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from enum import Enum +from epilot_template_variables.types import BaseModel +from typing import List, Optional, TypedDict +from typing_extensions import NotRequired + + +class ConfigTypedDict(TypedDict): + r"""Variable configuration""" + + + +class Config(BaseModel): + r"""Variable configuration""" + + + +class Type(str, Enum): + r"""Custom variable type""" + ORDER_TABLE = "order_table" + CUSTOM = "custom" + +class CustomVariableTypedDict(TypedDict): + config: NotRequired[ConfigTypedDict] + r"""Variable configuration""" + created_at: NotRequired[str] + r"""Creation time""" + created_by: NotRequired[str] + r"""Created by""" + helper_logic: NotRequired[str] + r"""The helper function logic""" + helper_params: NotRequired[List[str]] + r"""The helper function parameter's names""" + id: NotRequired[str] + r"""ID""" + key: NotRequired[str] + r"""The key which is used for Handlebar variable syntax {{key}}""" + name: NotRequired[str] + r"""Custom variable name""" + template: NotRequired[str] + r"""Handlebar template that used to generate the variable content""" + type: NotRequired[Type] + r"""Custom variable type""" + updated_at: NotRequired[str] + r"""Last update time""" + updated_by: NotRequired[str] + r"""Updated by""" + + +class CustomVariable(BaseModel): + config: Optional[Config] = None + r"""Variable configuration""" + created_at: Optional[str] = None + r"""Creation time""" + created_by: Optional[str] = None + r"""Created by""" + helper_logic: Optional[str] = None + r"""The helper function logic""" + helper_params: Optional[List[str]] = None + r"""The helper function parameter's names""" + id: Optional[str] = None + r"""ID""" + key: Optional[str] = None + r"""The key which is used for Handlebar variable syntax {{key}}""" + name: Optional[str] = None + r"""Custom variable name""" + template: Optional[str] = None + r"""Handlebar template that used to generate the variable content""" + type: Optional[Type] = None + r"""Custom variable type""" + updated_at: Optional[str] = None + r"""Last update time""" + updated_by: Optional[str] = None + r"""Updated by""" + diff --git a/template_variables/src/epilot_template_variables/models/deletecustomvariableop.py b/template_variables/src/epilot_template_variables/models/deletecustomvariableop.py new file mode 100644 index 0000000000..3e33c1e250 --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/deletecustomvariableop.py @@ -0,0 +1,18 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from epilot_template_variables.types import BaseModel +from epilot_template_variables.utils import FieldMetadata, PathParamMetadata +from typing import TypedDict +from typing_extensions import Annotated + + +class DeleteCustomVariableRequestTypedDict(TypedDict): + id: str + r"""Custom vairable ID""" + + +class DeleteCustomVariableRequest(BaseModel): + id: Annotated[str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False))] + r"""Custom vairable ID""" + diff --git a/template_variables/src/epilot_template_variables/models/externalcustomvariable.py b/template_variables/src/epilot_template_variables/models/externalcustomvariable.py new file mode 100644 index 0000000000..9b57f8c648 --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/externalcustomvariable.py @@ -0,0 +1,17 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from epilot_template_variables.types import BaseModel +from typing import Optional, TypedDict +from typing_extensions import NotRequired + + +class ExternalCustomVariableTypedDict(TypedDict): + value: NotRequired[str] + variable: NotRequired[str] + + +class ExternalCustomVariable(BaseModel): + value: Optional[str] = None + variable: Optional[str] = None + diff --git a/template_variables/src/epilot_template_variables/models/getcategoriesop.py b/template_variables/src/epilot_template_variables/models/getcategoriesop.py new file mode 100644 index 0000000000..751694b398 --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/getcategoriesop.py @@ -0,0 +1,16 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from epilot_template_variables.types import BaseModel +from epilot_template_variables.utils import FieldMetadata, QueryParamMetadata +from typing import Optional, TypedDict +from typing_extensions import Annotated, NotRequired + + +class GetCategoriesRequestTypedDict(TypedDict): + lang: NotRequired[str] + + +class GetCategoriesRequest(BaseModel): + lang: Annotated[Optional[str], FieldMetadata(query=QueryParamMetadata(style="form", explode=True))] = "de" + diff --git a/template_variables/src/epilot_template_variables/models/getcustomvariableop.py b/template_variables/src/epilot_template_variables/models/getcustomvariableop.py new file mode 100644 index 0000000000..6e26c9eed6 --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/getcustomvariableop.py @@ -0,0 +1,18 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from epilot_template_variables.types import BaseModel +from epilot_template_variables.utils import FieldMetadata, PathParamMetadata +from typing import TypedDict +from typing_extensions import Annotated + + +class GetCustomVariableRequestTypedDict(TypedDict): + id: str + r"""Custom vairable ID""" + + +class GetCustomVariableRequest(BaseModel): + id: Annotated[str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False))] + r"""Custom vairable ID""" + diff --git a/template_variables/src/epilot_template_variables/models/getvariablecontextop.py b/template_variables/src/epilot_template_variables/models/getvariablecontextop.py new file mode 100644 index 0000000000..4ddb72c025 --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/getvariablecontextop.py @@ -0,0 +1,16 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .variableparameters import VariableParameters, VariableParametersTypedDict +from epilot_template_variables.types import BaseModel +from typing import Optional, TypedDict +from typing_extensions import NotRequired + + +class GetVariableContextRequestBodyTypedDict(TypedDict): + parameters: NotRequired[VariableParametersTypedDict] + + +class GetVariableContextRequestBody(BaseModel): + parameters: Optional[VariableParameters] = None + diff --git a/template_variables/src/epilot_template_variables/models/replacetemplatesop.py b/template_variables/src/epilot_template_variables/models/replacetemplatesop.py new file mode 100644 index 0000000000..2dd8153c2a --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/replacetemplatesop.py @@ -0,0 +1,30 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .variableparameters import VariableParameters, VariableParametersTypedDict +from epilot_template_variables.types import BaseModel +from typing import List, Optional, TypedDict +from typing_extensions import NotRequired + + +class ReplaceTemplatesRequestBodyTypedDict(TypedDict): + inputs: NotRequired[List[str]] + parameters: NotRequired[VariableParametersTypedDict] + + +class ReplaceTemplatesRequestBody(BaseModel): + inputs: Optional[List[str]] = None + parameters: Optional[VariableParameters] = None + + +class ReplaceTemplatesResponseBodyTypedDict(TypedDict): + r"""ok""" + + outputs: NotRequired[List[str]] + + +class ReplaceTemplatesResponseBody(BaseModel): + r"""ok""" + + outputs: Optional[List[str]] = None + diff --git a/template_variables/src/epilot_template_variables/models/sdkerror.py b/template_variables/src/epilot_template_variables/models/sdkerror.py new file mode 100644 index 0000000000..03216cbf51 --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/sdkerror.py @@ -0,0 +1,22 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from dataclasses import dataclass +from typing import Optional +import httpx + + +@dataclass +class SDKError(Exception): + """Represents an error returned by the API.""" + + message: str + status_code: int = -1 + body: str = "" + raw_response: Optional[httpx.Response] = None + + def __str__(self): + body = "" + if len(self.body) > 0: + body = f"\n{self.body}" + + return f"{self.message}: Status {self.status_code}{body}" diff --git a/template_variables/src/epilot_template_variables/models/searchvariablesop.py b/template_variables/src/epilot_template_variables/models/searchvariablesop.py new file mode 100644 index 0000000000..132fd45142 --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/searchvariablesop.py @@ -0,0 +1,31 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .templatetype import TemplateType +from epilot_template_variables.types import BaseModel +import pydantic +from typing import List, Optional, TypedDict +from typing_extensions import Annotated, NotRequired + + +class SearchVariablesRequestBodyTypedDict(TypedDict): + query: str + r"""Search string""" + template_type: TemplateType + entity_schemas: NotRequired[List[str]] + from_: NotRequired[int] + lang: NotRequired[str] + r"""2-letter language code (ISO 639-1)""" + size: NotRequired[int] + + +class SearchVariablesRequestBody(BaseModel): + query: str + r"""Search string""" + template_type: TemplateType + entity_schemas: Optional[List[str]] = None + from_: Annotated[Optional[int], pydantic.Field(alias="from")] = 0 + lang: Optional[str] = "de" + r"""2-letter language code (ISO 639-1)""" + size: Optional[int] = 25 + diff --git a/template_variables/src/epilot_template_variables/models/security.py b/template_variables/src/epilot_template_variables/models/security.py new file mode 100644 index 0000000000..011c802bfd --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/security.py @@ -0,0 +1,18 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from epilot_template_variables.types import BaseModel +from epilot_template_variables.utils import FieldMetadata, SecurityMetadata +from typing import Optional, TypedDict +from typing_extensions import Annotated, NotRequired + + +class SecurityTypedDict(TypedDict): + epilot_auth: NotRequired[str] + epilot_org: NotRequired[str] + + +class Security(BaseModel): + epilot_auth: Annotated[Optional[str], FieldMetadata(security=SecurityMetadata(scheme=True, scheme_type="http", sub_type="bearer", field_name="Authorization"))] = None + epilot_org: Annotated[Optional[str], FieldMetadata(security=SecurityMetadata(scheme=True, scheme_type="apiKey", sub_type="header", field_name="x-ivy-org-id"))] = None + diff --git a/template_variables/src/epilot_template_variables/models/templatetype.py b/template_variables/src/epilot_template_variables/models/templatetype.py new file mode 100644 index 0000000000..323a0ebf33 --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/templatetype.py @@ -0,0 +1,9 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from enum import Enum + + +class TemplateType(str, Enum): + EMAIL = "email" + DOCUMENT = "document" diff --git a/template_variables/src/epilot_template_variables/models/updatecustomvariableop.py b/template_variables/src/epilot_template_variables/models/updatecustomvariableop.py new file mode 100644 index 0000000000..59d04389b9 --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/updatecustomvariableop.py @@ -0,0 +1,21 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .customvariable import CustomVariable, CustomVariableTypedDict +from epilot_template_variables.types import BaseModel +from epilot_template_variables.utils import FieldMetadata, PathParamMetadata, RequestMetadata +from typing import Optional, TypedDict +from typing_extensions import Annotated, NotRequired + + +class UpdateCustomVariableRequestTypedDict(TypedDict): + id: str + r"""Custom variable ID""" + custom_variable: NotRequired[CustomVariableTypedDict] + + +class UpdateCustomVariableRequest(BaseModel): + id: Annotated[str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False))] + r"""Custom variable ID""" + custom_variable: Annotated[Optional[CustomVariable], FieldMetadata(request=RequestMetadata(media_type="application/json"))] = None + diff --git a/template_variables/src/epilot_template_variables/models/variablecontext.py b/template_variables/src/epilot_template_variables/models/variablecontext.py new file mode 100644 index 0000000000..00eff9fa34 --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/variablecontext.py @@ -0,0 +1,21 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from epilot_template_variables.types import BaseModel +from typing import Any, Dict, Optional, TypedDict +from typing_extensions import NotRequired + + +class VariableContextTypedDict(TypedDict): + brand: NotRequired[Dict[str, Any]] + contact: NotRequired[Dict[str, Any]] + main: NotRequired[Dict[str, Any]] + unsubscribe_url: NotRequired[str] + + +class VariableContext(BaseModel): + brand: Optional[Dict[str, Any]] = None + contact: Optional[Dict[str, Any]] = None + main: Optional[Dict[str, Any]] = None + unsubscribe_url: Optional[str] = None + diff --git a/template_variables/src/epilot_template_variables/models/variableparameters.py b/template_variables/src/epilot_template_variables/models/variableparameters.py new file mode 100644 index 0000000000..c840ed0dc9 --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/variableparameters.py @@ -0,0 +1,94 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from .externalcustomvariable import ExternalCustomVariable, ExternalCustomVariableTypedDict +from .templatetype import TemplateType +from epilot_template_variables.types import BaseModel, Nullable, OptionalNullable, UNSET, UNSET_SENTINEL +from pydantic import model_serializer +from typing import List, Optional, TypedDict +from typing_extensions import NotRequired + + +class ContextDataTypedDict(TypedDict): + r"""If context data is avaialble, this data will be used for variable replace.""" + + + +class ContextData(BaseModel): + r"""If context data is avaialble, this data will be used for variable replace.""" + + + +class VariableParametersTypedDict(TypedDict): + template_type: TemplateType + brand_id: NotRequired[Nullable[float]] + r"""Brand ID""" + context_data: NotRequired[ContextDataTypedDict] + r"""If context data is avaialble, this data will be used for variable replace.""" + custom_variables: NotRequired[List[ExternalCustomVariableTypedDict]] + r"""Custom variables with specified values form other services.""" + language: NotRequired[str] + r"""2-letter language code (ISO 639-1)""" + main_entity_id: NotRequired[str] + r"""The main entity ID. Use main entity in order to use the variable without schema slug prefix - or just pass directly to other object ID.""" + template_name: NotRequired[str] + r"""The name of email template""" + template_tags: NotRequired[List[str]] + r"""The tags of email template""" + user_id: NotRequired[Nullable[str]] + r"""User ID""" + user_org_id: NotRequired[Nullable[str]] + r"""Organization ID of the user""" + variables_version: NotRequired[str] + r"""The version of the variables syntax supported. Default is 1.0""" + + +class VariableParameters(BaseModel): + template_type: TemplateType + brand_id: OptionalNullable[float] = UNSET + r"""Brand ID""" + context_data: Optional[ContextData] = None + r"""If context data is avaialble, this data will be used for variable replace.""" + custom_variables: Optional[List[ExternalCustomVariable]] = None + r"""Custom variables with specified values form other services.""" + language: Optional[str] = "de" + r"""2-letter language code (ISO 639-1)""" + main_entity_id: Optional[str] = None + r"""The main entity ID. Use main entity in order to use the variable without schema slug prefix - or just pass directly to other object ID.""" + template_name: Optional[str] = None + r"""The name of email template""" + template_tags: Optional[List[str]] = None + r"""The tags of email template""" + user_id: OptionalNullable[str] = UNSET + r"""User ID""" + user_org_id: OptionalNullable[str] = UNSET + r"""Organization ID of the user""" + variables_version: Optional[str] = None + r"""The version of the variables syntax supported. Default is 1.0""" + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = ["brand_id", "context_data", "custom_variables", "language", "main_entity_id", "template_name", "template_tags", "user_id", "user_org_id", "variables_version"] + nullable_fields = ["brand_id", "user_id", "user_org_id"] + null_default_fields = [] + + serialized = handler(self) + + m = {} + + for n, f in self.model_fields.items(): + k = f.alias or n + val = serialized.get(k) + + optional_nullable = k in optional_fields and k in nullable_fields + is_set = (self.__pydantic_fields_set__.intersection({n}) or k in null_default_fields) # pylint: disable=no-member + + if val is not None and val != UNSET_SENTINEL: + m[k] = val + elif val != UNSET_SENTINEL and ( + not k in optional_fields or (optional_nullable and is_set) + ): + m[k] = val + + return m + diff --git a/template_variables/src/epilot_template_variables/models/variableresult.py b/template_variables/src/epilot_template_variables/models/variableresult.py new file mode 100644 index 0000000000..cd2d3e173e --- /dev/null +++ b/template_variables/src/epilot_template_variables/models/variableresult.py @@ -0,0 +1,36 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from enum import Enum +from epilot_template_variables.types import BaseModel +from typing import Optional, TypedDict +from typing_extensions import NotRequired + + +class VariableResultType(str, Enum): + SIMPLE = "simple" + PARTIAL = "partial" + +class VariableResultTypedDict(TypedDict): + description: NotRequired[str] + r"""Variable description""" + group: NotRequired[str] + r"""Variable group""" + insert: NotRequired[str] + r"""The value which is used to insert to template""" + qrdata: NotRequired[str] + r"""Payload for the QR data""" + type: NotRequired[VariableResultType] + + +class VariableResult(BaseModel): + description: Optional[str] = None + r"""Variable description""" + group: Optional[str] = None + r"""Variable group""" + insert: Optional[str] = None + r"""The value which is used to insert to template""" + qrdata: Optional[str] = None + r"""Payload for the QR data""" + type: Optional[VariableResultType] = None + diff --git a/template_variables/src/epilot_template_variables/py.typed b/template_variables/src/epilot_template_variables/py.typed new file mode 100644 index 0000000000..3e38f1a929 --- /dev/null +++ b/template_variables/src/epilot_template_variables/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. The package enables type hints. diff --git a/template_variables/src/epilot_template_variables/sdk.py b/template_variables/src/epilot_template_variables/sdk.py new file mode 100644 index 0000000000..0c3099e599 --- /dev/null +++ b/template_variables/src/epilot_template_variables/sdk.py @@ -0,0 +1,93 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from .httpclient import AsyncHttpClient, HttpClient +from .sdkconfiguration import SDKConfiguration +from .utils.logger import Logger, NoOpLogger +from .utils.retries import RetryConfig +from epilot_template_variables import models, utils +from epilot_template_variables._hooks import SDKHooks +from epilot_template_variables.custom_variables import CustomVariables +from epilot_template_variables.types import OptionalNullable, UNSET +from epilot_template_variables.variables import Variables +import httpx +from typing import Callable, Dict, Optional, Union + +class Epilot(BaseSDK): + r"""Template Variables API: API to provide variables for email and document templates.""" + custom_variables: CustomVariables + variables: Variables + r"""Variables""" + def __init__( + self, + security: Union[models.Security, Callable[[], models.Security]], + server_idx: Optional[int] = None, + server_url: Optional[str] = None, + url_params: Optional[Dict[str, str]] = None, + client: Optional[HttpClient] = None, + async_client: Optional[AsyncHttpClient] = None, + retry_config: OptionalNullable[RetryConfig] = UNSET, + timeout_ms: Optional[int] = None, + debug_logger: Optional[Logger] = None + ) -> None: + r"""Instantiates the SDK configuring it with the provided parameters. + + :param security: The security details required for authentication + :param server_idx: The index of the server to use for all methods + :param server_url: The server URL to use for all methods + :param url_params: Parameters to optionally template the server URL with + :param client: The HTTP client to use for all synchronous methods + :param async_client: The Async HTTP client to use for all asynchronous methods + :param retry_config: The retry configuration to use for all supported methods + :param timeout_ms: Optional request timeout applied to each operation in milliseconds + """ + if client is None: + client = httpx.Client() + + assert issubclass( + type(client), HttpClient + ), "The provided client must implement the HttpClient protocol." + + if async_client is None: + async_client = httpx.AsyncClient() + + if debug_logger is None: + debug_logger = NoOpLogger() + + assert issubclass( + type(async_client), AsyncHttpClient + ), "The provided async_client must implement the AsyncHttpClient protocol." + + if server_url is not None: + if url_params is not None: + server_url = utils.template_url(server_url, url_params) + + + BaseSDK.__init__(self, SDKConfiguration( + client=client, + async_client=async_client, + security=security, + server_url=server_url, + server_idx=server_idx, + retry_config=retry_config, + timeout_ms=timeout_ms, + debug_logger=debug_logger + )) + + hooks = SDKHooks() + + current_server_url, *_ = self.sdk_configuration.get_server_details() + server_url, self.sdk_configuration.client = hooks.sdk_init(current_server_url, self.sdk_configuration.client) + if current_server_url != server_url: + self.sdk_configuration.server_url = server_url + + # pylint: disable=protected-access + self.sdk_configuration.__dict__["_hooks"] = hooks + + self._init_sdks() + + + def _init_sdks(self): + self.custom_variables = CustomVariables(self.sdk_configuration) + self.variables = Variables(self.sdk_configuration) + diff --git a/template_variables/src/epilot_template_variables/sdkconfiguration.py b/template_variables/src/epilot_template_variables/sdkconfiguration.py new file mode 100644 index 0000000000..e551dc63f7 --- /dev/null +++ b/template_variables/src/epilot_template_variables/sdkconfiguration.py @@ -0,0 +1,48 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + + +from ._hooks import SDKHooks +from .httpclient import AsyncHttpClient, HttpClient +from .utils import Logger, RetryConfig, remove_suffix +from dataclasses import dataclass +from epilot_template_variables import models +from epilot_template_variables.types import OptionalNullable, UNSET +from pydantic import Field +from typing import Callable, Dict, Optional, Tuple, Union + + +SERVERS = [ + "https://template-variables-api.sls.epilot.io", +] +"""Contains the list of servers available to the SDK""" + +@dataclass +class SDKConfiguration: + client: HttpClient + async_client: AsyncHttpClient + debug_logger: Logger + security: Optional[Union[models.Security,Callable[[], models.Security]]] = None + server_url: Optional[str] = "" + server_idx: Optional[int] = 0 + language: str = "python" + openapi_doc_version: str = "1.0.0" + sdk_version: str = "1.3.0" + gen_version: str = "2.387.0" + user_agent: str = "speakeasy-sdk/python 1.3.0 2.387.0 1.0.0 epilot-template-variables" + retry_config: OptionalNullable[RetryConfig] = Field(default_factory=lambda: UNSET) + timeout_ms: Optional[int] = None + + def __post_init__(self): + self._hooks = SDKHooks() + + def get_server_details(self) -> Tuple[str, Dict[str, str]]: + if self.server_url is not None and self.server_url: + return remove_suffix(self.server_url, "/"), {} + if self.server_idx is None: + self.server_idx = 0 + + return SERVERS[self.server_idx], {} + + + def get_hooks(self) -> SDKHooks: + return self._hooks diff --git a/template_variables/src/epilot_template_variables/types/__init__.py b/template_variables/src/epilot_template_variables/types/__init__.py new file mode 100644 index 0000000000..fc76fe0c55 --- /dev/null +++ b/template_variables/src/epilot_template_variables/types/__init__.py @@ -0,0 +1,21 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basemodel import ( + BaseModel, + Nullable, + OptionalNullable, + UnrecognizedInt, + UnrecognizedStr, + UNSET, + UNSET_SENTINEL, +) + +__all__ = [ + "BaseModel", + "Nullable", + "OptionalNullable", + "UnrecognizedInt", + "UnrecognizedStr", + "UNSET", + "UNSET_SENTINEL", +] diff --git a/template_variables/src/epilot_template_variables/types/basemodel.py b/template_variables/src/epilot_template_variables/types/basemodel.py new file mode 100644 index 0000000000..a6187efa6d --- /dev/null +++ b/template_variables/src/epilot_template_variables/types/basemodel.py @@ -0,0 +1,39 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from pydantic import ConfigDict, model_serializer +from pydantic import BaseModel as PydanticBaseModel +from typing import TYPE_CHECKING, Literal, Optional, TypeVar, Union, NewType +from typing_extensions import TypeAliasType, TypeAlias + + +class BaseModel(PydanticBaseModel): + model_config = ConfigDict( + populate_by_name=True, arbitrary_types_allowed=True, protected_namespaces=() + ) + + +class Unset(BaseModel): + @model_serializer(mode="plain") + def serialize_model(self): + return UNSET_SENTINEL + + def __bool__(self) -> Literal[False]: + return False + + +UNSET = Unset() +UNSET_SENTINEL = "~?~unset~?~sentinel~?~" + + +T = TypeVar("T") +if TYPE_CHECKING: + Nullable: TypeAlias = Union[T, None] + OptionalNullable: TypeAlias = Union[Optional[Nullable[T]], Unset] +else: + Nullable = TypeAliasType("Nullable", Union[T, None], type_params=(T,)) + OptionalNullable = TypeAliasType( + "OptionalNullable", Union[Optional[Nullable[T]], Unset], type_params=(T,) + ) + +UnrecognizedInt = NewType("UnrecognizedInt", int) +UnrecognizedStr = NewType("UnrecognizedStr", str) diff --git a/template_variables/src/epilot_template_variables/utils/__init__.py b/template_variables/src/epilot_template_variables/utils/__init__.py new file mode 100644 index 0000000000..95aa1b60c9 --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/__init__.py @@ -0,0 +1,84 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .annotations import get_discriminator +from .enums import OpenEnumMeta +from .headers import get_headers, get_response_headers +from .metadata import ( + FieldMetadata, + find_metadata, + FormMetadata, + HeaderMetadata, + MultipartFormMetadata, + PathParamMetadata, + QueryParamMetadata, + RequestMetadata, + SecurityMetadata, +) +from .queryparams import get_query_params +from .retries import BackoffStrategy, Retries, retry, retry_async, RetryConfig +from .requestbodies import serialize_request_body, SerializedRequestBody +from .security import get_security +from .serializers import ( + get_pydantic_model, + marshal_json, + unmarshal, + unmarshal_json, + serialize_decimal, + serialize_float, + serialize_int, + stream_to_text, + validate_decimal, + validate_float, + validate_int, + validate_open_enum, +) +from .url import generate_url, template_url, remove_suffix +from .values import get_global_from_env, match_content_type, match_status_codes, match_response +from .logger import Logger, get_body_content, NoOpLogger + +__all__ = [ + "BackoffStrategy", + "FieldMetadata", + "find_metadata", + "FormMetadata", + "generate_url", + "get_body_content", + "get_discriminator", + "get_global_from_env", + "get_headers", + "get_pydantic_model", + "get_query_params", + "get_response_headers", + "get_security", + "HeaderMetadata", + "Logger", + "marshal_json", + "match_content_type", + "match_status_codes", + "match_response", + "MultipartFormMetadata", + "NoOpLogger", + "OpenEnumMeta", + "PathParamMetadata", + "QueryParamMetadata", + "remove_suffix", + "Retries", + "retry", + "retry_async", + "RetryConfig", + "RequestMetadata", + "SecurityMetadata", + "serialize_decimal", + "serialize_float", + "serialize_int", + "serialize_request_body", + "SerializedRequestBody", + "stream_to_text", + "template_url", + "unmarshal", + "unmarshal_json", + "validate_decimal", + "validate_float", + "validate_int", + "validate_open_enum", +] diff --git a/template_variables/src/epilot_template_variables/utils/annotations.py b/template_variables/src/epilot_template_variables/utils/annotations.py new file mode 100644 index 0000000000..0d17472b30 --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/annotations.py @@ -0,0 +1,19 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import Any + +def get_discriminator(model: Any, fieldname: str, key: str) -> str: + if isinstance(model, dict): + try: + return f'{model.get(key)}' + except AttributeError as e: + raise ValueError(f'Could not find discriminator key {key} in {model}') from e + + if hasattr(model, fieldname): + return f'{getattr(model, fieldname)}' + + fieldname = fieldname.upper() + if hasattr(model, fieldname): + return f'{getattr(model, fieldname)}' + + raise ValueError(f'Could not find discriminator field {fieldname} in {model}') diff --git a/template_variables/src/epilot_template_variables/utils/enums.py b/template_variables/src/epilot_template_variables/utils/enums.py new file mode 100644 index 0000000000..c650b10cb2 --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/enums.py @@ -0,0 +1,34 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import enum + + +class OpenEnumMeta(enum.EnumMeta): + def __call__( + cls, value, names=None, *, module=None, qualname=None, type=None, start=1 + ): + # The `type` kwarg also happens to be a built-in that pylint flags as + # redeclared. Safe to ignore this lint rule with this scope. + # pylint: disable=redefined-builtin + + if names is not None: + return super().__call__( + value, + names=names, + module=module, + qualname=qualname, + type=type, + start=start, + ) + + try: + return super().__call__( + value, + names=names, # pyright: ignore[reportArgumentType] + module=module, + qualname=qualname, + type=type, + start=start, + ) + except ValueError: + return value diff --git a/template_variables/src/epilot_template_variables/utils/eventstreaming.py b/template_variables/src/epilot_template_variables/utils/eventstreaming.py new file mode 100644 index 0000000000..553b386b3b --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/eventstreaming.py @@ -0,0 +1,178 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import re +import json +from typing import Callable, TypeVar, Optional, Generator, AsyncGenerator, Tuple +import httpx + +T = TypeVar("T") + + +class ServerEvent: + id: Optional[str] = None + event: Optional[str] = None + data: Optional[str] = None + retry: Optional[int] = None + + +MESSAGE_BOUNDARIES = [ + b"\r\n\r\n", + b"\n\n", + b"\r\r", +] + + +async def stream_events_async( + response: httpx.Response, + decoder: Callable[[str], T], + sentinel: Optional[str] = None, +) -> AsyncGenerator[T, None]: + buffer = bytearray() + position = 0 + discard = False + async for chunk in response.aiter_bytes(): + # We've encountered the sentinel value and should no longer process + # incoming data. Instead we throw new data away until the server closes + # the connection. + if discard: + continue + + buffer += chunk + for i in range(position, len(buffer)): + char = buffer[i : i + 1] + seq: Optional[bytes] = None + if char in [b"\r", b"\n"]: + for boundary in MESSAGE_BOUNDARIES: + seq = _peek_sequence(i, buffer, boundary) + if seq is not None: + break + if seq is None: + continue + + block = buffer[position:i] + position = i + len(seq) + event, discard = _parse_event(block, decoder, sentinel) + if event is not None: + yield event + + if position > 0: + buffer = buffer[position:] + position = 0 + + event, discard = _parse_event(buffer, decoder, sentinel) + if event is not None: + yield event + + +def stream_events( + response: httpx.Response, + decoder: Callable[[str], T], + sentinel: Optional[str] = None, +) -> Generator[T, None, None]: + buffer = bytearray() + position = 0 + discard = False + for chunk in response.iter_bytes(): + # We've encountered the sentinel value and should no longer process + # incoming data. Instead we throw new data away until the server closes + # the connection. + if discard: + continue + + buffer += chunk + for i in range(position, len(buffer)): + char = buffer[i : i + 1] + seq: Optional[bytes] = None + if char in [b"\r", b"\n"]: + for boundary in MESSAGE_BOUNDARIES: + seq = _peek_sequence(i, buffer, boundary) + if seq is not None: + break + if seq is None: + continue + + block = buffer[position:i] + position = i + len(seq) + event, discard = _parse_event(block, decoder, sentinel) + if event is not None: + yield event + + if position > 0: + buffer = buffer[position:] + position = 0 + + event, discard = _parse_event(buffer, decoder, sentinel) + if event is not None: + yield event + + +def _parse_event( + raw: bytearray, decoder: Callable[[str], T], sentinel: Optional[str] = None +) -> Tuple[Optional[T], bool]: + block = raw.decode() + lines = re.split(r"\r?\n|\r", block) + publish = False + event = ServerEvent() + data = "" + for line in lines: + if not line: + continue + + delim = line.find(":") + if delim <= 0: + continue + + field = line[0:delim] + value = line[delim + 1 :] if delim < len(line) - 1 else "" + if len(value) and value[0] == " ": + value = value[1:] + + if field == "event": + event.event = value + publish = True + elif field == "data": + data += value + "\n" + publish = True + elif field == "id": + event.id = value + publish = True + elif field == "retry": + event.retry = int(value) if value.isdigit() else None + publish = True + + if sentinel and data == f"{sentinel}\n": + return None, True + + if data: + data = data[:-1] + event.data = data + + data_is_primitive = ( + data.isnumeric() or data == "true" or data == "false" or data == "null" + ) + data_is_json = ( + data.startswith("{") or data.startswith("[") or data.startswith('"') + ) + + if data_is_primitive or data_is_json: + try: + event.data = json.loads(data) + except Exception: + pass + + out = None + if publish: + out = decoder(json.dumps(event.__dict__)) + + return out, False + + +def _peek_sequence(position: int, buffer: bytearray, sequence: bytes): + if len(sequence) > (len(buffer) - position): + return None + + for i, seq in enumerate(sequence): + if buffer[position + i] != seq: + return None + + return sequence diff --git a/template_variables/src/epilot_template_variables/utils/forms.py b/template_variables/src/epilot_template_variables/utils/forms.py new file mode 100644 index 0000000000..07f9b2359a --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/forms.py @@ -0,0 +1,207 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import ( + Any, + Dict, + get_type_hints, + List, + Tuple, +) +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .serializers import marshal_json + +from .metadata import ( + FormMetadata, + MultipartFormMetadata, + find_field_metadata, +) +from .values import _val_to_string + + +def _populate_form( + field_name: str, + explode: bool, + obj: Any, + delimiter: str, + form: Dict[str, List[str]], +): + if obj is None: + return form + + if isinstance(obj, BaseModel): + items = [] + + obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields + for name in obj_fields: + obj_field = obj_fields[name] + obj_field_name = obj_field.alias if obj_field.alias is not None else name + if obj_field_name == "": + continue + + val = getattr(obj, name) + if val is None: + continue + + if explode: + form[obj_field_name] = [_val_to_string(val)] + else: + items.append(f"{obj_field_name}{delimiter}{_val_to_string(val)}") + + if len(items) > 0: + form[field_name] = [delimiter.join(items)] + elif isinstance(obj, Dict): + items = [] + for key, value in obj.items(): + if value is None: + continue + + if explode: + form[key] = [_val_to_string(value)] + else: + items.append(f"{key}{delimiter}{_val_to_string(value)}") + + if len(items) > 0: + form[field_name] = [delimiter.join(items)] + elif isinstance(obj, List): + items = [] + + for value in obj: + if value is None: + continue + + if explode: + if not field_name in form: + form[field_name] = [] + form[field_name].append(_val_to_string(value)) + else: + items.append(_val_to_string(value)) + + if len(items) > 0: + form[field_name] = [delimiter.join([str(item) for item in items])] + else: + form[field_name] = [_val_to_string(obj)] + + return form + + +def serialize_multipart_form( + media_type: str, request: Any +) -> Tuple[str, Dict[str, Any], Dict[str, Any]]: + form: Dict[str, Any] = {} + files: Dict[str, Any] = {} + + if not isinstance(request, BaseModel): + raise TypeError("invalid request body type") + + request_fields: Dict[str, FieldInfo] = request.__class__.model_fields + request_field_types = get_type_hints(request.__class__) + + for name in request_fields: + field = request_fields[name] + + val = getattr(request, name) + if val is None: + continue + + field_metadata = find_field_metadata(field, MultipartFormMetadata) + if not field_metadata: + continue + + f_name = field.alias if field.alias is not None else name + + if field_metadata.file: + file_fields: Dict[str, FieldInfo] = val.__class__.model_fields + + file_name = "" + field_name = "" + content = None + content_type = None + + for file_field_name in file_fields: + file_field = file_fields[file_field_name] + + file_metadata = find_field_metadata(file_field, MultipartFormMetadata) + if file_metadata is None: + continue + + if file_metadata.content: + content = getattr(val, file_field_name, None) + elif file_field_name == "content_type": + content_type = getattr(val, file_field_name, None) + else: + field_name = ( + file_field.alias + if file_field.alias is not None + else file_field_name + ) + file_name = getattr(val, file_field_name) + + if field_name == "" or file_name == "" or content is None: + raise ValueError("invalid multipart/form-data file") + + if content_type is not None: + files[field_name] = (file_name, content, content_type) + else: + files[field_name] = (file_name, content) + elif field_metadata.json: + files[f_name] = ( + None, + marshal_json(val, request_field_types[name]), + "application/json", + ) + else: + if isinstance(val, List): + values = [] + + for value in val: + if value is None: + continue + values.append(_val_to_string(value)) + + form[f_name + "[]"] = values + else: + form[f_name] = _val_to_string(val) + return media_type, form, files + + +def serialize_form_data(data: Any) -> Dict[str, Any]: + form: Dict[str, List[str]] = {} + + if isinstance(data, BaseModel): + data_fields: Dict[str, FieldInfo] = data.__class__.model_fields + data_field_types = get_type_hints(data.__class__) + for name in data_fields: + field = data_fields[name] + + val = getattr(data, name) + if val is None: + continue + + metadata = find_field_metadata(field, FormMetadata) + if metadata is None: + continue + + f_name = field.alias if field.alias is not None else name + + if metadata.json: + form[f_name] = [marshal_json(val, data_field_types[name])] + else: + if metadata.style == "form": + _populate_form( + f_name, + metadata.explode, + val, + ",", + form, + ) + else: + raise ValueError(f"Invalid form style for field {name}") + elif isinstance(data, Dict): + for key, value in data.items(): + form[key] = [_val_to_string(value)] + else: + raise TypeError(f"Invalid request body type {type(data)} for form data") + + return form diff --git a/template_variables/src/epilot_template_variables/utils/headers.py b/template_variables/src/epilot_template_variables/utils/headers.py new file mode 100644 index 0000000000..e14a0f4a8e --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/headers.py @@ -0,0 +1,136 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import ( + Any, + Dict, + List, + Optional, +) +from httpx import Headers +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .metadata import ( + HeaderMetadata, + find_field_metadata, +) + +from .values import _populate_from_globals, _val_to_string + + +def get_headers(headers_params: Any, gbls: Optional[Any] = None) -> Dict[str, str]: + headers: Dict[str, str] = {} + + globals_already_populated = [] + if headers_params is not None: + globals_already_populated = _populate_headers(headers_params, gbls, headers, []) + if gbls is not None: + _populate_headers(gbls, None, headers, globals_already_populated) + + return headers + + +def _populate_headers( + headers_params: Any, + gbls: Any, + header_values: Dict[str, str], + skip_fields: List[str], +) -> List[str]: + globals_already_populated: List[str] = [] + + if not isinstance(headers_params, BaseModel): + return globals_already_populated + + param_fields: Dict[str, FieldInfo] = headers_params.__class__.model_fields + for name in param_fields: + if name in skip_fields: + continue + + field = param_fields[name] + f_name = field.alias if field.alias is not None else name + + metadata = find_field_metadata(field, HeaderMetadata) + if metadata is None: + continue + + value, global_found = _populate_from_globals( + name, getattr(headers_params, name), HeaderMetadata, gbls + ) + if global_found: + globals_already_populated.append(name) + value = _serialize_header(metadata.explode, value) + + if value != "": + header_values[f_name] = value + + return globals_already_populated + + +def _serialize_header(explode: bool, obj: Any) -> str: + if obj is None: + return "" + + if isinstance(obj, BaseModel): + items = [] + obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields + for name in obj_fields: + obj_field = obj_fields[name] + obj_param_metadata = find_field_metadata(obj_field, HeaderMetadata) + + if not obj_param_metadata: + continue + + f_name = obj_field.alias if obj_field.alias is not None else name + + val = getattr(obj, name) + if val is None: + continue + + if explode: + items.append(f"{f_name}={_val_to_string(val)}") + else: + items.append(f_name) + items.append(_val_to_string(val)) + + if len(items) > 0: + return ",".join(items) + elif isinstance(obj, Dict): + items = [] + + for key, value in obj.items(): + if value is None: + continue + + if explode: + items.append(f"{key}={_val_to_string(value)}") + else: + items.append(key) + items.append(_val_to_string(value)) + + if len(items) > 0: + return ",".join([str(item) for item in items]) + elif isinstance(obj, List): + items = [] + + for value in obj: + if value is None: + continue + + items.append(_val_to_string(value)) + + if len(items) > 0: + return ",".join(items) + else: + return f"{_val_to_string(obj)}" + + return "" + + +def get_response_headers(headers: Headers) -> Dict[str, List[str]]: + res: Dict[str, List[str]] = {} + for k, v in headers.items(): + if not k in res: + res[k] = [] + + res[k].append(v) + return res diff --git a/template_variables/src/epilot_template_variables/utils/logger.py b/template_variables/src/epilot_template_variables/utils/logger.py new file mode 100644 index 0000000000..7e4bbeac26 --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/logger.py @@ -0,0 +1,16 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import httpx +from typing import Any, Protocol + +class Logger(Protocol): + def debug(self, msg: str, *args: Any, **kwargs: Any) -> None: + pass + +class NoOpLogger: + def debug(self, msg: str, *args: Any, **kwargs: Any) -> None: + pass + +def get_body_content(req: httpx.Request) -> str: + return "" if not hasattr(req, "_content") else str(req.content) + diff --git a/template_variables/src/epilot_template_variables/utils/metadata.py b/template_variables/src/epilot_template_variables/utils/metadata.py new file mode 100644 index 0000000000..173b3e5ce6 --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/metadata.py @@ -0,0 +1,118 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import Optional, Type, TypeVar, Union +from dataclasses import dataclass +from pydantic.fields import FieldInfo + + +T = TypeVar("T") + + +@dataclass +class SecurityMetadata: + option: bool = False + scheme: bool = False + scheme_type: Optional[str] = None + sub_type: Optional[str] = None + field_name: Optional[str] = None + + def get_field_name(self, default: str) -> str: + return self.field_name or default + + +@dataclass +class ParamMetadata: + serialization: Optional[str] = None + style: str = "simple" + explode: bool = False + + +@dataclass +class PathParamMetadata(ParamMetadata): + pass + + +@dataclass +class QueryParamMetadata(ParamMetadata): + style: str = "form" + explode: bool = True + + +@dataclass +class HeaderMetadata(ParamMetadata): + pass + + +@dataclass +class RequestMetadata: + media_type: str = "application/octet-stream" + + +@dataclass +class MultipartFormMetadata: + file: bool = False + content: bool = False + json: bool = False + + +@dataclass +class FormMetadata: + json: bool = False + style: str = "form" + explode: bool = True + + +class FieldMetadata: + security: Optional[SecurityMetadata] = None + path: Optional[PathParamMetadata] = None + query: Optional[QueryParamMetadata] = None + header: Optional[HeaderMetadata] = None + request: Optional[RequestMetadata] = None + form: Optional[FormMetadata] = None + multipart: Optional[MultipartFormMetadata] = None + + def __init__( + self, + security: Optional[SecurityMetadata] = None, + path: Optional[Union[PathParamMetadata, bool]] = None, + query: Optional[Union[QueryParamMetadata, bool]] = None, + header: Optional[Union[HeaderMetadata, bool]] = None, + request: Optional[Union[RequestMetadata, bool]] = None, + form: Optional[Union[FormMetadata, bool]] = None, + multipart: Optional[Union[MultipartFormMetadata, bool]] = None, + ): + self.security = security + self.path = PathParamMetadata() if isinstance(path, bool) else path + self.query = QueryParamMetadata() if isinstance(query, bool) else query + self.header = HeaderMetadata() if isinstance(header, bool) else header + self.request = RequestMetadata() if isinstance(request, bool) else request + self.form = FormMetadata() if isinstance(form, bool) else form + self.multipart = ( + MultipartFormMetadata() if isinstance(multipart, bool) else multipart + ) + + +def find_field_metadata(field_info: FieldInfo, metadata_type: Type[T]) -> Optional[T]: + metadata = find_metadata(field_info, FieldMetadata) + if not metadata: + return None + + fields = metadata.__dict__ + + for field in fields: + if isinstance(fields[field], metadata_type): + return fields[field] + + return None + + +def find_metadata(field_info: FieldInfo, metadata_type: Type[T]) -> Optional[T]: + metadata = field_info.metadata + if not metadata: + return None + + for md in metadata: + if isinstance(md, metadata_type): + return md + + return None diff --git a/template_variables/src/epilot_template_variables/utils/queryparams.py b/template_variables/src/epilot_template_variables/utils/queryparams.py new file mode 100644 index 0000000000..1c8c58340d --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/queryparams.py @@ -0,0 +1,203 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from typing import ( + Any, + Dict, + get_type_hints, + List, + Optional, +) + +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .metadata import ( + QueryParamMetadata, + find_field_metadata, +) +from .values import _get_serialized_params, _populate_from_globals, _val_to_string +from .forms import _populate_form + + +def get_query_params( + query_params: Any, + gbls: Optional[Any] = None, +) -> Dict[str, List[str]]: + params: Dict[str, List[str]] = {} + + globals_already_populated = _populate_query_params(query_params, gbls, params, []) + if gbls is not None: + _populate_query_params(gbls, None, params, globals_already_populated) + + return params + + +def _populate_query_params( + query_params: Any, + gbls: Any, + query_param_values: Dict[str, List[str]], + skip_fields: List[str], +) -> List[str]: + globals_already_populated: List[str] = [] + + if not isinstance(query_params, BaseModel): + return globals_already_populated + + param_fields: Dict[str, FieldInfo] = query_params.__class__.model_fields + param_field_types = get_type_hints(query_params.__class__) + for name in param_fields: + if name in skip_fields: + continue + + field = param_fields[name] + + metadata = find_field_metadata(field, QueryParamMetadata) + if not metadata: + continue + + value = getattr(query_params, name) if query_params is not None else None + + value, global_found = _populate_from_globals( + name, value, QueryParamMetadata, gbls + ) + if global_found: + globals_already_populated.append(name) + + f_name = field.alias if field.alias is not None else name + serialization = metadata.serialization + if serialization is not None: + serialized_parms = _get_serialized_params( + metadata, f_name, value, param_field_types[name] + ) + for key, value in serialized_parms.items(): + if key in query_param_values: + query_param_values[key].extend(value) + else: + query_param_values[key] = [value] + else: + style = metadata.style + if style == "deepObject": + _populate_deep_object_query_params(f_name, value, query_param_values) + elif style == "form": + _populate_delimited_query_params( + metadata, f_name, value, ",", query_param_values + ) + elif style == "pipeDelimited": + _populate_delimited_query_params( + metadata, f_name, value, "|", query_param_values + ) + else: + raise NotImplementedError( + f"query param style {style} not yet supported" + ) + + return globals_already_populated + + +def _populate_deep_object_query_params( + field_name: str, + obj: Any, + params: Dict[str, List[str]], +): + if obj is None: + return + + if isinstance(obj, BaseModel): + _populate_deep_object_query_params_basemodel(field_name, obj, params) + elif isinstance(obj, Dict): + _populate_deep_object_query_params_dict(field_name, obj, params) + + +def _populate_deep_object_query_params_basemodel( + prior_params_key: str, + obj: Any, + params: Dict[str, List[str]], +): + if obj is None: + return + + if not isinstance(obj, BaseModel): + return + + obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields + for name in obj_fields: + obj_field = obj_fields[name] + + f_name = obj_field.alias if obj_field.alias is not None else name + + params_key = f"{prior_params_key}[{f_name}]" + + obj_param_metadata = find_field_metadata(obj_field, QueryParamMetadata) + if obj_param_metadata is None: + continue + + obj_val = getattr(obj, name) + if obj_val is None: + continue + + if isinstance(obj_val, BaseModel): + _populate_deep_object_query_params_basemodel(params_key, obj_val, params) + elif isinstance(obj_val, Dict): + _populate_deep_object_query_params_dict(params_key, obj_val, params) + elif isinstance(obj_val, List): + _populate_deep_object_query_params_list(params_key, obj_val, params) + else: + params[params_key] = [_val_to_string(obj_val)] + + +def _populate_deep_object_query_params_dict( + prior_params_key: str, + value: Dict, + params: Dict[str, List[str]], +): + if value is None: + return + + for key, val in value.items(): + if val is None: + continue + + params_key = f"{prior_params_key}[{key}]" + + if isinstance(val, BaseModel): + _populate_deep_object_query_params_basemodel(params_key, val, params) + elif isinstance(val, Dict): + _populate_deep_object_query_params_dict(params_key, val, params) + elif isinstance(val, List): + _populate_deep_object_query_params_list(params_key, val, params) + else: + params[params_key] = [_val_to_string(val)] + + +def _populate_deep_object_query_params_list( + params_key: str, + value: List, + params: Dict[str, List[str]], +): + if value is None: + return + + for val in value: + if val is None: + continue + + if params.get(params_key) is None: + params[params_key] = [] + + params[params_key].append(_val_to_string(val)) + + +def _populate_delimited_query_params( + metadata: QueryParamMetadata, + field_name: str, + obj: Any, + delimiter: str, + query_param_values: Dict[str, List[str]], +): + _populate_form( + field_name, + metadata.explode, + obj, + delimiter, + query_param_values, + ) diff --git a/template_variables/src/epilot_template_variables/utils/requestbodies.py b/template_variables/src/epilot_template_variables/utils/requestbodies.py new file mode 100644 index 0000000000..4f586ae79a --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/requestbodies.py @@ -0,0 +1,66 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import io +from dataclasses import dataclass +import re +from typing import ( + Any, + Optional, +) + +from .forms import serialize_form_data, serialize_multipart_form + +from .serializers import marshal_json + +SERIALIZATION_METHOD_TO_CONTENT_TYPE = { + "json": "application/json", + "form": "application/x-www-form-urlencoded", + "multipart": "multipart/form-data", + "raw": "application/octet-stream", + "string": "text/plain", +} + + +@dataclass +class SerializedRequestBody: + media_type: str + content: Optional[Any] = None + data: Optional[Any] = None + files: Optional[Any] = None + + +def serialize_request_body( + request_body: Any, + nullable: bool, + optional: bool, + serialization_method: str, + request_body_type, +) -> Optional[SerializedRequestBody]: + if request_body is None: + if not nullable and optional: + return None + + media_type = SERIALIZATION_METHOD_TO_CONTENT_TYPE[serialization_method] + + serialized_request_body = SerializedRequestBody(media_type) + + if re.match(r"(application|text)\/.*?\+*json.*", media_type) is not None: + serialized_request_body.content = marshal_json(request_body, request_body_type) + elif re.match(r"multipart\/.*", media_type) is not None: + ( + serialized_request_body.media_type, + serialized_request_body.data, + serialized_request_body.files, + ) = serialize_multipart_form(media_type, request_body) + elif re.match(r"application\/x-www-form-urlencoded.*", media_type) is not None: + serialized_request_body.data = serialize_form_data(request_body) + elif isinstance(request_body, (bytes, bytearray, io.BytesIO, io.BufferedReader)): + serialized_request_body.content = request_body + elif isinstance(request_body, str): + serialized_request_body.content = request_body + else: + raise TypeError( + f"invalid request body type {type(request_body)} for mediaType {media_type}" + ) + + return serialized_request_body diff --git a/template_variables/src/epilot_template_variables/utils/retries.py b/template_variables/src/epilot_template_variables/utils/retries.py new file mode 100644 index 0000000000..a06f927946 --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/retries.py @@ -0,0 +1,216 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import random +import time +from typing import List + +import httpx + + +class BackoffStrategy: + initial_interval: int + max_interval: int + exponent: float + max_elapsed_time: int + + def __init__( + self, + initial_interval: int, + max_interval: int, + exponent: float, + max_elapsed_time: int, + ): + self.initial_interval = initial_interval + self.max_interval = max_interval + self.exponent = exponent + self.max_elapsed_time = max_elapsed_time + + +class RetryConfig: + strategy: str + backoff: BackoffStrategy + retry_connection_errors: bool + + def __init__( + self, strategy: str, backoff: BackoffStrategy, retry_connection_errors: bool + ): + self.strategy = strategy + self.backoff = backoff + self.retry_connection_errors = retry_connection_errors + + +class Retries: + config: RetryConfig + status_codes: List[str] + + def __init__(self, config: RetryConfig, status_codes: List[str]): + self.config = config + self.status_codes = status_codes + + +class TemporaryError(Exception): + response: httpx.Response + + def __init__(self, response: httpx.Response): + self.response = response + + +class PermanentError(Exception): + inner: Exception + + def __init__(self, inner: Exception): + self.inner = inner + + +def retry(func, retries: Retries): + if retries.config.strategy == "backoff": + + def do_request() -> httpx.Response: + res: httpx.Response + try: + res = func() + + for code in retries.status_codes: + if "X" in code.upper(): + code_range = int(code[0]) + + status_major = res.status_code / 100 + + if code_range <= status_major < code_range + 1: + raise TemporaryError(res) + else: + parsed_code = int(code) + + if res.status_code == parsed_code: + raise TemporaryError(res) + except httpx.ConnectError as exception: + if retries.config.retry_connection_errors: + raise + + raise PermanentError(exception) from exception + except httpx.TimeoutException as exception: + if retries.config.retry_connection_errors: + raise + + raise PermanentError(exception) from exception + except TemporaryError: + raise + except Exception as exception: + raise PermanentError(exception) from exception + + return res + + return retry_with_backoff( + do_request, + retries.config.backoff.initial_interval, + retries.config.backoff.max_interval, + retries.config.backoff.exponent, + retries.config.backoff.max_elapsed_time, + ) + + return func() + + +async def retry_async(func, retries: Retries): + if retries.config.strategy == "backoff": + + async def do_request() -> httpx.Response: + res: httpx.Response + try: + res = await func() + + for code in retries.status_codes: + if "X" in code.upper(): + code_range = int(code[0]) + + status_major = res.status_code / 100 + + if code_range <= status_major < code_range + 1: + raise TemporaryError(res) + else: + parsed_code = int(code) + + if res.status_code == parsed_code: + raise TemporaryError(res) + except httpx.ConnectError as exception: + if retries.config.retry_connection_errors: + raise + + raise PermanentError(exception) from exception + except httpx.TimeoutException as exception: + if retries.config.retry_connection_errors: + raise + + raise PermanentError(exception) from exception + except TemporaryError: + raise + except Exception as exception: + raise PermanentError(exception) from exception + + return res + + return await retry_with_backoff_async( + do_request, + retries.config.backoff.initial_interval, + retries.config.backoff.max_interval, + retries.config.backoff.exponent, + retries.config.backoff.max_elapsed_time, + ) + + return await func() + + +def retry_with_backoff( + func, + initial_interval=500, + max_interval=60000, + exponent=1.5, + max_elapsed_time=3600000, +): + start = round(time.time() * 1000) + retries = 0 + + while True: + try: + return func() + except PermanentError as exception: + raise exception.inner + except Exception as exception: # pylint: disable=broad-exception-caught + now = round(time.time() * 1000) + if now - start > max_elapsed_time: + if isinstance(exception, TemporaryError): + return exception.response + + raise + sleep = (initial_interval / 1000) * exponent**retries + random.uniform(0, 1) + sleep = min(sleep, max_interval / 1000) + time.sleep(sleep) + retries += 1 + + +async def retry_with_backoff_async( + func, + initial_interval=500, + max_interval=60000, + exponent=1.5, + max_elapsed_time=3600000, +): + start = round(time.time() * 1000) + retries = 0 + + while True: + try: + return await func() + except PermanentError as exception: + raise exception.inner + except Exception as exception: # pylint: disable=broad-exception-caught + now = round(time.time() * 1000) + if now - start > max_elapsed_time: + if isinstance(exception, TemporaryError): + return exception.response + + raise + sleep = (initial_interval / 1000) * exponent**retries + random.uniform(0, 1) + sleep = min(sleep, max_interval / 1000) + time.sleep(sleep) + retries += 1 diff --git a/template_variables/src/epilot_template_variables/utils/security.py b/template_variables/src/epilot_template_variables/utils/security.py new file mode 100644 index 0000000000..aab4cb65ca --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/security.py @@ -0,0 +1,168 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +import base64 +from typing import ( + Any, + Dict, + List, + Tuple, +) +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .metadata import ( + SecurityMetadata, + find_field_metadata, +) + + + +def get_security(security: Any) -> Tuple[Dict[str, str], Dict[str, List[str]]]: + headers: Dict[str, str] = {} + query_params: Dict[str, List[str]] = {} + + if security is None: + return headers, query_params + + if not isinstance(security, BaseModel): + raise TypeError("security must be a pydantic model") + + sec_fields: Dict[str, FieldInfo] = security.__class__.model_fields + for name in sec_fields: + sec_field = sec_fields[name] + + value = getattr(security, name) + if value is None: + continue + + metadata = find_field_metadata(sec_field, SecurityMetadata) + if metadata is None: + continue + if metadata.option: + _parse_security_option(headers, query_params, value) + return headers, query_params + if metadata.scheme: + # Special case for basic auth which could be a flattened model + if metadata.sub_type == "basic" and not isinstance(value, BaseModel): + _parse_security_scheme(headers, query_params, metadata, name, security) + else: + _parse_security_scheme(headers, query_params, metadata, name, value) + + return headers, query_params + + +def _parse_security_option( + headers: Dict[str, str], query_params: Dict[str, List[str]], option: Any +): + if not isinstance(option, BaseModel): + raise TypeError("security option must be a pydantic model") + + opt_fields: Dict[str, FieldInfo] = option.__class__.model_fields + for name in opt_fields: + opt_field = opt_fields[name] + + metadata = find_field_metadata(opt_field, SecurityMetadata) + if metadata is None or not metadata.scheme: + continue + _parse_security_scheme( + headers, query_params, metadata, name, getattr(option, name) + ) + + +def _parse_security_scheme( + headers: Dict[str, str], + query_params: Dict[str, List[str]], + scheme_metadata: SecurityMetadata, + field_name: str, + scheme: Any, +): + scheme_type = scheme_metadata.scheme_type + sub_type = scheme_metadata.sub_type + + if isinstance(scheme, BaseModel): + if scheme_type == "http" and sub_type == "basic": + _parse_basic_auth_scheme(headers, scheme) + return + + scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields + for name in scheme_fields: + scheme_field = scheme_fields[name] + + metadata = find_field_metadata(scheme_field, SecurityMetadata) + if metadata is None or metadata.field_name is None: + continue + + value = getattr(scheme, name) + + _parse_security_scheme_value( + headers, query_params, scheme_metadata, metadata, name, value + ) + else: + _parse_security_scheme_value( + headers, query_params, scheme_metadata, scheme_metadata, field_name, scheme + ) + + +def _parse_security_scheme_value( + headers: Dict[str, str], + query_params: Dict[str, List[str]], + scheme_metadata: SecurityMetadata, + security_metadata: SecurityMetadata, + field_name: str, + value: Any, +): + scheme_type = scheme_metadata.scheme_type + sub_type = scheme_metadata.sub_type + + header_name = security_metadata.get_field_name(field_name) + + if scheme_type == "apiKey": + if sub_type == "header": + headers[header_name] = value + elif sub_type == "query": + query_params[header_name] = [value] + else: + raise ValueError("sub type {sub_type} not supported") + elif scheme_type == "openIdConnect": + headers[header_name] = _apply_bearer(value) + elif scheme_type == "oauth2": + if sub_type != "client_credentials": + headers[header_name] = _apply_bearer(value) + elif scheme_type == "http": + if sub_type == "bearer": + headers[header_name] = _apply_bearer(value) + else: + raise ValueError("sub type {sub_type} not supported") + else: + raise ValueError("scheme type {scheme_type} not supported") + + +def _apply_bearer(token: str) -> str: + return token.lower().startswith("bearer ") and token or f"Bearer {token}" + + +def _parse_basic_auth_scheme(headers: Dict[str, str], scheme: Any): + username = "" + password = "" + + if not isinstance(scheme, BaseModel): + raise TypeError("basic auth scheme must be a pydantic model") + + scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields + for name in scheme_fields: + scheme_field = scheme_fields[name] + + metadata = find_field_metadata(scheme_field, SecurityMetadata) + if metadata is None or metadata.field_name is None: + continue + + field_name = metadata.field_name + value = getattr(scheme, name) + + if field_name == "username": + username = value + if field_name == "password": + password = value + + data = f"{username}:{password}".encode() + headers["Authorization"] = f"Basic {base64.b64encode(data).decode()}" diff --git a/template_variables/src/epilot_template_variables/utils/serializers.py b/template_variables/src/epilot_template_variables/utils/serializers.py new file mode 100644 index 0000000000..a98998a3ff --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/serializers.py @@ -0,0 +1,181 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from decimal import Decimal +import json +from typing import Any, Dict, List, Union, get_args +import httpx +from typing_extensions import get_origin +from pydantic import ConfigDict, create_model +from pydantic_core import from_json +from typing_inspect import is_optional_type + +from ..types.basemodel import BaseModel, Nullable, OptionalNullable + + +def serialize_decimal(as_str: bool): + def serialize(d): + if is_optional_type(type(d)) and d is None: + return None + + if not isinstance(d, Decimal): + raise ValueError("Expected Decimal object") + + return str(d) if as_str else float(d) + + return serialize + + +def validate_decimal(d): + if d is None: + return None + + if isinstance(d, Decimal): + return d + + if not isinstance(d, (str, int, float)): + raise ValueError("Expected string, int or float") + + return Decimal(str(d)) + + +def serialize_float(as_str: bool): + def serialize(f): + if is_optional_type(type(f)) and f is None: + return None + + if not isinstance(f, float): + raise ValueError("Expected float") + + return str(f) if as_str else f + + return serialize + + +def validate_float(f): + if f is None: + return None + + if isinstance(f, float): + return f + + if not isinstance(f, str): + raise ValueError("Expected string") + + return float(f) + + +def serialize_int(as_str: bool): + def serialize(b): + if is_optional_type(type(b)) and b is None: + return None + + if not isinstance(b, int): + raise ValueError("Expected int") + + return str(b) if as_str else b + + return serialize + + +def validate_int(b): + if b is None: + return None + + if isinstance(b, int): + return b + + if not isinstance(b, str): + raise ValueError("Expected string") + + return int(b) + + +def validate_open_enum(is_int: bool): + def validate(e): + if e is None: + return None + + if is_int: + if not isinstance(e, int): + raise ValueError("Expected int") + else: + if not isinstance(e, str): + raise ValueError("Expected string") + + return e + + return validate + + +def unmarshal_json(raw, typ: Any) -> Any: + return unmarshal(from_json(raw), typ) + + +def unmarshal(val, typ: Any) -> Any: + unmarshaller = create_model( + "Unmarshaller", + body=(typ, ...), + __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True), + ) + + m = unmarshaller(body=val) + + # pyright: ignore[reportAttributeAccessIssue] + return m.body # type: ignore + + +def marshal_json(val, typ): + if is_nullable(typ) and val is None: + return "null" + + marshaller = create_model( + "Marshaller", + body=(typ, ...), + __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True), + ) + + m = marshaller(body=val) + + d = m.model_dump(by_alias=True, mode="json", exclude_none=True) + + if len(d) == 0: + return "" + + return json.dumps(d[next(iter(d))], separators=(",", ":"), sort_keys=True) + + +def is_nullable(field): + origin = get_origin(field) + if origin is Nullable or origin is OptionalNullable: + return True + + if not origin is Union or type(None) not in get_args(field): + return False + + for arg in get_args(field): + if get_origin(arg) is Nullable or get_origin(arg) is OptionalNullable: + return True + + return False + + +def stream_to_text(stream: httpx.Response) -> str: + return "".join(stream.iter_text()) + + +def get_pydantic_model(data: Any, typ: Any) -> Any: + if not _contains_pydantic_model(data): + return unmarshal(data, typ) + + return data + + +def _contains_pydantic_model(data: Any) -> bool: + if isinstance(data, BaseModel): + return True + if isinstance(data, List): + return any(_contains_pydantic_model(item) for item in data) + if isinstance(data, Dict): + return any(_contains_pydantic_model(value) for value in data.values()) + + return False diff --git a/template_variables/src/epilot_template_variables/utils/url.py b/template_variables/src/epilot_template_variables/utils/url.py new file mode 100644 index 0000000000..b201bfa498 --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/url.py @@ -0,0 +1,150 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from decimal import Decimal +from typing import ( + Any, + Dict, + get_type_hints, + List, + Optional, + Union, + get_args, + get_origin, +) +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .metadata import ( + PathParamMetadata, + find_field_metadata, +) +from .values import _get_serialized_params, _populate_from_globals, _val_to_string + + +def generate_url( + server_url: str, + path: str, + path_params: Any, + gbls: Optional[Any] = None, +) -> str: + path_param_values: Dict[str, str] = {} + + globals_already_populated = _populate_path_params( + path_params, gbls, path_param_values, [] + ) + if gbls is not None: + _populate_path_params(gbls, None, path_param_values, globals_already_populated) + + for key, value in path_param_values.items(): + path = path.replace("{" + key + "}", value, 1) + + return remove_suffix(server_url, "/") + path + + +def _populate_path_params( + path_params: Any, + gbls: Any, + path_param_values: Dict[str, str], + skip_fields: List[str], +) -> List[str]: + globals_already_populated: List[str] = [] + + if not isinstance(path_params, BaseModel): + return globals_already_populated + + path_param_fields: Dict[str, FieldInfo] = path_params.__class__.model_fields + path_param_field_types = get_type_hints(path_params.__class__) + for name in path_param_fields: + if name in skip_fields: + continue + + field = path_param_fields[name] + + param_metadata = find_field_metadata(field, PathParamMetadata) + if param_metadata is None: + continue + + param = getattr(path_params, name) if path_params is not None else None + param, global_found = _populate_from_globals( + name, param, PathParamMetadata, gbls + ) + if global_found: + globals_already_populated.append(name) + + if param is None: + continue + + f_name = field.alias if field.alias is not None else name + serialization = param_metadata.serialization + if serialization is not None: + serialized_params = _get_serialized_params( + param_metadata, f_name, param, path_param_field_types[name] + ) + for key, value in serialized_params.items(): + path_param_values[key] = value + else: + pp_vals: List[str] = [] + if param_metadata.style == "simple": + if isinstance(param, List): + for pp_val in param: + if pp_val is None: + continue + pp_vals.append(_val_to_string(pp_val)) + path_param_values[f_name] = ",".join(pp_vals) + elif isinstance(param, Dict): + for pp_key in param: + if param[pp_key] is None: + continue + if param_metadata.explode: + pp_vals.append(f"{pp_key}={_val_to_string(param[pp_key])}") + else: + pp_vals.append(f"{pp_key},{_val_to_string(param[pp_key])}") + path_param_values[f_name] = ",".join(pp_vals) + elif not isinstance(param, (str, int, float, complex, bool, Decimal)): + param_fields: Dict[str, FieldInfo] = param.__class__.model_fields + for name in param_fields: + param_field = param_fields[name] + + param_value_metadata = find_field_metadata( + param_field, PathParamMetadata + ) + if param_value_metadata is None: + continue + + param_name = ( + param_field.alias if param_field.alias is not None else name + ) + + param_field_val = getattr(param, name) + if param_field_val is None: + continue + if param_metadata.explode: + pp_vals.append( + f"{param_name}={_val_to_string(param_field_val)}" + ) + else: + pp_vals.append( + f"{param_name},{_val_to_string(param_field_val)}" + ) + path_param_values[f_name] = ",".join(pp_vals) + else: + path_param_values[f_name] = _val_to_string(param) + + return globals_already_populated + + +def is_optional(field): + return get_origin(field) is Union and type(None) in get_args(field) + + +def template_url(url_with_params: str, params: Dict[str, str]) -> str: + for key, value in params.items(): + url_with_params = url_with_params.replace("{" + key + "}", value) + + return url_with_params + + +def remove_suffix(input_string, suffix): + if suffix and input_string.endswith(suffix): + return input_string[: -len(suffix)] + return input_string diff --git a/template_variables/src/epilot_template_variables/utils/values.py b/template_variables/src/epilot_template_variables/utils/values.py new file mode 100644 index 0000000000..24ccae3d0b --- /dev/null +++ b/template_variables/src/epilot_template_variables/utils/values.py @@ -0,0 +1,128 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from datetime import datetime +from enum import Enum +from email.message import Message +import os +from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union + +from httpx import Response +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from .serializers import marshal_json + +from .metadata import ParamMetadata, find_field_metadata + + +def match_content_type(content_type: str, pattern: str) -> bool: + if pattern in (content_type, "*", "*/*"): + return True + + msg = Message() + msg["content-type"] = content_type + media_type = msg.get_content_type() + + if media_type == pattern: + return True + + parts = media_type.split("/") + if len(parts) == 2: + if pattern in (f"{parts[0]}/*", f"*/{parts[1]}"): + return True + + return False + + +def match_status_codes(status_codes: List[str], status_code: int) -> bool: + if "default" in status_codes: + return True + + for code in status_codes: + if code == str(status_code): + return True + + if code.endswith("XX") and code.startswith(str(status_code)[:1]): + return True + return False + + +T = TypeVar("T") + + +def get_global_from_env( + value: Optional[T], env_key: str, type_cast: Callable[[str], T] +) -> Optional[T]: + if value is not None: + return value + env_value = os.getenv(env_key) + if env_value is not None: + try: + return type_cast(env_value) + except ValueError: + pass + return None + + +def match_response( + response: Response, code: Union[str, List[str]], content_type: str +) -> bool: + codes = code if isinstance(code, list) else [code] + return match_status_codes(codes, response.status_code) and match_content_type( + response.headers.get("content-type", "application/octet-stream"), content_type + ) + + +def _populate_from_globals( + param_name: str, value: Any, param_metadata_type: type, gbls: Any +) -> Tuple[Any, bool]: + if gbls is None: + return value, False + + if not isinstance(gbls, BaseModel): + raise TypeError("globals must be a pydantic model") + + global_fields: Dict[str, FieldInfo] = gbls.__class__.model_fields + found = False + for name in global_fields: + field = global_fields[name] + if name is not param_name: + continue + + found = True + + if value is not None: + return value, True + + global_value = getattr(gbls, name) + + param_metadata = find_field_metadata(field, param_metadata_type) + if param_metadata is None: + return value, True + + return global_value, True + + return value, found + + +def _val_to_string(val) -> str: + if isinstance(val, bool): + return str(val).lower() + if isinstance(val, datetime): + return str(val.isoformat().replace("+00:00", "Z")) + if isinstance(val, Enum): + return str(val.value) + + return str(val) + + +def _get_serialized_params( + metadata: ParamMetadata, field_name: str, obj: Any, typ: type +) -> Dict[str, str]: + params: Dict[str, str] = {} + + serialization = metadata.serialization + if serialization == "json": + params[field_name] = marshal_json(obj, typ) + + return params diff --git a/template_variables/src/epilot_template_variables/variables.py b/template_variables/src/epilot_template_variables/variables.py new file mode 100644 index 0000000000..ea7e3a2766 --- /dev/null +++ b/template_variables/src/epilot_template_variables/variables.py @@ -0,0 +1,621 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from .basesdk import BaseSDK +from epilot_template_variables import models, utils +from epilot_template_variables._hooks import HookContext +from epilot_template_variables.types import BaseModel, OptionalNullable, UNSET +from typing import List, Optional, Union, cast + +class Variables(BaseSDK): + r"""Variables""" + + + def get_categories( + self, *, + lang: Optional[str] = "de", + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[List[models.CategoryResult]]: + r"""getCategories + + Get all template variable categories + + :param lang: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + request = models.GetCategoriesRequest( + lang=lang, + ) + + req = self.build_request( + method="GET", + path="/v1/template-variables/categories", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = self.do_request( + hook_ctx=HookContext(operation_id="getCategories", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[List[models.CategoryResult]]) + if utils.match_response(http_res, ["4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + async def get_categories_async( + self, *, + lang: Optional[str] = "de", + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[List[models.CategoryResult]]: + r"""getCategories + + Get all template variable categories + + :param lang: + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + request = models.GetCategoriesRequest( + lang=lang, + ) + + req = self.build_request( + method="GET", + path="/v1/template-variables/categories", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = await self.do_request_async( + hook_ctx=HookContext(operation_id="getCategories", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[List[models.CategoryResult]]) + if utils.match_response(http_res, ["4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + def get_variable_context( + self, *, + request: Optional[Union[models.GetVariableContextRequestBody, models.GetVariableContextRequestBodyTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[models.VariableContext]: + r"""getVariableContext + + Get full variable context + + Calls Entity API, User API, Brand API and others to construct full context object used for template variable replace + + + :param request: The request object to send. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + if not isinstance(request, BaseModel) and request is not None: + request = utils.unmarshal(request, models.GetVariableContextRequestBody) + request = cast(models.GetVariableContextRequestBody, request) + + req = self.build_request( + method="POST", + path="/v1/template-variables:context", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request, False, True, "json", Optional[models.GetVariableContextRequestBody]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = self.do_request( + hook_ctx=HookContext(operation_id="getVariableContext", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[models.VariableContext]) + if utils.match_response(http_res, ["4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + async def get_variable_context_async( + self, *, + request: Optional[Union[models.GetVariableContextRequestBody, models.GetVariableContextRequestBodyTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[models.VariableContext]: + r"""getVariableContext + + Get full variable context + + Calls Entity API, User API, Brand API and others to construct full context object used for template variable replace + + + :param request: The request object to send. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + if not isinstance(request, BaseModel) and request is not None: + request = utils.unmarshal(request, models.GetVariableContextRequestBody) + request = cast(models.GetVariableContextRequestBody, request) + + req = self.build_request( + method="POST", + path="/v1/template-variables:context", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request, False, True, "json", Optional[models.GetVariableContextRequestBody]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = await self.do_request_async( + hook_ctx=HookContext(operation_id="getVariableContext", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[models.VariableContext]) + if utils.match_response(http_res, ["4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + def replace_templates( + self, *, + request: Optional[Union[models.ReplaceTemplatesRequestBody, models.ReplaceTemplatesRequestBodyTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[models.ReplaceTemplatesResponseBody]: + r"""replaceTemplates + + Replace variables in handlebars templates + + Takes in an array of input templates and outputs the output text with replaced variables + + + :param request: The request object to send. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + if not isinstance(request, BaseModel) and request is not None: + request = utils.unmarshal(request, models.ReplaceTemplatesRequestBody) + request = cast(models.ReplaceTemplatesRequestBody, request) + + req = self.build_request( + method="POST", + path="/v1/template-variables:replace", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request, False, True, "json", Optional[models.ReplaceTemplatesRequestBody]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = self.do_request( + hook_ctx=HookContext(operation_id="replaceTemplates", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[models.ReplaceTemplatesResponseBody]) + if utils.match_response(http_res, ["4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + async def replace_templates_async( + self, *, + request: Optional[Union[models.ReplaceTemplatesRequestBody, models.ReplaceTemplatesRequestBodyTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[models.ReplaceTemplatesResponseBody]: + r"""replaceTemplates + + Replace variables in handlebars templates + + Takes in an array of input templates and outputs the output text with replaced variables + + + :param request: The request object to send. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + if not isinstance(request, BaseModel) and request is not None: + request = utils.unmarshal(request, models.ReplaceTemplatesRequestBody) + request = cast(models.ReplaceTemplatesRequestBody, request) + + req = self.build_request( + method="POST", + path="/v1/template-variables:replace", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request, False, True, "json", Optional[models.ReplaceTemplatesRequestBody]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = await self.do_request_async( + hook_ctx=HookContext(operation_id="replaceTemplates", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[models.ReplaceTemplatesResponseBody]) + if utils.match_response(http_res, ["4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + def search_variables( + self, *, + request: Optional[Union[models.SearchVariablesRequestBody, models.SearchVariablesRequestBodyTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[List[models.VariableResult]]: + r"""searchVariables + + Search variables + + :param request: The request object to send. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + if not isinstance(request, BaseModel) and request is not None: + request = utils.unmarshal(request, models.SearchVariablesRequestBody) + request = cast(models.SearchVariablesRequestBody, request) + + req = self.build_request( + method="POST", + path="/v1/template-variables:search", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request, False, True, "json", Optional[models.SearchVariablesRequestBody]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = self.do_request( + hook_ctx=HookContext(operation_id="searchVariables", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[List[models.VariableResult]]) + if utils.match_response(http_res, ["4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + + + + async def search_variables_async( + self, *, + request: Optional[Union[models.SearchVariablesRequestBody, models.SearchVariablesRequestBodyTypedDict]] = None, + retries: OptionalNullable[utils.RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + ) -> Optional[List[models.VariableResult]]: + r"""searchVariables + + Search variables + + :param request: The request object to send. + :param retries: Override the default retry configuration for this method + :param server_url: Override the default server URL for this method + :param timeout_ms: Override the default request timeout configuration for this method in milliseconds + """ + base_url = None + url_variables = None + if timeout_ms is None: + timeout_ms = self.sdk_configuration.timeout_ms + + if server_url is not None: + base_url = server_url + + if not isinstance(request, BaseModel) and request is not None: + request = utils.unmarshal(request, models.SearchVariablesRequestBody) + request = cast(models.SearchVariablesRequestBody, request) + + req = self.build_request( + method="POST", + path="/v1/template-variables:search", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=False, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + security=self.sdk_configuration.security, + get_serialized_body=lambda: utils.serialize_request_body(request, False, True, "json", Optional[models.SearchVariablesRequestBody]), + timeout_ms=timeout_ms, + ) + + if retries == UNSET: + if self.sdk_configuration.retry_config is not UNSET: + retries = self.sdk_configuration.retry_config + + retry_config = None + if isinstance(retries, utils.RetryConfig): + retry_config = (retries, [ + "429", + "500", + "502", + "503", + "504" + ]) + + http_res = await self.do_request_async( + hook_ctx=HookContext(operation_id="searchVariables", oauth2_scopes=[], security_source=self.sdk_configuration.security), + request=req, + error_status_codes=["4XX","5XX"], + retry_config=retry_config + ) + + if utils.match_response(http_res, "200", "application/json"): + return utils.unmarshal_json(http_res.text, Optional[List[models.VariableResult]]) + if utils.match_response(http_res, ["4XX","5XX"], "*"): + raise models.SDKError("API error occurred", http_res.status_code, http_res.text, http_res) + + content_type = http_res.headers.get("Content-Type") + raise models.SDKError(f"Unexpected response received (code: {http_res.status_code}, type: {content_type})", http_res.status_code, http_res.text, http_res) + +