diff --git a/submission/.gitattributes b/submission/.gitattributes new file mode 100644 index 0000000000..4d75d59008 --- /dev/null +++ b/submission/.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/submission/.gitignore b/submission/.gitignore new file mode 100644 index 0000000000..3cdf338022 --- /dev/null +++ b/submission/.gitignore @@ -0,0 +1,6 @@ +venv/ +src/*.egg-info/ +__pycache__/ +.pytest_cache/ +.python-version +.DS_Store diff --git a/submission/.speakeasy/gen.lock b/submission/.speakeasy/gen.lock new file mode 100755 index 0000000000..b52c5cd79a --- /dev/null +++ b/submission/.speakeasy/gen.lock @@ -0,0 +1,57 @@ +lockVersion: 2.0.0 +id: 10c30c50-231f-4672-b225-8be4e7bd56e3 +management: + docChecksum: 3e73a0b032d576778d71b4b1bce49714 + docVersion: 1.0.0 + speakeasyVersion: 1.269.1 + generationVersion: 2.312.1 + releaseVersion: 1.3.0 + configChecksum: e42c0b11b06754209ea416c74fbd505f + repoURL: https://github.com/epilot-dev/sdk-python.git + repoSubDirectory: submission + installationURL: https://github.com/epilot-dev/sdk-python.git#subdirectory=submission +features: + python: + additionalProperties: 0.1.0 + core: 4.6.5 + deprecations: 2.81.1 + globalServerURLs: 2.82.2 + responseFormat: 0.1.0 +generatedFiles: + - src/epilot/sdkconfiguration.py + - src/epilot/submissions.py + - src/epilot/sdk.py + - py.typed + - pylintrc + - setup.py + - src/epilot/__init__.py + - src/epilot/utils/__init__.py + - src/epilot/utils/retries.py + - src/epilot/utils/utils.py + - src/epilot/models/errors/sdkerror.py + - tests/helpers.py + - src/epilot/models/operations/createsubmission.py + - src/epilot/models/components/httpmetadata.py + - src/epilot/models/components/submissionpayload.py + - src/epilot/models/components/optin.py + - src/epilot/models/components/submissionentity.py + - src/epilot/models/components/s3reference.py + - src/epilot/models/__init__.py + - src/epilot/models/errors/__init__.py + - src/epilot/models/operations/__init__.py + - src/epilot/models/components/__init__.py + - docs/models/operations/createsubmissionresponse.md + - docs/models/components/httpmetadata.md + - docs/models/components/submissionpayload.md + - docs/models/components/optin.md + - docs/models/components/schema.md + - docs/models/components/files.md + - docs/models/components/submissionentity.md + - docs/models/components/s3reference.md + - docs/sdks/epilot/README.md + - docs/sdks/submissions/README.md + - USAGE.md + - .gitattributes + - src/epilot/_hooks/sdkhooks.py + - src/epilot/_hooks/types.py + - src/epilot/_hooks/__init__.py diff --git a/submission/README.md b/submission/README.md index 815eaf5381..d8ca99b215 100755 --- a/submission/README.md +++ b/submission/README.md @@ -1,76 +1,264 @@ # epilot-submission - + ## SDK Installation ```bash pip install git+https://github.com/epilot-dev/sdk-python.git#subdirectory=submission ``` - + + ## SDK Example Usage - + +### Example + ```python import epilot -from epilot.models import operations, shared +from epilot.models import components s = epilot.Epilot() +req = components.SubmissionPayload( + entities=[ + components.SubmissionEntity( + schema=components.Schema.SUBMISSION, + additional_properties={ + '_schema': 'submission', + 'description': 'Submission created via API', + 'contact_first_name': 'First', + 'contact_last_name': 'Last', + 'contact_email': 'example@submission.com', + 'request': 'I would like to know more about electric vehicles', + 'files': '', + }, + description='Submission created via API', + files=[ + components.Files( + s3ref=components.S3Reference( + bucket='epilot-user-content', + key='temp/123/4d689aeb-1497-4410-a9fe-b36ca9ac4389/document.pdf', + ), + filename='document.pdf', + ), + ], + ), + ], + organization_id='123', + source_id='ce99875f-fba9-4fe2-a8f9-afaf52059051', + source_type='journey', + journey_submit_id='123', +) + +res = s.submissions.create_submission(req) + +if res is not None: + # handle response + pass + +``` + + + +## Available Resources and Operations + +### [submissions](docs/sdks/submissions/README.md) + +* [create_submission](docs/sdks/submissions/README.md#create_submission) - createSubmission + + + +## Error Handling + +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. -req = shared.SubmissionPayload( - ivy_opportunity_ids=[ - "deserunt", - "porro", - "nulla", +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4xx-5xx | */* | + +### Example + +```python +import epilot +from epilot.models import components, errors + +s = epilot.Epilot() + +req = components.SubmissionPayload( + entities=[ + components.SubmissionEntity( + schema=components.Schema.SUBMISSION, + additional_properties={ + '_schema': 'submission', + 'description': 'Submission created via API', + 'contact_first_name': 'First', + 'contact_last_name': 'Last', + 'contact_email': 'example@submission.com', + 'request': 'I would like to know more about electric vehicles', + 'files': '', + }, + description='Submission created via API', + files=[ + components.Files( + s3ref=components.S3Reference( + bucket='epilot-user-content', + key='temp/123/4d689aeb-1497-4410-a9fe-b36ca9ac4389/document.pdf', + ), + filename='document.pdf', + ), + ], + ), ], + organization_id='123', + source_id='ce99875f-fba9-4fe2-a8f9-afaf52059051', + source_type='journey', + journey_submit_id='123', +) + +res = None +try: + res = s.submissions.create_submission(req) +except errors.SDKError as e: + # handle exception + raise(e) + +if res is not None: + # handle response + pass + +``` + + + +## 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://submission.sls.epilot.io` | None | + +#### Example + +```python +import epilot +from epilot.models import components + +s = epilot.Epilot( + server_idx=0, +) + +req = components.SubmissionPayload( entities=[ - { - "perspiciatis": "nulla", - "nihil": "fuga", - "facilis": "eum", - "iusto": "ullam", - }, - { - "inventore": "sapiente", - "enim": "eum", - "voluptatum": "autem", - "vel": "non", - }, - { - "similique": "reprehenderit", - "molestiae": "quo", - }, + components.SubmissionEntity( + schema=components.Schema.SUBMISSION, + additional_properties={ + '_schema': 'submission', + 'description': 'Submission created via API', + 'contact_first_name': 'First', + 'contact_last_name': 'Last', + 'contact_email': 'example@submission.com', + 'request': 'I would like to know more about electric vehicles', + 'files': '', + }, + description='Submission created via API', + files=[ + components.Files( + s3ref=components.S3Reference( + bucket='epilot-user-content', + key='temp/123/4d689aeb-1497-4410-a9fe-b36ca9ac4389/document.pdf', + ), + filename='document.pdf', + ), + ], + ), ], - journey_submit_id="123", - opt_ins=[ - shared.OptIn( - identifier="example@email.com", - meta={ - "dicta": "est", - "voluptatem": "consequatur", + organization_id='123', + source_id='ce99875f-fba9-4fe2-a8f9-afaf52059051', + source_type='journey', + journey_submit_id='123', +) + +res = s.submissions.create_submission(req) + +if res is not None: + # handle response + pass + +``` + + +### 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 +from epilot.models import components + +s = epilot.Epilot( + server_url="https://submission.sls.epilot.io", +) + +req = components.SubmissionPayload( + entities=[ + components.SubmissionEntity( + schema=components.Schema.SUBMISSION, + additional_properties={ + '_schema': 'submission', + 'description': 'Submission created via API', + 'contact_first_name': 'First', + 'contact_last_name': 'Last', + 'contact_email': 'example@submission.com', + 'request': 'I would like to know more about electric vehicles', + 'files': '', }, - topic="EMAIL_MARKETING", + description='Submission created via API', + files=[ + components.Files( + s3ref=components.S3Reference( + bucket='epilot-user-content', + key='temp/123/4d689aeb-1497-4410-a9fe-b36ca9ac4389/document.pdf', + ), + filename='document.pdf', + ), + ], ), ], - organization_id="123", - source_id="ce99875f-fba9-4fe2-a8f9-afaf52059051", - source_type="journey", + organization_id='123', + source_id='ce99875f-fba9-4fe2-a8f9-afaf52059051', + source_type='journey', + journey_submit_id='123', ) - + res = s.submissions.create_submission(req) -if res.status_code == 200: +if res is not None: # handle response + pass + ``` - + + + +## Custom HTTP Client + +The Python SDK makes API calls using the [requests](https://pypi.org/project/requests/) 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 a custom `requests.Session` object. - -## SDK Available Operations +For example, you could specify a header for every request that this sdk makes as follows: +```python +import epilot +import requests + +http_client = requests.Session() +http_client.headers.update({'x-custom-header': 'someValue'}) +s = epilot.Epilot(client=http_client) +``` + + -### submissions -* `create_submission` - createSubmission - ### SDK Generated by [Speakeasy](https://docs.speakeasyapi.dev/docs/using-speakeasy/client-sdks) diff --git a/submission/RELEASES.md b/submission/RELEASES.md index 2ba9053d42..b88be5a479 100644 --- a/submission/RELEASES.md +++ b/submission/RELEASES.md @@ -34,4 +34,12 @@ Based on: ### Changes Based on: - OpenAPI Doc 1.0.0 https://docs.api.epilot.io/submission-api.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-04-23 00:20:54 +### Changes +Based on: +- OpenAPI Doc 1.0.0 https://docs.api.epilot.io/submission-api.yaml +- Speakeasy CLI 1.269.1 (2.312.1) https://github.com/speakeasy-api/speakeasy +### Generated +- [python v1.3.0] submission \ No newline at end of file diff --git a/submission/USAGE.md b/submission/USAGE.md old mode 100755 new mode 100644 index f99c116400..1f31c8c733 --- a/submission/USAGE.md +++ b/submission/USAGE.md @@ -1,54 +1,46 @@ - + ```python import epilot -from epilot.models import operations, shared +from epilot.models import components s = epilot.Epilot() - -req = shared.SubmissionPayload( - ivy_opportunity_ids=[ - "deserunt", - "porro", - "nulla", - ], +req = components.SubmissionPayload( entities=[ - { - "perspiciatis": "nulla", - "nihil": "fuga", - "facilis": "eum", - "iusto": "ullam", - }, - { - "inventore": "sapiente", - "enim": "eum", - "voluptatum": "autem", - "vel": "non", - }, - { - "similique": "reprehenderit", - "molestiae": "quo", - }, - ], - journey_submit_id="123", - opt_ins=[ - shared.OptIn( - identifier="example@email.com", - meta={ - "dicta": "est", - "voluptatem": "consequatur", + components.SubmissionEntity( + schema=components.Schema.SUBMISSION, + additional_properties={ + '_schema': 'submission', + 'description': 'Submission created via API', + 'contact_first_name': 'First', + 'contact_last_name': 'Last', + 'contact_email': 'example@submission.com', + 'request': 'I would like to know more about electric vehicles', + 'files': '', }, - topic="EMAIL_MARKETING", + description='Submission created via API', + files=[ + components.Files( + s3ref=components.S3Reference( + bucket='epilot-user-content', + key='temp/123/4d689aeb-1497-4410-a9fe-b36ca9ac4389/document.pdf', + ), + filename='document.pdf', + ), + ], ), ], - organization_id="123", - source_id="ce99875f-fba9-4fe2-a8f9-afaf52059051", - source_type="journey", + organization_id='123', + source_id='ce99875f-fba9-4fe2-a8f9-afaf52059051', + source_type='journey', + journey_submit_id='123', ) - + res = s.submissions.create_submission(req) -if res.status_code == 200: +if res is not None: # handle response + pass + ``` - \ No newline at end of file + \ No newline at end of file diff --git a/submission/docs/models/components/files.md b/submission/docs/models/components/files.md new file mode 100644 index 0000000000..422a4c8ebd --- /dev/null +++ b/submission/docs/models/components/files.md @@ -0,0 +1,12 @@ +# Files + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | +| `s3ref` | [components.S3Reference](../../models/components/s3reference.md) | :heavy_check_mark: | S3 Reference from File API | +| `additional_properties` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | +| `tags` | List[*str*] | :heavy_minus_sign: | List of tags for File entities | +| `filename` | *Optional[str]* | :heavy_minus_sign: | Override the file name | +| `relation_tags` | List[*str*] | :heavy_minus_sign: | List of relation labels for File attachments | \ No newline at end of file diff --git a/submission/docs/models/components/httpmetadata.md b/submission/docs/models/components/httpmetadata.md new file mode 100644 index 0000000000..5febcce063 --- /dev/null +++ b/submission/docs/models/components/httpmetadata.md @@ -0,0 +1,9 @@ +# HTTPMetadata + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | +| `response` | [requests.Response](https://requests.readthedocs.io/en/latest/api/#requests.Response) | :heavy_check_mark: | Raw HTTP response; suitable for custom response parsing | +| `request` | [requests.Request](https://requests.readthedocs.io/en/latest/api/#requests.Request) | :heavy_check_mark: | Raw HTTP request; suitable for debugging | \ No newline at end of file diff --git a/submission/docs/models/components/optin.md b/submission/docs/models/components/optin.md new file mode 100644 index 0000000000..14c95bda5a --- /dev/null +++ b/submission/docs/models/components/optin.md @@ -0,0 +1,10 @@ +# OptIn + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------ | ------------------ | ------------------ | ------------------ | ------------------ | +| `identifier` | *Optional[str]* | :heavy_minus_sign: | Consent identifier | example@email.com | +| `meta` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | | +| `topic` | *Optional[str]* | :heavy_minus_sign: | N/A | EMAIL_MARKETING | \ No newline at end of file diff --git a/submission/docs/models/components/s3reference.md b/submission/docs/models/components/s3reference.md new file mode 100644 index 0000000000..75994bcaf4 --- /dev/null +++ b/submission/docs/models/components/s3reference.md @@ -0,0 +1,11 @@ +# S3Reference + +S3 Reference from File API + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | +| `bucket` | *str* | :heavy_check_mark: | N/A | epilot-user-content | +| `key` | *str* | :heavy_check_mark: | N/A | temp/123/4d689aeb-1497-4410-a9fe-b36ca9ac4389/document.pdf | \ No newline at end of file diff --git a/submission/docs/models/components/schema.md b/submission/docs/models/components/schema.md new file mode 100644 index 0000000000..2dcb7523b6 --- /dev/null +++ b/submission/docs/models/components/schema.md @@ -0,0 +1,8 @@ +# Schema + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `SUBMISSION` | submission | \ No newline at end of file diff --git a/submission/docs/models/components/submissionentity.md b/submission/docs/models/components/submissionentity.md new file mode 100644 index 0000000000..c2f1179ac6 --- /dev/null +++ b/submission/docs/models/components/submissionentity.md @@ -0,0 +1,13 @@ +# SubmissionEntity + +The submission entity to create + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `schema` | [components.Schema](../../models/components/schema.md) | :heavy_check_mark: | N/A | | +| `additional_properties` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | {
"_schema": "submission",
"description": "Submission created via API",
"contact_first_name": "First",
"contact_last_name": "Last",
"contact_email": "example@submission.com",
"request": "I would like to know more about electric vehicles",
"files": [
{
"s3ref": {
"bucket": "epilot-user-content",
"key": "temp/123/4d689aeb-1497-4410-a9fe-b36ca9ac4389/document.pdf"
},
"filename": "document.pdf"
}
]
} | +| `description` | *Optional[str]* | :heavy_minus_sign: | Readable description of the submission. Will be used as the title if passed | | +| `files` | List[[components.Files](../../models/components/files.md)] | :heavy_minus_sign: | Files to attach to Submission Entity as a relation (s3refs from File API)
| | \ No newline at end of file diff --git a/submission/docs/models/components/submissionpayload.md b/submission/docs/models/components/submissionpayload.md new file mode 100644 index 0000000000..bf174133c6 --- /dev/null +++ b/submission/docs/models/components/submissionpayload.md @@ -0,0 +1,16 @@ +# SubmissionPayload + +Holds content and meta information + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| `entities` | List[[components.SubmissionEntity](../../models/components/submissionentity.md)] | :heavy_check_mark: | Entities to create from submission
| | +| `organization_id` | *str* | :heavy_check_mark: | organization id | 123 | +| `source_id` | *str* | :heavy_check_mark: | identifier for source e.g. journey ID or frontend ID | ce99875f-fba9-4fe2-a8f9-afaf52059051 | +| `source_type` | *str* | :heavy_check_mark: | type of source, e.g. journey or frontend | journey | +| ~~`ivy_opportunity_ids`~~ | List[*str*] | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

Related Ivy Opportunity Ids | | +| `journey_submit_id` | *Optional[str]* | :heavy_minus_sign: | journey submit uid | 123 | +| `opt_ins` | List[[components.OptIn](../../models/components/optin.md)] | :heavy_minus_sign: | Opt-ins to create from submission
| | \ No newline at end of file diff --git a/submission/docs/models/operations/createsubmissionresponse.md b/submission/docs/models/operations/createsubmissionresponse.md new file mode 100644 index 0000000000..3613e52c52 --- /dev/null +++ b/submission/docs/models/operations/createsubmissionresponse.md @@ -0,0 +1,8 @@ +# CreateSubmissionResponse + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `http_meta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/submission/docs/sdks/epilot/README.md b/submission/docs/sdks/epilot/README.md new file mode 100644 index 0000000000..20e90c2442 --- /dev/null +++ b/submission/docs/sdks/epilot/README.md @@ -0,0 +1,10 @@ +# Epilot SDK + + +## Overview + +Submission API: Use this API to handle submissions entities from external sources e.g. journeys and frontends + + +### Available Operations + diff --git a/submission/docs/sdks/submissions/README.md b/submission/docs/sdks/submissions/README.md new file mode 100644 index 0000000000..502a0946a6 --- /dev/null +++ b/submission/docs/sdks/submissions/README.md @@ -0,0 +1,78 @@ +# Submissions +(*submissions*) + +## Overview + +Journey Submission + +### Available Operations + +* [create_submission](#create_submission) - createSubmission + +## create_submission + +Creates a submission from a public facing Journey + + +### Example Usage + +```python +import epilot +from epilot.models import components + +s = epilot.Epilot() + +req = components.SubmissionPayload( + entities=[ + components.SubmissionEntity( + schema=components.Schema.SUBMISSION, + additional_properties={ + '_schema': 'submission', + 'description': 'Submission created via API', + 'contact_first_name': 'First', + 'contact_last_name': 'Last', + 'contact_email': 'example@submission.com', + 'request': 'I would like to know more about electric vehicles', + 'files': '', + }, + description='Submission created via API', + files=[ + components.Files( + s3ref=components.S3Reference( + bucket='epilot-user-content', + key='temp/123/4d689aeb-1497-4410-a9fe-b36ca9ac4389/document.pdf', + ), + filename='document.pdf', + ), + ], + ), + ], + organization_id='123', + source_id='ce99875f-fba9-4fe2-a8f9-afaf52059051', + source_type='journey', + journey_submit_id='123', +) + +res = s.submissions.create_submission(req) + +if res is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `request` | [components.SubmissionPayload](../../models/components/submissionpayload.md) | :heavy_check_mark: | The request object to use for the request. | + + +### Response + +**[operations.CreateSubmissionResponse](../../models/operations/createsubmissionresponse.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4xx-5xx | */* | diff --git a/submission/gen.yaml b/submission/gen.yaml index 789de5f7c1..d4204b85ec 100644 --- a/submission/gen.yaml +++ b/submission/gen.yaml @@ -1,16 +1,37 @@ -configVersion: 1.0.0 -management: - docChecksum: 89cb5b3bf127d6ae2e1c29fa5742affa - 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: + dependencies: {} + extraDependencies: + dev: {} author: epilot + clientServerStatusCodesAsErrors: true description: Python Client SDK for Epilot + flattenGlobalSecurity: true + imports: + option: openapi + paths: + callbacks: models/callbacks + errors: models/errors + operations: models/operations + shared: models/components + webhooks: models/webhooks + inputModelSuffix: input + maxMethodParams: 4 + outputModelSuffix: output packageName: epilot-submission + projectUrls: {} + responseFormat: envelope-http diff --git a/submission/py.typed b/submission/py.typed new file mode 100644 index 0000000000..3e38f1a929 --- /dev/null +++ b/submission/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. The package enables type hints. diff --git a/submission/pylintrc b/submission/pylintrc old mode 100755 new mode 100644 index 81c63b93fe..a165907e9e --- a/submission/pylintrc +++ b/submission/pylintrc @@ -88,7 +88,7 @@ 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 @@ -116,20 +116,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 @@ -184,7 +179,8 @@ good-names=i, k, ex, Run, - _ + _, + e # Good variable names regexes, separated by a comma. If names match any regex, # they will always be accepted @@ -438,7 +434,15 @@ disable=raw-checker-failed, 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 # 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 @@ -619,7 +623,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/submission/setup.py b/submission/setup.py old mode 100755 new mode 100644 index a6a164c948..3a54b00aba --- a/submission/setup.py +++ b/submission/setup.py @@ -1,39 +1,55 @@ """Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" import setuptools +import re try: - with open("README.md", "r") as fh: + with open('README.md', 'r') as fh: long_description = fh.read() + GITHUB_URL = 'https://github.com/epilot-dev/sdk-python.git' + GITHUB_URL = GITHUB_URL[: -len('.git')] if GITHUB_URL.endswith('.git') else GITHUB_URL + # links on PyPI should have absolute URLs + long_description = re.sub( + r'(\[[^\]]+\]\()((?!https?:)[^\)]+)(\))', + lambda m: m.group(1) + GITHUB_URL + '/blob/master/' + m.group(2) + m.group(3), + long_description, + ) except FileNotFoundError: - long_description = "" + long_description = '' setuptools.setup( - name="epilot-submission", - version="1.2.2", - author="epilot", - description="Python Client SDK for Epilot", + name='epilot-submission', + version='1.3.0', + author='epilot', + description='Python Client SDK for Epilot', + url='https://github.com/epilot-dev/sdk-python.git', long_description=long_description, - long_description_content_type="text/markdown", - packages=setuptools.find_packages(where="src"), + 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", + "certifi>=2023.7.22", + "charset-normalizer>=3.2.0", + "dataclasses-json>=0.6.4", + "idna>=3.4", + "jsonpath-python>=1.0.6", + "marshmallow>=3.19.0", + "mypy-extensions>=1.0.0", + "packaging>=23.1", + "python-dateutil>=2.8.2", + "requests>=2.31.0", + "six>=1.16.0", + "typing-inspect>=0.9.0", + "typing_extensions>=4.7.1", + "urllib3>=1.26.18", ], + extras_require={ + "dev": [ + "pylint==3.1.0", + ], + }, package_dir={'': 'src'}, - python_requires='>=3.9' + python_requires='>=3.8', + package_data={ + 'epilot-submission': ['py.typed'] + }, ) diff --git a/submission/src/epilot/__init__.py b/submission/src/epilot/__init__.py old mode 100755 new mode 100644 index b9e232018a..e6c0deeb64 --- a/submission/src/epilot/__init__.py +++ b/submission/src/epilot/__init__.py @@ -1,3 +1,4 @@ """Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" from .sdk import * +from .sdkconfiguration import * diff --git a/submission/src/epilot/_hooks/__init__.py b/submission/src/epilot/_hooks/__init__.py new file mode 100644 index 0000000000..5fd985a8ad --- /dev/null +++ b/submission/src/epilot/_hooks/__init__.py @@ -0,0 +1,5 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +from .sdkhooks import * +from .types import * +from .registration import * diff --git a/submission/src/epilot/_hooks/registration.py b/submission/src/epilot/_hooks/registration.py new file mode 100644 index 0000000000..1db6a52934 --- /dev/null +++ b/submission/src/epilot/_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/submission/src/epilot/_hooks/sdkhooks.py b/submission/src/epilot/_hooks/sdkhooks.py new file mode 100644 index 0000000000..17750b62ca --- /dev/null +++ b/submission/src/epilot/_hooks/sdkhooks.py @@ -0,0 +1,57 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +import requests +from .types import SDKInitHook, BeforeRequestContext, BeforeRequestHook, AfterSuccessContext, AfterSuccessHook, AfterErrorContext, AfterErrorHook, Hooks +from .registration import init_hooks +from typing import List, Optional, Tuple + + +class SDKHooks(Hooks): + def __init__(self): + 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: requests.Session) -> Tuple[str, requests.Session]: + 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: requests.PreparedRequest) -> requests.PreparedRequest: + 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: requests.Response) -> requests.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[requests.Response], error: Optional[Exception]) -> Tuple[Optional[requests.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/submission/src/epilot/_hooks/types.py b/submission/src/epilot/_hooks/types.py new file mode 100644 index 0000000000..b24c14146e --- /dev/null +++ b/submission/src/epilot/_hooks/types.py @@ -0,0 +1,74 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +import requests as requests_http +from abc import ABC, abstractmethod +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: requests_http.Session) -> Tuple[str, requests_http.Session]: + pass + + +class BeforeRequestHook(ABC): + @abstractmethod + def before_request(self, hook_ctx: BeforeRequestContext, request: requests_http.PreparedRequest) -> Union[requests_http.PreparedRequest, Exception]: + pass + + +class AfterSuccessHook(ABC): + @abstractmethod + def after_success(self, hook_ctx: AfterSuccessContext, response: requests_http.Response) -> Union[requests_http.Response, Exception]: + pass + + +class AfterErrorHook(ABC): + @abstractmethod + def after_error(self, hook_ctx: AfterErrorContext, response: Optional[requests_http.Response], error: Optional[Exception]) -> Union[Tuple[Optional[requests_http.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/submission/src/epilot/models/__init__.py b/submission/src/epilot/models/__init__.py old mode 100755 new mode 100644 index 889f8adcf4..722bb99827 --- a/submission/src/epilot/models/__init__.py +++ b/submission/src/epilot/models/__init__.py @@ -1,2 +1,4 @@ """Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +# package diff --git a/submission/src/epilot/models/components/__init__.py b/submission/src/epilot/models/components/__init__.py new file mode 100644 index 0000000000..e7ed835fbe --- /dev/null +++ b/submission/src/epilot/models/components/__init__.py @@ -0,0 +1,9 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +from .httpmetadata import * +from .optin import * +from .s3reference import * +from .submissionentity import * +from .submissionpayload import * + +__all__ = ["Files","HTTPMetadata","OptIn","S3Reference","Schema","SubmissionEntity","SubmissionPayload"] diff --git a/submission/src/epilot/models/components/httpmetadata.py b/submission/src/epilot/models/components/httpmetadata.py new file mode 100644 index 0000000000..5a87cb4efd --- /dev/null +++ b/submission/src/epilot/models/components/httpmetadata.py @@ -0,0 +1,17 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +from __future__ import annotations +import dataclasses +import requests as requests_http +from dataclasses_json import Undefined, dataclass_json + + +@dataclass_json(undefined=Undefined.EXCLUDE) +@dataclasses.dataclass +class HTTPMetadata: + response: requests_http.Response = dataclasses.field(metadata={'dataclasses_json': { 'exclude': lambda f: True }}) + r"""Raw HTTP response; suitable for custom response parsing""" + request: requests_http.Request = dataclasses.field(metadata={'dataclasses_json': { 'exclude': lambda f: True }}) + r"""Raw HTTP request; suitable for debugging""" + + diff --git a/submission/src/epilot/models/shared/optin.py b/submission/src/epilot/models/components/optin.py old mode 100755 new mode 100644 similarity index 74% rename from submission/src/epilot/models/shared/optin.py rename to submission/src/epilot/models/components/optin.py index 4e148ae0f7..f6ef3e31f7 --- a/submission/src/epilot/models/shared/optin.py +++ b/submission/src/epilot/models/components/optin.py @@ -4,15 +4,15 @@ import dataclasses from dataclasses_json import Undefined, dataclass_json from epilot import utils -from typing import Any, Optional +from typing import Any, Dict, Optional @dataclass_json(undefined=Undefined.EXCLUDE) @dataclasses.dataclass class OptIn: - identifier: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('identifier'), 'exclude': lambda f: f is None }}) - r"""Consent identifier""" - meta: Optional[dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('meta'), 'exclude': lambda f: f is None }}) - topic: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('topic'), 'exclude': lambda f: f is None }}) - \ No newline at end of file + r"""Consent identifier""" + meta: Optional[Dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('meta'), 'exclude': lambda f: f is None }}) + topic: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('topic'), 'exclude': lambda f: f is None }}) + + diff --git a/submission/src/epilot/models/components/s3reference.py b/submission/src/epilot/models/components/s3reference.py new file mode 100644 index 0000000000..5e7156d049 --- /dev/null +++ b/submission/src/epilot/models/components/s3reference.py @@ -0,0 +1,16 @@ +"""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 + + +@dataclass_json(undefined=Undefined.EXCLUDE) +@dataclasses.dataclass +class S3Reference: + r"""S3 Reference from File API""" + bucket: str = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('bucket') }}) + key: str = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('key') }}) + + diff --git a/submission/src/epilot/models/components/submissionentity.py b/submission/src/epilot/models/components/submissionentity.py new file mode 100644 index 0000000000..8e38ba2590 --- /dev/null +++ b/submission/src/epilot/models/components/submissionentity.py @@ -0,0 +1,44 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +from __future__ import annotations +import dataclasses +from .s3reference import S3Reference +from dataclasses_json import Undefined, dataclass_json +from enum import Enum +from epilot import utils +from typing import Any, Dict, List, Optional + +class Schema(str, Enum): + SUBMISSION = 'submission' + + +@dataclass_json(undefined=Undefined.EXCLUDE) +@dataclasses.dataclass +class Files: + UNSET='__SPEAKEASY_UNSET__' + s3ref: S3Reference = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('s3ref') }}) + r"""S3 Reference from File API""" + additional_properties: Optional[Dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'exclude': lambda f: f is None }}) + tags: Optional[List[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('_tags'), 'exclude': lambda f: f is None }}) + r"""List of tags for File entities""" + filename: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('filename'), 'exclude': lambda f: f is None }}) + r"""Override the file name""" + relation_tags: Optional[List[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('relation_tags'), 'exclude': lambda f: f is None }}) + r"""List of relation labels for File attachments""" + + + + +@dataclass_json(undefined=Undefined.EXCLUDE) +@dataclasses.dataclass +class SubmissionEntity: + r"""The submission entity to create""" + UNSET='__SPEAKEASY_UNSET__' + schema: Schema = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('_schema') }}) + additional_properties: Optional[Dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { '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 }}) + r"""Readable description of the submission. Will be used as the title if passed""" + files: Optional[List[Files]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('files'), 'exclude': lambda f: f is None }}) + r"""Files to attach to Submission Entity as a relation (s3refs from File API)""" + + diff --git a/submission/src/epilot/models/shared/submissionpayload.py b/submission/src/epilot/models/components/submissionpayload.py old mode 100755 new mode 100644 similarity index 54% rename from submission/src/epilot/models/shared/submissionpayload.py rename to submission/src/epilot/models/components/submissionpayload.py index be943dc72f..06bfc8c5f6 --- a/submission/src/epilot/models/shared/submissionpayload.py +++ b/submission/src/epilot/models/components/submissionpayload.py @@ -2,33 +2,33 @@ from __future__ import annotations import dataclasses -from ..shared import optin as shared_optin +from .optin import OptIn +from .submissionentity import SubmissionEntity from dataclasses_json import Undefined, dataclass_json from epilot import utils -from typing import Any, Optional +from typing import List, Optional @dataclass_json(undefined=Undefined.EXCLUDE) @dataclasses.dataclass class SubmissionPayload: r"""Holds content and meta information""" - - entities: list[dict[str, Any]] = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('entities') }}) - r"""Entities to create from submission - - """ + entities: List[SubmissionEntity] = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('entities') }}) + r"""Entities to create from submission""" organization_id: str = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('organization_id') }}) - r"""organization id""" + r"""organization id""" source_id: str = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('source_id') }}) - r"""identifier for source e.g. journey ID or frontend ID""" + r"""identifier for source e.g. journey ID or frontend ID""" source_type: str = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('source_type') }}) - r"""type of source, e.g. journey or frontend""" - ivy_opportunity_ids: Optional[list[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('_ivy_opportunity_ids'), 'exclude': lambda f: f is None }}) - r"""Related Ivy Opportunity Ids""" + r"""type of source, e.g. journey or frontend""" + ivy_opportunity_ids: Optional[List[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('_ivy_opportunity_ids'), 'exclude': lambda f: f is None }}) + r"""Related Ivy Opportunity Ids + + Deprecated field: This will be removed in a future release, please migrate away from it as soon as possible. + """ journey_submit_id: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('journey_submit_id'), 'exclude': lambda f: f is None }}) - r"""journey submit uid""" - opt_ins: Optional[list[shared_optin.OptIn]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('opt_ins'), 'exclude': lambda f: f is None }}) - r"""Opt-ins to create from submission + r"""journey submit uid""" + opt_ins: Optional[List[OptIn]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('opt_ins'), 'exclude': lambda f: f is None }}) + r"""Opt-ins to create from submission""" - """ - \ No newline at end of file + diff --git a/submission/src/epilot/models/errors/__init__.py b/submission/src/epilot/models/errors/__init__.py new file mode 100644 index 0000000000..88d0916936 --- /dev/null +++ b/submission/src/epilot/models/errors/__init__.py @@ -0,0 +1,5 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +from .sdkerror import * + +__all__ = ["SDKError"] diff --git a/submission/src/epilot/models/errors/sdkerror.py b/submission/src/epilot/models/errors/sdkerror.py new file mode 100644 index 0000000000..6bb02bbd61 --- /dev/null +++ b/submission/src/epilot/models/errors/sdkerror.py @@ -0,0 +1,24 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +import requests as requests_http + + +class SDKError(Exception): + """Represents an error returned by the API.""" + message: str + status_code: int + body: str + raw_response: requests_http.Response + + def __init__(self, message: str, status_code: int, body: str, raw_response: requests_http.Response): + self.message = message + self.status_code = status_code + self.body = body + self.raw_response = raw_response + + 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/submission/src/epilot/models/operations/__init__.py b/submission/src/epilot/models/operations/__init__.py old mode 100755 new mode 100644 diff --git a/submission/src/epilot/models/operations/createsubmission.py b/submission/src/epilot/models/operations/createsubmission.py old mode 100755 new mode 100644 index 64112745c5..227a3fad28 --- a/submission/src/epilot/models/operations/createsubmission.py +++ b/submission/src/epilot/models/operations/createsubmission.py @@ -2,14 +2,11 @@ from __future__ import annotations import dataclasses -import requests as requests_http -from typing import Optional +from ...models.components import httpmetadata as components_httpmetadata @dataclasses.dataclass class CreateSubmissionResponse: + http_meta: components_httpmetadata.HTTPMetadata = dataclasses.field() - 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/submission/src/epilot/models/shared/__init__.py b/submission/src/epilot/models/shared/__init__.py deleted file mode 100755 index 36a4fdd7a9..0000000000 --- a/submission/src/epilot/models/shared/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from .optin import * -from .submissionpayload import * - -__all__ = ["OptIn","SubmissionPayload"] diff --git a/submission/src/epilot/sdk.py b/submission/src/epilot/sdk.py old mode 100755 new mode 100644 index 8e8a4c1d52..d694fea657 --- a/submission/src/epilot/sdk.py +++ b/submission/src/epilot/sdk.py @@ -1,67 +1,67 @@ """Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" import requests as requests_http -from . import utils +from .sdkconfiguration import SDKConfiguration from .submissions import Submissions - -SERVERS = [ - "https://submission.sls.epilot.io", -] -"""Contains the list of servers available to the SDK""" +from .utils.retries import RetryConfig +from epilot import utils +from epilot._hooks import SDKHooks +from typing import Dict, Optional class Epilot: - r"""Use this API to handle submissions entities from external sources e.g. journeys and frontends - - """ + r"""Submission API: Use this API to handle submissions entities from external sources e.g. journeys and frontends""" submissions: Submissions r"""Journey Submission""" - _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" + sdk_configuration: SDKConfiguration def __init__(self, - server_url: str = None, - url_params: dict[str, str] = None, - client: requests_http.Session = None + server_idx: Optional[int] = None, + server_url: Optional[str] = None, + url_params: Optional[Dict[str, str]] = None, + client: Optional[requests_http.Session] = None, + retry_config: Optional[RetryConfig] = None ) -> None: """Instantiates the SDK configuring it with the provided parameters. - + + :param server_idx: The index of the server to use for all operations + :type server_idx: int :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] + :type url_params: Dict[str, str] :param client: The requests.Session HTTP client to use for all operations - :type client: requests_http.Session + :type client: requests_http.Session + :param retry_config: The utils.RetryConfig to use globally + :type retry_config: RetryConfig """ - self._client = requests_http.Session() - - + if client is None: + 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 + server_url = utils.template_url(server_url, url_params) + + + self.sdk_configuration = SDKConfiguration( + client, + server_url, + server_idx, + retry_config=retry_config + ) - if client is not None: - self._client = client - - self._security_client = self._client - + 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.submissions = Submissions( - self._client, - self._security_client, - self._server_url, - self._language, - self._sdk_version, - self._gen_version - ) - - \ No newline at end of file + self.submissions = Submissions(self.sdk_configuration) diff --git a/submission/src/epilot/sdkconfiguration.py b/submission/src/epilot/sdkconfiguration.py new file mode 100644 index 0000000000..750f1c694d --- /dev/null +++ b/submission/src/epilot/sdkconfiguration.py @@ -0,0 +1,42 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + + +import requests as requests_http +from ._hooks import SDKHooks +from .utils import utils +from .utils.retries import RetryConfig +from dataclasses import dataclass +from typing import Dict, Optional, Tuple + + +SERVERS = [ + 'https://submission.sls.epilot.io', +] +"""Contains the list of servers available to the SDK""" + +@dataclass +class SDKConfiguration: + client: requests_http.Session + 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.312.1' + user_agent: str = 'speakeasy-sdk/python 1.3.0 2.312.1 1.0.0 epilot-submission' + retry_config: Optional[RetryConfig] = 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 utils.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/submission/src/epilot/submissions.py b/submission/src/epilot/submissions.py old mode 100755 new mode 100644 index 7feafdcffa..48e32b32b5 --- a/submission/src/epilot/submissions.py +++ b/submission/src/epilot/submissions.py @@ -1,50 +1,69 @@ """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 .sdkconfiguration import SDKConfiguration +from epilot import utils +from epilot._hooks import AfterErrorContext, AfterSuccessContext, BeforeRequestContext, HookContext +from epilot.models import components, errors, operations +from typing import Optional class Submissions: r"""Journey Submission""" - _client: requests_http.Session - _security_client: requests_http.Session - _server_url: str - _language: str - _sdk_version: str - _gen_version: str + sdk_configuration: SDKConfiguration - 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_submission(self, request: shared.SubmissionPayload) -> operations.CreateSubmissionResponse: + def __init__(self, sdk_config: SDKConfiguration) -> None: + self.sdk_configuration = sdk_config + + + + def create_submission(self, request: Optional[components.SubmissionPayload]) -> operations.CreateSubmissionResponse: r"""createSubmission Creates a submission from a public facing Journey - """ - base_url = self._server_url + hook_ctx = HookContext(operation_id='createSubmission', oauth2_scopes=[], security_source=None) + base_url = utils.template_url(*self.sdk_configuration.get_server_details()) - url = base_url.removesuffix('/') + '/v1/submission/submissions' + url = base_url + '/v1/submission/submissions' 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._client + req_content_type, data, form = utils.serialize_request_body(request, Optional[components.SubmissionPayload], "request", False, True, 'json') + if req_content_type is not None and req_content_type not in ('multipart/form-data', 'multipart/mixed'): + headers['content-type'] = req_content_type + headers['Accept'] = '*/*' + headers['user-agent'] = self.sdk_configuration.user_agent + client = self.sdk_configuration.client - http_res = client.request('POST', url, data=data, files=form, headers=headers) - content_type = http_res.headers.get('Content-Type') + try: + req = client.prepare_request(requests_http.Request('POST', url, data=data, files=form, headers=headers)) + req = self.sdk_configuration.get_hooks().before_request(BeforeRequestContext(hook_ctx), req) + http_res = client.send(req) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), None, e) + if e is not None: + raise e - res = operations.CreateSubmissionResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) + if utils.match_status_codes(['4XX','5XX'], http_res.status_code): + result, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), http_res, None) + if e is not None: + raise e + if result is not None: + http_res = result + else: + http_res = self.sdk_configuration.get_hooks().after_success(AfterSuccessContext(hook_ctx), http_res) + + + + res = operations.CreateSubmissionResponse(http_meta=components.HTTPMetadata(request=req, response=http_res)) if http_res.status_code == 201: pass + elif http_res.status_code >= 400 and http_res.status_code < 500 or http_res.status_code >= 500 and http_res.status_code < 600: + raise errors.SDKError('API error occurred', http_res.status_code, http_res.text, http_res) + else: + raise errors.SDKError('unknown status code received', http_res.status_code, http_res.text, http_res) return res - \ No newline at end of file + + diff --git a/submission/src/epilot/utils/__init__.py b/submission/src/epilot/utils/__init__.py old mode 100755 new mode 100644 diff --git a/submission/src/epilot/utils/retries.py b/submission/src/epilot/utils/retries.py old mode 100755 new mode 100644 index c6251d948e..c40fc413c0 --- a/submission/src/epilot/utils/retries.py +++ b/submission/src/epilot/utils/retries.py @@ -2,6 +2,7 @@ import random import time +from typing import List import requests @@ -24,16 +25,17 @@ class RetryConfig: backoff: BackoffStrategy retry_connection_errors: bool - def __init__(self, strategy: str, 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] + status_codes: List[str] - def __init__(self, config: RetryConfig, status_codes: list[str]): + def __init__(self, config: RetryConfig, status_codes: List[str]): self.config = config self.status_codes = status_codes @@ -73,12 +75,12 @@ def do_request(): if res.status_code == parsed_code: raise TemporaryError(res) except requests.exceptions.ConnectionError as exception: - if not retries.config.config.retry_connection_errors: + if retries.config.retry_connection_errors: raise raise PermanentError(exception) from exception except requests.exceptions.Timeout as exception: - if not retries.config.config.retry_connection_errors: + if retries.config.retry_connection_errors: raise raise PermanentError(exception) from exception @@ -112,7 +114,6 @@ def retry_with_backoff(func, initial_interval=500, max_interval=60000, exponent= raise sleep = ((initial_interval/1000) * exponent**retries + random.uniform(0, 1)) - if sleep > max_interval/1000: - sleep = max_interval/1000 + sleep = min(sleep, max_interval / 1000) time.sleep(sleep) retries += 1 diff --git a/submission/src/epilot/utils/utils.py b/submission/src/epilot/utils/utils.py old mode 100755 new mode 100644 index 9d4fba3248..b238ff2f1e --- a/submission/src/epilot/utils/utils.py +++ b/submission/src/epilot/utils/utils.py @@ -3,37 +3,35 @@ import base64 import json import re -from dataclasses import Field, dataclass, fields, is_dataclass, make_dataclass +import sys +from dataclasses import Field, fields, is_dataclass, make_dataclass from datetime import date, datetime +from decimal import Decimal from email.message import Message from enum import Enum -from typing import Any, Callable, Optional, Tuple, Union, get_args, get_origin +from typing import ( + Any, + Callable, + Dict, + List, + Optional, + Tuple, + Union, + get_args, + get_origin, +) from xmlrpc.client import boolean - +from typing_inspect import is_optional_type 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) +def get_security(security: Any) -> Tuple[Dict[str, str], Dict[str, str]]: + headers: Dict[str, str] = {} + query_params: Dict[str, str] = {} if security is None: - return client + return headers, query_params sec_fields: Tuple[Field, ...] = fields(security) for sec_field in sec_fields: @@ -41,267 +39,380 @@ def configure_security_client(client: requests.Session, security: dataclass): if value is None: continue - metadata = sec_field.metadata.get('security') + 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'): + if metadata.get("option"): + _parse_security_option(headers, query_params, value) + return headers, query_params + 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) + _parse_security_scheme(headers, query_params, metadata, security) else: - _parse_security_scheme(client, metadata, value) + _parse_security_scheme(headers, query_params, metadata, value) - return client + return headers, query_params -def _parse_security_option(client: SecurityClient, option: dataclass): +def _parse_security_option( + headers: Dict[str, str], query_params: Dict[str, str], option: Any +): 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: + 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)) + headers, query_params, 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') +def _parse_security_scheme( + headers: Dict[str, str], + query_params: Dict[str, str], + 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) + if scheme_type == "http" and sub_type == "basic": + _parse_basic_auth_scheme(headers, 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: + 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) + headers, query_params, scheme_metadata, metadata, value + ) else: _parse_security_scheme_value( - client, scheme_metadata, scheme_metadata, scheme) + headers, query_params, 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') +def _parse_security_scheme_value( + headers: Dict[str, str], + query_params: Dict[str, str], + 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') + header_name = str(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 + if sub_type == "header": + headers[header_name] = value + elif sub_type == "query": + query_params[header_name] = value else: - raise Exception('not supported') + 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 + 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 Exception('not supported') + raise Exception("not supported") else: - raise Exception('not supported') + raise Exception("not supported") + + +def _apply_bearer(token: str) -> str: + return token.lower().startswith("bearer ") and token or f"Bearer {token}" -def _parse_basic_auth_scheme(client: SecurityClient, scheme: dataclass): +def _parse_basic_auth_scheme(headers: Dict[str, str], scheme: Any): 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: + metadata = scheme_field.metadata.get("security") + if metadata is None or metadata.get("field_name") is None: continue - field_name = metadata.get('field_name') + field_name = metadata.get("field_name") value = getattr(scheme, scheme_field.name) - if field_name == 'username': + if field_name == "username": username = value - if field_name == 'password': + if field_name == "password": password = value - data = f'{username}:{password}'.encode() - client.client.headers['Authorization'] = f'Basic {base64.b64encode(data).decode()}' + data = f"{username}:{password}".encode() + 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) +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] = [] + + path_param_fields: Tuple[Field, ...] = fields(path_params) for field in path_param_fields: - request_metadata = field.metadata.get('request') - if request_metadata is not None: + if field.name in skip_fields: continue - param_metadata = field.metadata.get('path_param') + 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 + param = getattr(path_params, field.name) if path_params is not None else None + param, global_found = _populate_from_globals( + field.name, param, "path_param", gbls + ) + if global_found: + globals_already_populated.append(field.name) - parm_name = param_value_metadata.get( - 'field_name', field.name) + if param is None: + continue - 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) + f_name = param_metadata.get("field_name", field.name) + serialization = param_metadata.get("serialization", "") + if serialization != "": + serialized_params = _get_serialized_params( + param_metadata, field.type, f_name, param + ) + for key, value in serialized_params.items(): + path_param_values[key] = value + else: + if param_metadata.get("style", "simple") == "simple": + 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_param_values[param_metadata.get("field_name", field.name)] = ( + ",".join(pp_vals) + ) + 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_param_values[param_metadata.get("field_name", field.name)] = ( + ",".join(pp_vals) + ) + elif not isinstance(param, (str, int, float, complex, bool, Decimal)): + 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 + + param_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"{param_name}={_val_to_string(param_field_val)}" + ) + else: + pp_vals.append( + f"{param_name},{_val_to_string(param_field_val)}" + ) + path_param_values[param_metadata.get("field_name", field.name)] = ( + ",".join(pp_vals) + ) + else: + path_param_values[param_metadata.get("field_name", field.name)] = ( + _val_to_string(param) + ) - return server_url.removesuffix("/") + path + 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: +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) + 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]] = {} +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] = [] - param_fields: Tuple[Field, ...] = fields(clazz) + param_fields: Tuple[Field, ...] = fields(query_params) for field in param_fields: - request_metadata = field.metadata.get('request') - if request_metadata is not None: + if field.name in skip_fields: continue - metadata = field.metadata.get('query_param') + 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 = getattr(query_params, param_name) if query_params is not None else None - value = _populate_from_globals(param_name, value, 'queryParam', gbls) + value, global_found = _populate_from_globals( + param_name, value, "query_param", gbls + ) + if global_found: + globals_already_populated.append(param_name) f_name = metadata.get("field_name") - serialization = metadata.get('serialization', '') - if serialization != '': - params = params | _get_serialized_query_params( - metadata, f_name, value) + serialization = metadata.get("serialization", "") + if serialization != "": + serialized_parms = _get_serialized_params( + metadata, field.type, f_name, value + ) + 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.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) + style = metadata.get("style", "form") + if style == "deepObject": + _populate_deep_object_query_params( + metadata, 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 Exception('not yet implemented') - return params + raise Exception("not yet implemented") + + return globals_already_populated + +def get_headers(headers_params: Any, gbls: Optional[Any] = None) -> Dict[str, str]: + headers: Dict[str, str] = {} -def get_headers(headers_params: dataclass) -> dict[str, str]: - if headers_params is None: - return {} + 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 - headers: dict[str, str] = {} + +def _populate_headers( + headers_params: Any, + gbls: Any, + header_values: Dict[str, str], + skip_fields: List[str], +) -> List[str]: + globals_already_populated: List[str] = [] param_fields: Tuple[Field, ...] = fields(headers_params) for field in param_fields: - metadata = field.metadata.get('header') + if field.name in skip_fields: + continue + + metadata = field.metadata.get("header") if not metadata: continue - value = _serialize_header(metadata.get( - 'explode', False), getattr(headers_params, field.name)) + value, global_found = _populate_from_globals( + field.name, getattr(headers_params, field.name), "header", gbls + ) + if global_found: + globals_already_populated.append(field.name) + value = _serialize_header(metadata.get("explode", False), value) - if value != '': - headers[metadata.get('field_name', field.name)] = value + if value != "": + header_values[metadata.get("field_name", field.name)] = value - return headers + return globals_already_populated -def _get_serialized_query_params(metadata: dict, field_name: str, obj: any) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} +def _get_serialized_params( + metadata: Dict, field_type: type, field_name: str, obj: Any +) -> Dict[str, str]: + params: Dict[str, str] = {} - serialization = metadata.get('serialization', '') - if serialization == 'json': - params[metadata.get("field_name", field_name)] = marshal_json(obj) + serialization = metadata.get("serialization", "") + if serialization == "json": + params[metadata.get("field_name", field_name)] = marshal_json(obj, field_type) return params -def _get_deep_object_query_params(metadata: dict, field_name: str, obj: any) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} - +def _populate_deep_object_query_params( + metadata: Dict, field_name: str, obj: Any, params: Dict[str, List[str]] +): if obj is None: - return params + return 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') + obj_param_metadata = obj_field.metadata.get("query_param") if not obj_param_metadata: continue @@ -309,45 +420,55 @@ def _get_deep_object_query_params(metadata: dict, field_name: str, obj: any) -> if obj_val is None: continue - if isinstance(obj_val, list): + 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)}]'] = [ - ] + 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)) + 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): + 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): + 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}]'] = [ - ] + 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)) + 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 + _val_to_string(value) + ] def _get_query_param_field_name(obj_field: Field) -> str: - obj_param_metadata = obj_field.metadata.get('query_param') + obj_param_metadata = obj_field.metadata.get("query_param") if not obj_param_metadata: return "" @@ -355,48 +476,87 @@ def _get_query_param_field_name(obj_field: Field) -> str: 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) +def _populate_delimited_query_params( + metadata: Dict, + field_name: str, + obj: Any, + delimiter: str, + query_param_values: Dict[str, List[str]], +): + _populate_form( + field_name, + metadata.get("explode", True), + obj, + _get_query_param_field_name, + delimiter, + query_param_values, + ) 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', + "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]: +def serialize_request_body( + request: Any, + request_type: type, + request_field_name: str, + nullable: bool, + optional: bool, + serialization_method: str, + encoder=None, +) -> Tuple[Optional[str], Optional[Any], Optional[Any]]: if request is None: - return None, None, None, None + if not nullable and optional: + return 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) + return serialize_content_type( + request_field_name, + request_type, + SERIALIZATION_METHOD_TO_CONTENT_TYPE[serialization_method], + request, + encoder, + ) request_val = getattr(request, request_field_name) + if request_val is None: + if not nullable and optional: + return None, None, None + 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') + 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: + raise Exception("invalid request type") + + return serialize_content_type( + request_field_name, + request_type, + request_metadata.get("media_type", "application/octet-stream"), + request_val, + ) + + +def serialize_content_type( + field_name: str, request_type: Any, media_type: str, request: Any, encoder=None +) -> Tuple[Optional[str], Optional[Any], Optional[List[List[Any]]]]: + if re.match(r"(application|text)\/.*?\+*json.*", media_type) is not None: + return media_type, marshal_json(request, request_type, encoder), 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: + 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 @@ -404,11 +564,14 @@ def serialize_content_type(field_name: str, media_type: str, request: dataclass) return media_type, request, None raise Exception( - f"invalid request body type {type(request)} for mediaType {media_type}") + 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]] = [] +def serialize_multipart_form( + media_type: str, request: Any +) -> Tuple[str, Any, List[List[Any]]]: + form: List[List[Any]] = [] request_fields = fields(request) for field in request_fields: @@ -416,7 +579,7 @@ def serialize_multipart_form(media_type: str, request: dataclass) -> Tuple[str, if val is None: continue - field_metadata = field.metadata.get('multipart_form') + field_metadata = field.metadata.get("multipart_form") if not field_metadata: continue @@ -428,42 +591,42 @@ def serialize_multipart_form(media_type: str, request: dataclass) -> Tuple[str, content = bytes() for file_field in file_fields: - file_metadata = file_field.metadata.get('multipart_form') + 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) + 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') + 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"]] + to_append = [ + field_metadata.get("field_name", field.name), + [None, marshal_json(val, field.type), "application/json"], + ] form.append(to_append) else: - field_name = field_metadata.get( - "field_name", field.name) - if isinstance(val, list): + 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)]]) + 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]]: +def serialize_dict( + original: Dict, explode: bool, field_name, existing: Optional[Dict[str, List[str]]] +) -> Dict[str, List[str]]: if existing is None: - existing = [] + existing = {} if explode is True: for key, val in original.items(): @@ -481,8 +644,8 @@ def serialize_dict(original: dict, explode: bool, field_name, existing: Optional return existing -def serialize_form_data(field_name: str, data: dataclass) -> dict[str, any]: - form: dict[str, list[str]] = {} +def serialize_form_data(field_name: str, data: Any) -> Dict[str, Any]: + form: Dict[str, List[str]] = {} if is_dataclass(data): for field in fields(data): @@ -490,32 +653,37 @@ def serialize_form_data(field_name: str, data: dataclass) -> dict[str, any]: if val is None: continue - metadata = field.metadata.get('form') + metadata = field.metadata.get("form") if metadata is None: continue - field_name = metadata.get('field_name', field.name) + field_name = metadata.get("field_name", field.name) - if metadata.get('json'): - form[field_name] = [marshal_json(val)] + if metadata.get("json"): + form[field_name] = [marshal_json(val, field.type)] else: - if metadata.get('style', 'form') == 'form': - form = form | _populate_form( - field_name, metadata.get('explode', True), val, _get_form_field_name) + if metadata.get("style", "form") == "form": + _populate_form( + field_name, + metadata.get("explode", True), + val, + _get_form_field_name, + ",", + form, + ) else: - raise Exception( - f'Invalid form style for field {field.name}') - elif isinstance(data, dict): + 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}') + 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') + obj_param_metadata = obj_field.metadata.get("form") if not obj_param_metadata: return "" @@ -523,11 +691,16 @@ def _get_form_field_name(obj_field: Field) -> str: 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]] = {} - +def _populate_form( + field_name: str, + explode: boolean, + obj: Any, + get_field_name_func: Callable, + delimiter: str, + form: Dict[str, List[str]], +): if obj is None: - return params + return form if is_dataclass(obj): items = [] @@ -535,7 +708,7 @@ def _populate_form(field_name: str, explode: boolean, obj: any, get_field_name_f 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 == '': + if obj_field_name == "": continue val = getattr(obj, obj_field.name) @@ -543,27 +716,26 @@ def _populate_form(field_name: str, explode: boolean, obj: any, get_field_name_f continue if explode: - params[obj_field_name] = [_val_to_string(val)] + form[obj_field_name] = [_val_to_string(val)] else: - items.append( - f'{obj_field_name},{_val_to_string(val)}') + items.append(f"{obj_field_name}{delimiter}{_val_to_string(val)}") if len(items) > 0: - params[field_name] = [','.join(items)] - elif isinstance(obj, dict): + form[field_name] = [delimiter.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) + form[key] = [_val_to_string(value)] else: - items.append(f'{key},{_val_to_string(value)}') + items.append(f"{key}{delimiter}{_val_to_string(value)}") if len(items) > 0: - params[field_name] = [','.join(items)] - elif isinstance(obj, list): + form[field_name] = [delimiter.join(items)] + elif isinstance(obj, List): items = [] for value in obj: @@ -571,36 +743,35 @@ def _populate_form(field_name: str, explode: boolean, obj: any, get_field_name_f continue if explode: - if not field_name in params: - params[field_name] = [] - params[field_name].append(_val_to_string(value)) + 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: - params[field_name] = [','.join([str(item) for item in items])] + form[field_name] = [delimiter.join([str(item) for item in items])] else: - params[field_name] = [_val_to_string(obj)] + form[field_name] = [_val_to_string(obj)] - return params + return form -def _serialize_header(explode: bool, obj: any) -> str: +def _serialize_header(explode: bool, obj: Any) -> str: if obj is None: - return '' + 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') + 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 == '': + obj_field_name = obj_param_metadata.get("field_name", obj_field.name) + if obj_field_name == "": continue val = getattr(obj, obj_field.name) @@ -608,15 +779,14 @@ def _serialize_header(explode: bool, obj: any) -> str: continue if explode: - items.append( - f'{obj_field_name}={_val_to_string(val)}') + 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): + return ",".join(items) + elif isinstance(obj, Dict): items = [] for key, value in obj.items(): @@ -624,14 +794,14 @@ def _serialize_header(explode: bool, obj: any) -> str: continue if explode: - items.append(f'{key}={_val_to_string(value)}') + 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): + return ",".join([str(item) for item in items]) + elif isinstance(obj, List): items = [] for value in obj: @@ -641,27 +811,36 @@ def _serialize_header(explode: bool, obj: any) -> str: items.append(_val_to_string(value)) if len(items) > 0: - return ','.join(items) + return ",".join(items) else: - return f'{_val_to_string(obj)}' + return f"{_val_to_string(obj)}" - return '' + return "" -def unmarshal_json(data, typ): - unmarhsal = make_dataclass('Unmarhsal', [('res', typ)], - bases=(DataClassJsonMixin,)) +def unmarshal_json(data, typ, decoder=None): + unmarshal = make_dataclass("Unmarshal", [("res", typ)], bases=(DataClassJsonMixin,)) json_dict = json.loads(data) - out = unmarhsal.from_dict({"res": json_dict}) - return out.res + try: + out = unmarshal.from_dict({"res": json_dict}) + except AttributeError as attr_err: + raise AttributeError( + f"unable to unmarshal {data} as {typ} - {attr_err}" + ) from attr_err + + return out.res if decoder is None else decoder(out.res) + +def marshal_json(val, typ, encoder=None): + if not is_optional_type(typ) and val is None: + raise ValueError(f"Could not marshal None into non-optional type: {typ}") -def marshal_json(val): - marshal = make_dataclass('Marshal', [('res', type(val))], - bases=(DataClassJsonMixin,)) + marshal = make_dataclass("Marshal", [("res", typ)], bases=(DataClassJsonMixin,)) marshaller = marshal(res=val) json_dict = marshaller.to_dict() - return json.dumps(json_dict["res"]) + val = json_dict["res"] if encoder is None else encoder(json_dict["res"]) + + return json.dumps(val, separators=(",", ":"), sort_keys=True) def match_content_type(content_type: str, pattern: str) -> boolean: @@ -669,7 +848,7 @@ def match_content_type(content_type: str, pattern: str) -> boolean: return True msg = Message() - msg['content-type'] = content_type + msg["content-type"] = content_type media_type = msg.get_content_type() if media_type == pattern: @@ -677,12 +856,22 @@ def match_content_type(content_type: str, pattern: str) -> boolean: parts = media_type.split("/") if len(parts) == 2: - if pattern in (f'{parts[0]}/*', f'*/{parts[1]}'): + 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: + 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 + + def datetimeisoformat(optional: bool): def isoformatoptional(val): if optional and val is None: @@ -705,6 +894,111 @@ def datefromisoformat(date_str: str): return dateutil.parser.parse(date_str).date() +def bigintencoder(optional: bool): + def bigintencode(val: int): + if optional and val is None: + return None + return str(val) + + return bigintencode + + +def bigintdecoder(val): + if isinstance(val, float): + raise ValueError(f"{val} is a float") + return int(val) + + +def decimalencoder(optional: bool, as_str: bool): + def decimalencode(val: Decimal): + if optional and val is None: + return None + + if as_str: + return str(val) + + return float(val) + + return decimalencode + + +def decimaldecoder(val): + return Decimal(str(val)) + + +def map_encoder(optional: bool, value_encoder: Callable): + def map_encode(val: Dict): + if optional and val is None: + return None + + encoded = {} + for key, value in val.items(): + encoded[key] = value_encoder(value) + + return encoded + + return map_encode + + +def map_decoder(value_decoder: Callable): + def map_decode(val: Dict): + decoded = {} + for key, value in val.items(): + decoded[key] = value_decoder(value) + + return decoded + + return map_decode + + +def list_encoder(optional: bool, value_encoder: Callable): + def list_encode(val: List): + if optional and val is None: + return None + + encoded = [] + for value in val: + encoded.append(value_encoder(value)) + + return encoded + + return list_encode + + +def list_decoder(value_decoder: Callable): + def list_decode(val: List): + decoded = [] + for value in val: + decoded.append(value_decoder(value)) + + return decoded + + return list_decode + + +def union_encoder(all_encoders: Dict[str, Callable]): + def selective_encoder(val: Any): + if type(val) in all_encoders: + return all_encoders[type(val)](val) + return val + + return selective_encoder + + +def union_decoder(all_decoders: List[Callable]): + def selective_decoder(val: Any): + decoded = val + for decoder in all_decoders: + try: + decoded = decoder(val) + break + except (TypeError, ValueError): + continue + return decoded + + return selective_decoder + + def get_field_name(name): def override(_, _field_name=name): return _field_name @@ -712,24 +1006,55 @@ def override(_, _field_name=name): return override -def _val_to_string(val): +def _val_to_string(val) -> str: if isinstance(val, bool): return str(val).lower() if isinstance(val, datetime): - return val.isoformat().replace('+00:00', 'Z') + return str(val.isoformat().replace("+00:00", "Z")) if isinstance(val, Enum): - return val.value + return str(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 +def _populate_from_globals( + param_name: str, value: Any, param_type: str, gbls: Any +) -> Tuple[Any, bool]: + if gbls is None: + return value, False + + global_fields = fields(gbls) + + found = False + for field in global_fields: + if field.name is not param_name: + continue + + found = True + + if value is not None: + return value, True + + global_value = getattr(gbls, field.name) + + param_metadata = field.metadata.get(param_type) + if param_metadata is None: + return value, True + + return global_value, True + + return value, found + + +def decoder_with_discriminator(field_name): + def decode_fx(obj): + kls = getattr(sys.modules["sdk.models.components"], obj[field_name]) + return unmarshal_json(json.dumps(obj), kls) + + return decode_fx + - return value +def remove_suffix(input_string, suffix): + if suffix and input_string.endswith(suffix): + return input_string[: -len(suffix)] + return input_string diff --git a/submission/tests/helpers.py b/submission/tests/helpers.py new file mode 100644 index 0000000000..b3d0950402 --- /dev/null +++ b/submission/tests/helpers.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +import re + + +def sort_query_parameters(url): + parts = url.split("?") + + if len(parts) == 1: + return url + + query = parts[1] + params = query.split("&") + + params.sort(key=lambda x: x.split('=')[0]) + + return parts[0] + "?" + "&".join(params) + + +def sort_serialized_maps(inp: any, regex: str, delim: str): + + def sort_map(m): + entire_match = m.group(0) + + groups = m.groups() + + for group in groups: + pairs = [] + if '=' in group: + pairs = group.split(delim) + + pairs.sort(key=lambda x: x.split('=')[0]) + else: + values = group.split(delim) + + if len(values) == 1: + pairs = values + else: + pairs = [''] * int(len(values)/2) + # loop though every 2nd item + for i in range(0, len(values), 2): + pairs[int(i/2)] = values[i] + delim + values[i+1] + + pairs.sort(key=lambda x: x.split(delim)[0]) + + entire_match = entire_match.replace(group, delim.join(pairs)) + + return entire_match + + if isinstance(inp, str): + return re.sub(regex, sort_map, inp) + elif isinstance(inp, list): + for i, v in enumerate(inp): + inp[i] = sort_serialized_maps(v, regex, delim) + return inp + elif isinstance(inp, dict): + for k, v in inp.items(): + inp[k] = sort_serialized_maps(v, regex, delim) + return inp + else: + raise Exception("Unsupported type")