diff --git a/.github/workflows/check-supported-versions.yaml b/.github/workflows/check-supported-versions.yaml index 430b0ea815c..56992b9811e 100644 --- a/.github/workflows/check-supported-versions.yaml +++ b/.github/workflows/check-supported-versions.yaml @@ -26,6 +26,7 @@ jobs: - name: Set up JDK ${{ matrix.java }} uses: actions/setup-java@v2 with: + distribution: 'adopt' java-version: ${{ matrix.java }} - uses: actions/cache@v2.1.5 diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 98f191f2c9c..d991e052a7d 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -16,6 +16,7 @@ jobs: - name: Set up JDK 11 uses: actions/setup-java@v2 with: + distribution: 'adopt' java-version: 11 - name: Compile with Maven run: mvn -B -q clean install jacoco:report diff --git a/CI/.drone.yml b/CI/.drone.yml index 037fb654724..032d64b9e15 100644 --- a/CI/.drone.yml +++ b/CI/.drone.yml @@ -1,6 +1,5 @@ kind: pipeline name: default - steps: # test Java 11 HTTP client - name: java11-test @@ -53,4 +52,12 @@ steps: - name: haskell-client-test image: haskell:8.6.5 commands: - - (cd samples/client/petstore/haskell-http-client/ && stack --install-ghc --no-haddock-deps haddock --fast && stack test --fast) + - (cd samples/client/petstore/haskell-http-client/ && stack --allow-different-user --install-ghc --no-haddock-deps haddock --fast && stack --allow-different-user test --fast) +# test erlang client and server +- name: erlang + image: erlang:alpine + commands: + - (cd samples/client/petstore/erlang-client && rebar3 compile) + - (cd samples/client/petstore/erlang-proper && rebar3 compile) + # comment out as the tests pass locally but not in the CI + #- (cd samples/server/petstore/erlang-server && rebar3 compile) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 30258ec9fd6..0fe833163af 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -48,6 +48,7 @@ Code change should conform to the programming style guide of the respective lang - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - C++: https://google.github.io/styleguide/cppguide.html - C++ (Tizen): https://wiki.tizen.org/Native_Platform_Coding_Idiom_and_Style_Guide#C.2B.2B_Coding_Style +- C++ (Unreal Engine 4): https://docs.unrealengine.com/en-US/ProductionPipelines/DevelopmentSetup/CodingStandard/index.html - Clojure: https://github.com/bbatsov/clojure-style-guide - Crystal: https://crystal-lang.org/reference/conventions/coding_style.html - Dart: https://www.dartlang.org/guides/language/effective-dart/style diff --git a/README.md b/README.md index c27f86b1531..97e01df1c97 100644 --- a/README.md +++ b/README.md @@ -9,27 +9,17 @@
-[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`5.1.1`): +[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`5.2.0`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) [![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) -[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=master)](https://app.shippable.com/github/OpenAPITools/openapi-generator) [![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu) [![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/master)](https://cloud.drone.io/OpenAPITools/openapi-generator) [![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/master?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67) [![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/openapitools/openapi-generator/Check%20Supported%20Java%20Versions/master?label=Check%20Supported%20Java%20Versions&logo=github&logoColor=green)](https://github.com/OpenAPITools/openapi-generator/actions?query=workflow%3A%22Check+Supported+Java+Versions%22) -[5.2.x](https://github.com/OpenAPITools/openapi-generator/tree/5.2.x) (`5.2.x`): -[![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/5.2.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) -[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/5.2.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) -[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=5.2.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator) -[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=5.2.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu) -[![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/5.2.x)](https://cloud.drone.io/OpenAPITools/openapi-generator) -[![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/5.2.x?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67) - [6.0.x](https://github.com/OpenAPITools/openapi-generator/tree/6.0.x) (`6.0.x`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/6.0.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) [![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/6.0.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) -[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=6.0.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator) [![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=6.0.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu) [![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/6.0.x)](https://cloud.drone.io/OpenAPITools/openapi-generator) [![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/6.0.x?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67) @@ -120,9 +110,8 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 | OpenAPI Generator Version | Release Date | Notes | | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------- | | 6.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/6.0.0-SNAPSHOT/) | Nov/Dec 2021 | Minor release with breaking changes (no fallback) | -| 5.2.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.2.0-SNAPSHOT/) | May/Jun 2021 | Minor release with breaking changes (with fallback) | -| 5.1.1 (upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.1.1-SNAPSHOT/) | Apr/May 2021 | Patch release (enhancements, bug fixes, etc) | -| [5.1.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.1.0) (latest stable release) | 20.03.2021 | Minor release with breaking changes (with fallback) | +| 5.2.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.2.0-SNAPSHOT/) | Jun/Jul 2021 | Minor release with breaking changes (with fallback) | +| [5.1.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.1.1) (latest stable release) | 07.05.2021 | Patch release (enhancements, bug fixes, etc) | | [4.3.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.3.1) | 06.05.2020 | Patch release (enhancements, bug fixes, etc) | OpenAPI Spec compatibility: 1.0, 1.1, 1.2, 2.0, 3.0 @@ -179,16 +168,16 @@ See the different versions of the [openapi-generator-cli](https://mvnrepository. If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum): -JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.0/openapi-generator-cli-5.1.0.jar` +JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.1/openapi-generator-cli-5.1.1.jar` For **Mac/Linux** users: ```sh -wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.0/openapi-generator-cli-5.1.0.jar -O openapi-generator-cli.jar +wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.1/openapi-generator-cli-5.1.1.jar -O openapi-generator-cli.jar ``` For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g. ``` -Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.0/openapi-generator-cli-5.1.0.jar +Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.1/openapi-generator-cli-5.1.1.jar ``` After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage. @@ -413,7 +402,7 @@ openapi-generator-cli version To use a specific version of "openapi-generator-cli" ```sh -openapi-generator-cli version-manager set 5.1.0 +openapi-generator-cli version-manager set 5.1.1 ``` Or install it as dev-dependency: @@ -437,7 +426,7 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat (if you're on Windows, replace the last command with `java -jar modules\openapi-generator-cli\target\openapi-generator-cli.jar generate -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g php -o c:\temp\php_api_client`) -You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.0/openapi-generator-cli-5.1.0.jar) +You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.1/openapi-generator-cli-5.1.1.jar) To get a list of **general** options available, please run `java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar help generate` @@ -562,7 +551,7 @@ When code is generated from this project, it shall be considered **AS IS** and o ### [3.5 - IDE Integration](#table-of-contents) -Here is a list of community-conitributed IDE plug-ins that integrate with OpenAPI Generator: +Here is a list of community-contributed IDE plug-ins that integrate with OpenAPI Generator: - Eclipse: [Codewind OpenAPI Tools for Eclipse](https://www.eclipse.org/codewind/open-api-tools-for-eclipse.html) by [IBM](https://www.ibm.com) - IntelliJ IDEA: [OpenAPI Generator](https://plugins.jetbrains.com/plugin/8433-openapi-generator) by [Jim Schubert](https://jimschubert.us/#/) @@ -666,6 +655,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - [Twitter](https://twitter.com) - [unblu inc.](https://www.unblu.com/) - [Veamly](https://www.veamly.com/) +- [VMWare](https://www.vmware.com/) - [wbt-solutions](https://www.wbt-solutions.de/) - [Woleet](https://www.woleet.io/) - [WSO2](https://wso2.com/) @@ -821,8 +811,8 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - 2021-03-28 - [Trying out NestJS part 4: Generate Typescript clients from OpenAPI documents](https://dev.to/arnaudcortisse/trying-out-nestjs-part-4-generate-typescript-clients-from-openapi-documents-28mk) by [Arnaud Cortisse](https://dev.to/arnaudcortisse) - 2021-03-31 - [Open API Server Implementation Using OpenAPI Generator](https://www.baeldung.com/java-openapi-generator-server) at [Baeldung](https://www.baeldung.com/) - 2021-03-31 - [使用OpenAPI Generator實現Open API Server](https://www.1ju.org/article/java-openapi-generator-server) at [億聚網](https://www.1ju.org/) -- 2022-04-19 - [Introducing Twilio’s OpenAPI Specification Beta](https://www.twilio.com/blog/introducing-twilio-open-api-specification-beta) by [GARETH PAUL JONES](https://www.twilio.com/blog/author/gpj) at [Twilio Blog](https://www.twilio.com/blog) -- 2022-04-22 - [Leveraging OpenApi strengths in a Micro-Service environment](https://medium.com/unibuddy-technology-blog/leveraging-openapi-strengths-in-a-micro-service-environment-3d7f9e7c26ff) by Nicolas Jellab at [Unibuddy Technology Blog](https://medium.com/unibuddy-technology-blog) +- 2021-04-19 - [Introducing Twilio’s OpenAPI Specification Beta](https://www.twilio.com/blog/introducing-twilio-open-api-specification-beta) by [GARETH PAUL JONES](https://www.twilio.com/blog/author/gpj) at [Twilio Blog](https://www.twilio.com/blog) +- 2021-04-22 - [Leveraging OpenApi strengths in a Micro-Service environment](https://medium.com/unibuddy-technology-blog/leveraging-openapi-strengths-in-a-micro-service-environment-3d7f9e7c26ff) by Nicolas Jellab at [Unibuddy Technology Blog](https://medium.com/unibuddy-technology-blog) ## [6 - About Us](#table-of-contents) diff --git a/bin/configs/other/cpp-pistache-server-cpp-pistache.yaml b/bin/configs/cpp-pistache-server-cpp-pistache.yaml similarity index 100% rename from bin/configs/other/cpp-pistache-server-cpp-pistache.yaml rename to bin/configs/cpp-pistache-server-cpp-pistache.yaml diff --git a/bin/configs/kotlin-json-request-string.yaml b/bin/configs/kotlin-json-request-string.yaml index 8f1dade28c9..375622ae5df 100644 --- a/bin/configs/kotlin-json-request-string.yaml +++ b/bin/configs/kotlin-json-request-string.yaml @@ -5,3 +5,4 @@ templateDir: modules/openapi-generator/src/main/resources/kotlin-client additionalProperties: requestDateConverter: toString artifactId: kotlin-petstore-json-request-string + parcelizeModels: true diff --git a/bin/configs/ktorm-schema.yaml b/bin/configs/ktorm-schema.yaml index aff895cb279..d3c5beb9a33 100644 --- a/bin/configs/ktorm-schema.yaml +++ b/bin/configs/ktorm-schema.yaml @@ -1,7 +1,7 @@ generatorName: ktorm-schema outputDir: samples/schema/petstore/ktorm -inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/ktorm-schema additionalProperties: hideGenerationTimestamp: true - importModelPackageName: org.openapitools.client.models \ No newline at end of file + importModelPackageName: org.openapitools.client.models diff --git a/bin/configs/nim.yaml b/bin/configs/nim.yaml index 136a92764c3..13a27a6b764 100644 --- a/bin/configs/nim.yaml +++ b/bin/configs/nim.yaml @@ -1,6 +1,6 @@ generatorName: nim outputDir: samples/client/petstore/nim -inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/nim-client additionalProperties: packageName: petstore diff --git a/docs/contributing.md b/docs/contributing.md index a791b0d6f1b..fe325ae17e1 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -52,6 +52,7 @@ Code change should conform to the programming style guide of the respective lang - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - C++: https://google.github.io/styleguide/cppguide.html - C++ (Tizen): https://wiki.tizen.org/Native_Platform_Coding_Idiom_and_Style_Guide#C.2B.2B_Coding_Style +- C++ (Unreal Engine 4): https://docs.unrealengine.com/en-US/ProductionPipelines/DevelopmentSetup/CodingStandard/index.html - Clojure: https://github.com/bbatsov/clojure-style-guide - Crystal: https://crystal-lang.org/reference/conventions/coding_style.html - Dart: https://www.dartlang.org/guides/language/effective-dart/style diff --git a/docs/generators.md b/docs/generators.md index 521bdc3dbf0..6cb063b2230 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -106,6 +106,7 @@ The following generators are available: * [jaxrs-resteasy-eap](generators/jaxrs-resteasy-eap.md) * [jaxrs-spec](generators/jaxrs-spec.md) * [kotlin-server](generators/kotlin-server.md) +* [kotlin-server-deprecated (deprecated)](generators/kotlin-server-deprecated.md) * [kotlin-spring](generators/kotlin-spring.md) * [kotlin-vertx (beta)](generators/kotlin-vertx.md) * [nodejs-express-server (beta)](generators/nodejs-express-server.md) diff --git a/docs/generators/README.md b/docs/generators/README.md index 6510770e47a..a8ac9c9310c 100644 --- a/docs/generators/README.md +++ b/docs/generators/README.md @@ -91,6 +91,7 @@ The following generators are available: * [jaxrs-resteasy-eap](jaxrs-resteasy-eap.md) * [jaxrs-spec](jaxrs-spec.md) * [kotlin-server](kotlin-server.md) +* [kotlin-server-deprecated](kotlin-server-deprecated.md) * [kotlin-spring](kotlin-spring.md) * [kotlin-vertx (beta)](kotlin-vertx.md) * [nodejs-express-server (beta)](nodejs-express-server.md) diff --git a/docs/generators/aspnetcore.md b/docs/generators/aspnetcore.md index 0a30830099f..99f0b789bdc 100644 --- a/docs/generators/aspnetcore.md +++ b/docs/generators/aspnetcore.md @@ -7,9 +7,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | -|aspnetCoreVersion|ASP.NET Core version: 5.0, 3.1, 3.0, 2.2, 2.1, 2.0 (deprecated)| |3.1| -|buildTarget|Target to build an application or library| |program| -|classModifier|Class Modifier for controller classes: Empty string or abstract.| || +|aspnetCoreVersion|ASP.NET Core version: 5.0, 3.1, 3.0, 2.2, 2.1, 2.0 (deprecated)|
**2.0**
ASP.NET Core 2.0
**2.1**
ASP.NET Core 2.1
**2.2**
ASP.NET Core 2.2
**3.0**
ASP.NET Core 3.0
**3.1**
ASP.NET Core 3.1
**5.0**
ASP.NET Core 5.0
|3.1| +|buildTarget|Target to build an application or library|
**program**
Generate code for a standalone server
**library**
Generate code for a server abstract class library
|program| +|classModifier|Class Modifier for controller classes: Empty string or abstract.|
****
Keep class default with no modifier
**abstract**
Make class abstract
|| |compatibilityVersion|ASP.Net Core CompatibilityVersion| |Version_2_2| |enumNameSuffix|Suffix that will be appended to all enum names.| |Enum| |enumValueSuffix|Suffix that will be appended to all enum values.| |Enum| @@ -17,10 +17,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |isLibrary|Is the build a library| |false| |licenseName|The name of the license| |NoLicense| |licenseUrl|The URL of the license| |http://localhost| -|modelClassModifier|Model Class Modifier can be nothing or partial| |partial| +|modelClassModifier|Model Class Modifier can be nothing or partial|
****
Keep model class default with no modifier
**partial**
Make model class partial
|partial| |newtonsoftVersion|Version for Microsoft.AspNetCore.Mvc.NewtonsoftJson for ASP.NET Core 3.0+| |3.0.0| |operationIsAsync|Set methods to async or sync (default).| |false| -|operationModifier|Operation Modifier can be virtual or abstract| |virtual| +|operationModifier|Operation Modifier can be virtual or abstract|
**virtual**
Keep method virtual
**abstract**
Make method abstract
|virtual| |operationResultTask|Set methods result to Task<>.| |false| |packageAuthors|Specifies Authors property in the .NET Core project file.| |OpenAPI| |packageCopyright|Specifies an AssemblyCopyright for the .NET Framework global assembly attributes stored in the AssemblyInfo file.| |No Copyright| @@ -32,7 +32,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |returnICollection|Return ICollection<T> instead of the concrete type.| |false| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|source folder for generated code| |src| -|swashbuckleVersion|Swashbuckle version: 3.0.0, 4.0.0, 5.0.0| |3.0.0| +|swashbuckleVersion|Swashbuckle version: 3.0.0, 4.0.0, 5.0.0|
**3.0.0**
Swashbuckle 3.0.0
**4.0.0**
Swashbuckle 4.0.0
**5.0.0**
Swashbuckle 5.0.0
|3.0.0| |useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| |useDefaultRouting|Use default routing for the ASP.NET Core version.| |true| diff --git a/docs/generators/kotlin-server-deprecated.md b/docs/generators/kotlin-server-deprecated.md new file mode 100644 index 00000000000..5499354747c --- /dev/null +++ b/docs/generators/kotlin-server-deprecated.md @@ -0,0 +1,214 @@ +--- +title: Config Options for kotlin-server-deprecated +sidebar_label: kotlin-server-deprecated +--- + +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|apiSuffix|suffix for api classes| |Api| +|artifactId|Generated artifact id (name of jar).| |kotlin-server-deprecated| +|artifactVersion|Generated artifact's package version.| |1.0.0| +|enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |camelCase| +|featureAutoHead|Automatically provide responses to HEAD requests for existing routes that have the GET verb defined.| |true| +|featureCORS|Ktor by default provides an interceptor for implementing proper support for Cross-Origin Resource Sharing (CORS). See enable-cors.org.| |false| +|featureCompression|Adds ability to compress outgoing content using gzip, deflate or custom encoder and thus reduce size of the response.| |true| +|featureConditionalHeaders|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |false| +|featureHSTS|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |true| +|groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| +|library|library template (sub-template)|
**ktor**
ktor framework
|ktor| +|modelMutable|Create mutable models| |false| +|packageName|Generated artifact package name.| |org.openapitools.server| +|parcelizeModels|toggle "@Parcelize" for generated models| |null| +|serializableModel|boolean - toggle "implements Serializable" for generated models| |null| +|serializationLibrary|What serialization library to use: 'moshi' (default), or 'gson' or 'jackson'| |moshi| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |null| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null| +|sourceFolder|source folder for generated code| |src/main/kotlin| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | +|BigDecimal|java.math.BigDecimal| +|Date|java.time.LocalDate| +|DateTime|java.time.OffsetDateTime| +|File|java.io.File| +|LocalDate|java.time.LocalDate| +|LocalDateTime|java.time.LocalDateTime| +|LocalTime|java.time.LocalTime| +|Timestamp|java.sql.Timestamp| +|URI|java.net.URI| +|UUID|java.util.UUID| + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|kotlin.collections.ArrayList| +|list|kotlin.collections.ArrayList| +|map|kotlin.collections.HashMap| + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✗|OAS3 +|OAuth2_Implicit|✓|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/kotlin-server.md b/docs/generators/kotlin-server.md index ecaf99a294f..b45dc3ffb4d 100644 --- a/docs/generators/kotlin-server.md +++ b/docs/generators/kotlin-server.md @@ -16,6 +16,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |featureCompression|Adds ability to compress outgoing content using gzip, deflate or custom encoder and thus reduce size of the response.| |true| |featureConditionalHeaders|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |false| |featureHSTS|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |true| +|featureLocations|Generates routes in a typed way, for both: constructing URLs and reading the parameters.| |true| |groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| |library|library template (sub-template)|
**ktor**
ktor framework
|ktor| |modelMutable|Create mutable models| |false| diff --git a/docs/generators/kotlin.md b/docs/generators/kotlin.md index ef76c9af691..f4b0aceeb60 100644 --- a/docs/generators/kotlin.md +++ b/docs/generators/kotlin.md @@ -16,6 +16,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| |library|Library template (sub-template) to use|
**jvm-okhttp4**
[DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0.
**jvm-okhttp3**
Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0.
**jvm-retrofit2**
Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2.
**multiplatform**
Platform: Kotlin multiplatform. HTTP client: Ktor 1.2.4. JSON processing: Kotlinx Serialization: 0.12.0.
|jvm-okhttp4| |modelMutable|Create mutable models| |false| +|moshiCodeGen|Whether to enable codegen with the Moshi library. Refer to the [official Moshi doc](https://github.com/square/moshi#codegen) for more info.| |false| |packageName|Generated artifact package name.| |org.openapitools.client| |parcelizeModels|toggle "@Parcelize" for generated models| |null| |requestDateConverter|JVM-Option. Defines in how to handle date-time objects that are used for a request (as query or parameter)|
**toJson**
[DEFAULT] Date formater option using a json converter.
**toString**
Use the 'toString'-method of the date-time object to retrieve the related string representation.
|toJson| diff --git a/docs/generators/scala-sttp.md b/docs/generators/scala-sttp.md index 5f0c9f7e6ad..77891a59141 100644 --- a/docs/generators/scala-sttp.md +++ b/docs/generators/scala-sttp.md @@ -13,8 +13,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl |dateLibrary|Option. Date library to use|
**joda**
Joda (for legacy app)
**java8**
Java 8 native JSR310 (prefered for JDK 1.8+)
|java8| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| -|jodaTimeVersion|The version of joda-time library| |2.10.6| -|json4sVersion|The version of json4s library| |3.6.8| +|jodaTimeVersion|The version of joda-time library| |2.10.10| +|json4sVersion|The version of json4s library| |3.6.11| |jsonLibrary|Json library to use. Possible values are: json4s and circe.| |json4s| |legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |mainPackage|Top-level package name, which defines 'apiPackage', 'modelPackage', 'invokerPackage'| |org.openapitools.client| @@ -25,7 +25,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|source folder for generated code| |null| -|sttpClientVersion|The version of sttp client| |2.2.0| +|sttpClientVersion|The version of sttp client| |2.2.9| ## IMPORT MAPPING diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java index a52fa88609a..f7c24196331 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java @@ -199,14 +199,14 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { aspnetCoreVersion.addEnum("5.0", "ASP.NET Core 5.0"); aspnetCoreVersion.setDefault("3.1"); aspnetCoreVersion.setOptValue(aspnetCoreVersion.getDefault()); - addOption(aspnetCoreVersion.getOpt(), aspnetCoreVersion.getDescription(), aspnetCoreVersion.getOptValue()); + cliOptions.add(aspnetCoreVersion); swashbuckleVersion.addEnum("3.0.0", "Swashbuckle 3.0.0"); swashbuckleVersion.addEnum("4.0.0", "Swashbuckle 4.0.0"); swashbuckleVersion.addEnum("5.0.0", "Swashbuckle 5.0.0"); swashbuckleVersion.setDefault("3.0.0"); swashbuckleVersion.setOptValue(swashbuckleVersion.getDefault()); - addOption(swashbuckleVersion.getOpt(), swashbuckleVersion.getDescription(), swashbuckleVersion.getOptValue()); + cliOptions.add(swashbuckleVersion); // CLI Switches addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, @@ -261,19 +261,19 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { classModifier.addEnum("abstract", "Make class abstract"); classModifier.setDefault(""); classModifier.setOptValue(classModifier.getDefault()); - addOption(classModifier.getOpt(), classModifier.getDescription(), classModifier.getOptValue()); + cliOptions.add(classModifier); operationModifier.addEnum("virtual", "Keep method virtual"); operationModifier.addEnum("abstract", "Make method abstract"); operationModifier.setDefault("virtual"); operationModifier.setOptValue(operationModifier.getDefault()); - addOption(operationModifier.getOpt(), operationModifier.getDescription(), operationModifier.getOptValue()); + cliOptions.add(operationModifier); buildTarget.addEnum("program", "Generate code for a standalone server"); buildTarget.addEnum("library", "Generate code for a server abstract class library"); buildTarget.setDefault("program"); buildTarget.setOptValue(buildTarget.getDefault()); - addOption(buildTarget.getOpt(), buildTarget.getDescription(), buildTarget.getOptValue()); + cliOptions.add(buildTarget); addSwitch(GENERATE_BODY, "Generates method body.", @@ -292,7 +292,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { modelClassModifier.addEnum("partial", "Make model class partial"); modelClassModifier.setDefault("partial"); modelClassModifier.setOptValue(modelClassModifier.getDefault()); - addOption(modelClassModifier.getOpt(), modelClassModifier.getDescription(), modelClassModifier.getOptValue()); + cliOptions.add(modelClassModifier); } @Override @@ -592,6 +592,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { private void setBuildTarget() { setCliOption(buildTarget); if ("library".equals(buildTarget.getOptValue())) { + LOGGER.warn("buildTarget is {} so changing default isLibrary to true", buildTarget.getOptValue()); isLibrary = true; projectSdk = SDK_LIB; additionalProperties.put(CLASS_MODIFIER, "abstract"); @@ -636,7 +637,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { private void setUseSwashbuckle() { if (isLibrary) { - LOGGER.warn("buildTarget is " + buildTarget.getOptValue() + " so changing default isLibrary to false "); + LOGGER.warn("isLibrary is true so changing default useSwashbuckle to false"); useSwashbuckle = false; } else { useSwashbuckle = true; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java index bf49fd425e0..3064af52c20 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java @@ -128,6 +128,7 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen { typeMapping.put("boolean", "bool"); typeMapping.put("array", "std::vector"); typeMapping.put("map", "std::map"); + typeMapping.put("set", "std::vector"); typeMapping.put("file", "std::string"); typeMapping.put("object", "Object"); typeMapping.put("binary", "std::string"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java index 72646d58cd7..3ff2429d99d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java @@ -61,6 +61,8 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { public static final String REQUEST_DATE_CONVERTER = "requestDateConverter"; public static final String COLLECTION_TYPE = "collectionType"; + public static final String MOSHI_CODE_GEN = "moshiCodeGen"; + protected static final String VENDOR_EXTENSION_BASE_NAME_LITERAL = "x-base-name-literal"; protected String dateLibrary = DateLibrary.JAVA8.value; @@ -204,6 +206,8 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { cliOptions.add(CliOption.newBoolean(USE_RX_JAVA2, "Whether to use the RxJava2 adapter with the retrofit2 library.")); cliOptions.add(CliOption.newBoolean(USE_RX_JAVA3, "Whether to use the RxJava3 adapter with the retrofit2 library.")); cliOptions.add(CliOption.newBoolean(USE_COROUTINES, "Whether to use the Coroutines adapter with the retrofit2 library.")); + + cliOptions.add(CliOption.newBoolean(MOSHI_CODE_GEN, "Whether to enable codegen with the Moshi library. Refer to the [official Moshi doc](https://github.com/square/moshi#codegen) for more info.")); } public CodegenType getTag() { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java index d4d9902da7f..0c182417c94 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java @@ -42,15 +42,17 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { private Boolean hstsFeatureEnabled = true; private Boolean corsFeatureEnabled = false; private Boolean compressionFeatureEnabled = true; + private Boolean locationsFeatureEnabled = true; - // This is here to potentially warn the user when an option is not supoprted by the target framework. + // This is here to potentially warn the user when an option is not supported by the target framework. private Map> optionsSupportedPerFramework = new ImmutableMap.Builder>() .put(Constants.KTOR, Arrays.asList( Constants.AUTOMATIC_HEAD_REQUESTS, Constants.CONDITIONAL_HEADERS, Constants.HSTS, Constants.CORS, - Constants.COMPRESSION + Constants.COMPRESSION, + Constants.LOCATIONS )) .build(); @@ -85,6 +87,8 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { artifactId = "kotlin-server"; packageName = "org.openapitools.server"; + typeMapping.put("array", "kotlin.collections.List"); + // cliOptions default redefinition need to be updated updateOption(CodegenConstants.ARTIFACT_ID, this.artifactId); updateOption(CodegenConstants.PACKAGE_NAME, this.packageName); @@ -110,6 +114,7 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { addSwitch(Constants.HSTS, Constants.HSTS_DESC, getHstsFeatureEnabled()); addSwitch(Constants.CORS, Constants.CORS_DESC, getCorsFeatureEnabled()); addSwitch(Constants.COMPRESSION, Constants.COMPRESSION_DESC, getCompressionFeatureEnabled()); + addSwitch(Constants.LOCATIONS, Constants.LOCATIONS_DESC, getLocationsFeatureEnabled()); } public Boolean getAutoHeadFeatureEnabled() { @@ -156,6 +161,14 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { this.hstsFeatureEnabled = hstsFeatureEnabled; } + public Boolean getLocationsFeatureEnabled() { + return locationsFeatureEnabled; + } + + public void setLocationsFeatureEnabled(Boolean locationsFeatureEnabled) { + this.locationsFeatureEnabled = locationsFeatureEnabled; + } + public String getName() { return "kotlin-server"; } @@ -209,6 +222,12 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { additionalProperties.put(Constants.COMPRESSION, getCompressionFeatureEnabled()); } + if (additionalProperties.containsKey(Constants.LOCATIONS)) { + setLocationsFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.LOCATIONS)); + } else { + additionalProperties.put(Constants.LOCATIONS, getLocationsFeatureEnabled()); + } + boolean generateApis = additionalProperties.containsKey(CodegenConstants.GENERATE_APIS) && (Boolean) additionalProperties.get(CodegenConstants.GENERATE_APIS); String packageFolder = (sourceFolder + File.separator + packageName).replace(".", File.separator); String resourcesFolder = "src/main/resources"; // not sure this can be user configurable. @@ -223,7 +242,7 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { supportingFiles.add(new SupportingFile("AppMain.kt.mustache", packageFolder, "AppMain.kt")); supportingFiles.add(new SupportingFile("Configuration.kt.mustache", packageFolder, "Configuration.kt")); - if (generateApis) { + if (generateApis && locationsFeatureEnabled) { supportingFiles.add(new SupportingFile("Paths.kt.mustache", packageFolder, "Paths.kt")); } @@ -247,6 +266,8 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { public final static String CORS_DESC = "Ktor by default provides an interceptor for implementing proper support for Cross-Origin Resource Sharing (CORS). See enable-cors.org."; public final static String COMPRESSION = "featureCompression"; public final static String COMPRESSION_DESC = "Adds ability to compress outgoing content using gzip, deflate or custom encoder and thus reduce size of the response."; + public final static String LOCATIONS = "featureLocations"; + public final static String LOCATIONS_DESC = "Generates routes in a typed way, for both: constructing URLs and reading the parameters."; } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerDeprecatedCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerDeprecatedCodegen.java new file mode 100644 index 00000000000..84cee1d2aa9 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerDeprecatedCodegen.java @@ -0,0 +1,270 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.languages; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.openapitools.codegen.meta.features.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; + +public class KotlinServerDeprecatedCodegen extends AbstractKotlinCodegen { + + public static final String DEFAULT_LIBRARY = Constants.KTOR; + private final Logger LOGGER = LoggerFactory.getLogger(KotlinServerDeprecatedCodegen.class); + private Boolean autoHeadFeatureEnabled = true; + private Boolean conditionalHeadersFeatureEnabled = false; + private Boolean hstsFeatureEnabled = true; + private Boolean corsFeatureEnabled = false; + private Boolean compressionFeatureEnabled = true; + + // This is here to potentially warn the user when an option is not supported by the target framework. + private Map> optionsSupportedPerFramework = new ImmutableMap.Builder>() + .put(Constants.KTOR, Arrays.asList( + Constants.AUTOMATIC_HEAD_REQUESTS, + Constants.CONDITIONAL_HEADERS, + Constants.HSTS, + Constants.CORS, + Constants.COMPRESSION + )) + .build(); + + /** + * Constructs an instance of `KotlinServerDeprecatedCodegen`. + */ + public KotlinServerDeprecatedCodegen() { + super(); + + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) + .securityFeatures(EnumSet.of( + SecurityFeature.BasicAuth, + SecurityFeature.ApiKey, + SecurityFeature.OAuth2_Implicit + )) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling + ) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie + ) + ); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.DEPRECATED) + .build(); + + artifactId = "kotlin-server-deprecated"; + packageName = "org.openapitools.server"; + + // cliOptions default redefinition need to be updated + updateOption(CodegenConstants.ARTIFACT_ID, this.artifactId); + updateOption(CodegenConstants.PACKAGE_NAME, this.packageName); + + outputFolder = "generated-code" + File.separator + "kotlin-server-deprecated"; + modelTemplateFiles.put("model.mustache", ".kt"); + apiTemplateFiles.put("api.mustache", ".kt"); + embeddedTemplateDir = templateDir = "kotlin-server-deprecated"; + apiPackage = packageName + ".apis"; + modelPackage = packageName + ".models"; + + supportedLibraries.put(Constants.KTOR, "ktor framework"); + + // TODO: Configurable server engine. Defaults to netty in build.gradle. + CliOption library = new CliOption(CodegenConstants.LIBRARY, CodegenConstants.LIBRARY_DESC); + library.setDefault(DEFAULT_LIBRARY); + library.setEnum(supportedLibraries); + + cliOptions.add(library); + + addSwitch(Constants.AUTOMATIC_HEAD_REQUESTS, Constants.AUTOMATIC_HEAD_REQUESTS_DESC, getAutoHeadFeatureEnabled()); + addSwitch(Constants.CONDITIONAL_HEADERS, Constants.CONDITIONAL_HEADERS_DESC, getConditionalHeadersFeatureEnabled()); + addSwitch(Constants.HSTS, Constants.HSTS_DESC, getHstsFeatureEnabled()); + addSwitch(Constants.CORS, Constants.CORS_DESC, getCorsFeatureEnabled()); + addSwitch(Constants.COMPRESSION, Constants.COMPRESSION_DESC, getCompressionFeatureEnabled()); + } + + public Boolean getAutoHeadFeatureEnabled() { + return autoHeadFeatureEnabled; + } + + public void setAutoHeadFeatureEnabled(Boolean autoHeadFeatureEnabled) { + this.autoHeadFeatureEnabled = autoHeadFeatureEnabled; + } + + public Boolean getCompressionFeatureEnabled() { + return compressionFeatureEnabled; + } + + public void setCompressionFeatureEnabled(Boolean compressionFeatureEnabled) { + this.compressionFeatureEnabled = compressionFeatureEnabled; + } + + public Boolean getConditionalHeadersFeatureEnabled() { + return conditionalHeadersFeatureEnabled; + } + + public void setConditionalHeadersFeatureEnabled(Boolean conditionalHeadersFeatureEnabled) { + this.conditionalHeadersFeatureEnabled = conditionalHeadersFeatureEnabled; + } + + public Boolean getCorsFeatureEnabled() { + return corsFeatureEnabled; + } + + public void setCorsFeatureEnabled(Boolean corsFeatureEnabled) { + this.corsFeatureEnabled = corsFeatureEnabled; + } + + public String getHelp() { + return "Generates a Kotlin server (Ktor v1.1.3). IMPORTANT: this generator has been deprecated." + + " Please migrate to `kotlin-server` which supports Ktor v1.5.2+."; + } + + public Boolean getHstsFeatureEnabled() { + return hstsFeatureEnabled; + } + + public void setHstsFeatureEnabled(Boolean hstsFeatureEnabled) { + this.hstsFeatureEnabled = hstsFeatureEnabled; + } + + public String getName() { + return "kotlin-server-deprecated"; + } + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.LIBRARY)) { + this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); + } + + // set default library to "ktor" + if (StringUtils.isEmpty(library)) { + this.setLibrary(DEFAULT_LIBRARY); + additionalProperties.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY); + LOGGER.info("`library` option is empty. Default to " + DEFAULT_LIBRARY); + } + + if (additionalProperties.containsKey(Constants.AUTOMATIC_HEAD_REQUESTS)) { + setAutoHeadFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.AUTOMATIC_HEAD_REQUESTS)); + } else { + additionalProperties.put(Constants.AUTOMATIC_HEAD_REQUESTS, getAutoHeadFeatureEnabled()); + } + + if (additionalProperties.containsKey(Constants.CONDITIONAL_HEADERS)) { + setConditionalHeadersFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.CONDITIONAL_HEADERS)); + } else { + additionalProperties.put(Constants.CONDITIONAL_HEADERS, getConditionalHeadersFeatureEnabled()); + } + + if (additionalProperties.containsKey(Constants.HSTS)) { + setHstsFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.HSTS)); + } else { + additionalProperties.put(Constants.HSTS, getHstsFeatureEnabled()); + } + + if (additionalProperties.containsKey(Constants.CORS)) { + setCorsFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.CORS)); + } else { + additionalProperties.put(Constants.CORS, getCorsFeatureEnabled()); + } + + if (additionalProperties.containsKey(Constants.COMPRESSION)) { + setCompressionFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.COMPRESSION)); + } else { + additionalProperties.put(Constants.COMPRESSION, getCompressionFeatureEnabled()); + } + + boolean generateApis = additionalProperties.containsKey(CodegenConstants.GENERATE_APIS) && (Boolean) additionalProperties.get(CodegenConstants.GENERATE_APIS); + String packageFolder = (sourceFolder + File.separator + packageName).replace(".", File.separator); + String resourcesFolder = "src/main/resources"; // not sure this can be user configurable. + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("Dockerfile.mustache", "", "Dockerfile")); + + supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); + supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); + supportingFiles.add(new SupportingFile("gradle.properties", "", "gradle.properties")); + + supportingFiles.add(new SupportingFile("AppMain.kt.mustache", packageFolder, "AppMain.kt")); + supportingFiles.add(new SupportingFile("Configuration.kt.mustache", packageFolder, "Configuration.kt")); + + if (generateApis) { + supportingFiles.add(new SupportingFile("Paths.kt.mustache", packageFolder, "Paths.kt")); + } + + supportingFiles.add(new SupportingFile("application.conf.mustache", resourcesFolder, "application.conf")); + supportingFiles.add(new SupportingFile("logback.xml", resourcesFolder, "logback.xml")); + + final String infrastructureFolder = (sourceFolder + File.separator + packageName + File.separator + "infrastructure").replace(".", File.separator); + + supportingFiles.add(new SupportingFile("ApiKeyAuth.kt.mustache", infrastructureFolder, "ApiKeyAuth.kt")); + } + + public static class Constants { + public final static String KTOR = "ktor"; + public final static String AUTOMATIC_HEAD_REQUESTS = "featureAutoHead"; + public final static String AUTOMATIC_HEAD_REQUESTS_DESC = "Automatically provide responses to HEAD requests for existing routes that have the GET verb defined."; + public final static String CONDITIONAL_HEADERS = "featureConditionalHeaders"; + public final static String CONDITIONAL_HEADERS_DESC = "Avoid sending content if client already has same content, by checking ETag or LastModified properties."; + public final static String HSTS = "featureHSTS"; + public final static String HSTS_DESC = "Avoid sending content if client already has same content, by checking ETag or LastModified properties."; + public final static String CORS = "featureCORS"; + public final static String CORS_DESC = "Ktor by default provides an interceptor for implementing proper support for Cross-Origin Resource Sharing (CORS). See enable-cors.org."; + public final static String COMPRESSION = "featureCompression"; + public final static String COMPRESSION_DESC = "Adds ability to compress outgoing content using gzip, deflate or custom encoder and thus reduce size of the response."; + } + + @Override + public void postProcess() { + System.out.println("################################################################################"); + System.out.println("# Thanks for using OpenAPI Generator. #"); + System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #"); + System.out.println("# https://opencollective.com/openapi_generator/donate #"); + System.out.println("# #"); + System.out.println("# This generator's contributed by Jim Schubert (https://github.com/jimschubert)#"); + System.out.println("# Please support his work directly via https://patreon.com/jimschubert \uD83D\uDE4F #"); + System.out.println("################################################################################"); + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaClientCodegen.java index 138e9bf9c1d..a5e293c9879 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaClientCodegen.java @@ -166,8 +166,8 @@ public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements Code additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("reference.mustache", resourcesFolder, "reference.conf")); final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); supportingFiles.add(new SupportingFile("apiRequest.mustache", invokerFolder, "ApiRequest.scala")); @@ -175,6 +175,7 @@ public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements Code supportingFiles.add(new SupportingFile("requests.mustache", invokerFolder, "requests.scala")); supportingFiles.add(new SupportingFile("apiSettings.mustache", invokerFolder, "ApiSettings.scala")); final String apiFolder = (sourceFolder + File.separator + apiPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("project/build.properties.mustache", "project", "build.properties")); supportingFiles.add(new SupportingFile("enumsSerializers.mustache", apiFolder, "EnumsSerializers.scala")); supportingFiles.add(new SupportingFile("serializers.mustache", invokerFolder, "Serializers.scala")); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java index 701be93e47d..18ad2632440 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java @@ -37,20 +37,22 @@ import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import static org.openapitools.codegen.utils.StringUtils.camelize; public class ScalaSttpClientCodegen extends AbstractScalaCodegen implements CodegenConfig { private static final StringProperty STTP_CLIENT_VERSION = new StringProperty("sttpClientVersion", "The version of " + - "sttp client", "2.2.0"); + "sttp client", "2.2.9"); private static final BooleanProperty USE_SEPARATE_ERROR_CHANNEL = new BooleanProperty("separateErrorChannel", "Whether to return response as " + "F[Either[ResponseError[ErrorType], ReturnType]]] or to flatten " + "response's error raising them through enclosing monad (F[ReturnType]).", true); private static final StringProperty JODA_TIME_VERSION = new StringProperty("jodaTimeVersion", "The version of " + - "joda-time library", "2.10.6"); + "joda-time library", "2.10.10"); private static final StringProperty JSON4S_VERSION = new StringProperty("json4sVersion", "The version of json4s " + - "library", "3.6.8"); + "library", "3.6.11"); private static final StringProperty CIRCE_VERSION = new StringProperty("circeVersion", "The version of circe " + "library", "0.13.0"); private static final JsonLibraryProperty JSON_LIBRARY_PROPERTY = new JsonLibraryProperty(); @@ -179,8 +181,17 @@ public class ScalaSttpClientCodegen extends AbstractScalaCodegen implements Code @Override public String encodePath(String input) { - String result = super.encodePath(input); - return result.replace("{", "${"); + String path = super.encodePath(input); + + // The parameter names in the URI must be converted to the same case as + // the method parameter. + StringBuffer buf = new StringBuffer(path.length()); + Matcher matcher = Pattern.compile("[{](.*?)[}]").matcher(path); + while (matcher.find()) { + matcher.appendReplacement(buf, "\\${" + toParamName(matcher.group(0)) + "}"); + } + matcher.appendTail(buf); + return buf.toString(); } @Override diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache index a14047e7998..8979b10a7f8 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache @@ -10,8 +10,8 @@ lazy val root = (project in file(".")). resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.24", - "com.squareup.okhttp3" % "okhttp" % "3.14.7", - "com.squareup.okhttp3" % "logging-interceptor" % "3.14.7", + "com.squareup.okhttp3" % "okhttp" % "4.9.1", + "com.squareup.okhttp3" % "logging-interceptor" % "4.9.1", "com.google.code.gson" % "gson" % "2.8.6", "org.apache.commons" % "commons-lang3" % "3.10", {{#hasOAuthMethods}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache index 0fe89ccb026..6491013f5a8 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache @@ -59,6 +59,9 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TimeZone; + +import javax.annotation.Nullable; + {{#jsr310}} {{#threetenbp}} import org.threeten.bp.OffsetDateTime; @@ -98,12 +101,47 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { private final WebClient webClient; private final DateFormat dateFormat; + private final ObjectMapper objectMapper; private Map authentications; public ApiClient() { this.dateFormat = createDefaultDateFormat(); + this.objectMapper = createDefaultObjectMapper(this.dateFormat); + this.webClient = buildWebClient(this.objectMapper); + this.init(); + } + + public ApiClient(WebClient webClient) { + this(Optional.ofNullable(webClient).orElseGet(() -> buildWebClient()), createDefaultDateFormat()); + } + + public ApiClient(ObjectMapper mapper, DateFormat format) { + this(buildWebClient(mapper.copy()), format); + } + + public ApiClient(WebClient webClient, ObjectMapper mapper, DateFormat format) { + this(Optional.ofNullable(webClient).orElseGet(() -> buildWebClient(mapper.copy())), format); + } + + private ApiClient(WebClient webClient, DateFormat format) { + this.webClient = webClient; + this.dateFormat = format; + this.objectMapper = createDefaultObjectMapper(format); + this.init(); + } + + public static DateFormat createDefaultDateFormat() { + DateFormat dateFormat = new RFC3339DateFormat(); + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + return dateFormat; + } + + public static ObjectMapper createDefaultObjectMapper(@Nullable DateFormat dateFormat) { + if (null == dateFormat) { + dateFormat = createDefaultDateFormat(); + } ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(dateFormat); mapper.registerModule(new JavaTimeModule()); @@ -112,29 +150,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { JsonNullableModule jnm = new JsonNullableModule(); mapper.registerModule(jnm); {{/openApiNullable}} - - this.webClient = buildWebClient(mapper); - this.init(); - } - - public ApiClient(ObjectMapper mapper, DateFormat format) { - this(buildWebClient(mapper.copy()), format); - } - - public ApiClient(WebClient webClient, ObjectMapper mapper, DateFormat format) { - this(Optional.ofNullable(webClient).orElseGet(() ->buildWebClient(mapper.copy())), format); - } - - private ApiClient(WebClient webClient, DateFormat format) { - this.webClient = webClient; - this.dateFormat = format; - this.init(); - } - - public DateFormat createDefaultDateFormat() { - DateFormat dateFormat = new RFC3339DateFormat(); - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - return dateFormat; + return mapper; } protected void init() { @@ -149,20 +165,45 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { } /** - * Build the WebClient used to make HTTP requests. + * Build the WebClientBuilder used to make WebClient. + * @param mapper ObjectMapper used for serialize/deserialize * @return WebClient */ - public static WebClient buildWebClient(ObjectMapper mapper) { + public static WebClient.Builder buildWebClientBuilder(ObjectMapper mapper) { ExchangeStrategies strategies = ExchangeStrategies .builder() .codecs(clientDefaultCodecsConfigurer -> { clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(mapper, MediaType.APPLICATION_JSON)); clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(mapper, MediaType.APPLICATION_JSON)); }).build(); - WebClient.Builder webClient = WebClient.builder().exchangeStrategies(strategies); - return webClient.build(); + WebClient.Builder webClientBuilder = WebClient.builder().exchangeStrategies(strategies); + return webClientBuilder; } + /** + * Build the WebClientBuilder used to make WebClient. + * @return WebClient + */ + public static WebClient.Builder buildWebClientBuilder() { + return buildWebClientBuilder(createDefaultObjectMapper(null)); + } + + /** + * Build the WebClient used to make HTTP requests. + * @param mapper ObjectMapper used for serialize/deserialize + * @return WebClient + */ + public static WebClient buildWebClient(ObjectMapper mapper) { + return buildWebClientBuilder(mapper).build(); + } + + /** + * Build the WebClient used to make HTTP requests. + * @return WebClient + */ + public static WebClient buildWebClient() { + return buildWebClientBuilder(createDefaultObjectMapper(null)).build(); + } /** * Get the current base path @@ -352,6 +393,22 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { return dateFormat.format(date); } + /** + * Get the ObjectMapper used to make HTTP requests. + * @return ObjectMapper objectMapper + */ + public ObjectMapper getObjectMapper() { + return objectMapper; + } + + /** + * Get the WebClient used to make HTTP requests. + * @return WebClient webClient + */ + public WebClient getWebClient() { + return webClient; + } + /** * Format the given parameter object into string. * @param param the object to convert @@ -655,10 +712,10 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { } // collectionFormat is assumed to be "csv" by default - if(collectionFormat == null) { - collectionFormat = CollectionFormat.CSV; - } + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } - return collectionFormat.collectionToString(values); + return collectionFormat.collectionToString(values); } } diff --git a/modules/openapi-generator/src/main/resources/Javascript-Flowtyped/api.mustache b/modules/openapi-generator/src/main/resources/Javascript-Flowtyped/api.mustache index 35bff5b9687..ccfed6298ec 100644 --- a/modules/openapi-generator/src/main/resources/Javascript-Flowtyped/api.mustache +++ b/modules/openapi-generator/src/main/resources/Javascript-Flowtyped/api.mustache @@ -36,7 +36,6 @@ export type FetchArgs = { options: {}; } - /** * * @export @@ -79,12 +78,12 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur {{/summary}} * @throws {RequiredError} */ - {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options: RequestOptions): FetchArgs { + {{operationId}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options: RequestOptions): FetchArgs { {{#allParams}} {{#required}} // verify required parameter '{{paramName}}' is not null or undefined if ({{paramName}} === null || {{paramName}} === undefined) { - throw new RequiredError('{{paramName}}','Required parameter {{paramName}} was null or undefined when calling {{nickname}}.'); + throw new RequiredError('{{paramName}}','Required parameter {{paramName}} was null or undefined when calling {{operationId}}.'); } {{/required}} {{/allParams}} @@ -104,16 +103,16 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur {{#isKeyInHeader}} if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("{{keyParamName}}") - : configuration.apiKey; + ? configuration.apiKey("{{keyParamName}}") + : configuration.apiKey; localVarHeaderParameter["{{keyParamName}}"] = localVarApiKeyValue; } {{/isKeyInHeader}} {{#isKeyInQuery}} if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("{{keyParamName}}") - : configuration.apiKey; + ? configuration.apiKey("{{keyParamName}}") + : configuration.apiKey; localVarQueryParameter["{{keyParamName}}"] = localVarApiKeyValue; } {{/isKeyInQuery}} @@ -127,9 +126,9 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur {{#isOAuth}} // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("{{name}}", [{{#scopes}}"{{{scope}}}"{{^-last}}, {{/-last}}{{/scopes}}]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("{{name}}", [{{#scopes}}"{{{scope}}}"{{^-last}}, {{/-last}}{{/scopes}}]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } {{/isOAuth}} @@ -142,7 +141,7 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur localVarQueryParameter['{{baseName}}'] = {{paramName}}; {{/isCollectionFormatMulti}} {{^isCollectionFormatMulti}} - localVarQueryParameter['{{baseName}}'] = {{paramName}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]); + localVarQueryParameter['{{baseName}}'] = {{#uniqueItems}}Array.from({{/uniqueItems}}{{paramName}}{{#uniqueItems}}){{/uniqueItems}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]); {{/isCollectionFormatMulti}} } {{/isArray}} @@ -166,7 +165,7 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur {{#headerParams}} {{#isArray}} if ({{paramName}}) { - localVarHeaderParameter['{{baseName}}'] = {{paramName}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]); + localVarHeaderParameter['{{baseName}}'] = {{#uniqueItems}}Array.from({{/uniqueItems}}{{paramName}}{{#uniqueItems}}){{/uniqueItems}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]); } {{/isArray}} {{^isArray}} @@ -185,7 +184,7 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur }) {{/isCollectionFormatMulti}} {{^isCollectionFormatMulti}} - localVarFormParams.set('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS["{{collectionFormat}}"])); + localVarFormParams.set('{{baseName}}', {{#uniqueItems}}Array.from({{/uniqueItems}}{{paramName}}{{#uniqueItems}}){{/uniqueItems}}.join(COLLECTION_FORMATS["{{collectionFormat}}"])); {{/isCollectionFormatMulti}} } {{/isArray}} @@ -227,7 +226,7 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur }; export type {{classname}}Type = { {{#operation}} - {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: RequestOptions): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Response{{/returnType}}>, + {{operationId}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: RequestOptions): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Response{{/returnType}}>, {{/operation}} } @@ -247,8 +246,8 @@ export const {{classname}} = function(configuration?: Configuration, fetch: Fetc {{/summary}} * @throws {RequiredError} */ - {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: RequestOptions = {}): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Response{{/returnType}}> { - const localVarFetchArgs = {{classname}}FetchParamCreator(configuration).{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options); + {{operationId}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: RequestOptions = {}): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Response{{/returnType}}> { + const localVarFetchArgs = {{classname}}FetchParamCreator(configuration).{{operationId}}({{#allParams}}{{paramName}}, {{/allParams}}options); return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response{{#returnType}}.json(){{/returnType}}; @@ -260,6 +259,7 @@ export const {{classname}} = function(configuration?: Configuration, fetch: Fetc {{/operation}} } }; + {{/operations}}{{/apis}}{{/apiInfo}} export type ApiTypes = { {{#apiInfo}}{{#apis}}{{#operations}} {{classname}}: {{classname}}Type, diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index 87ab2b5e352..4226cade162 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -44,6 +44,7 @@ org.openapitools.codegen.languages.GraphQLNodeJSExpressServerCodegen org.openapitools.codegen.languages.GroovyClientCodegen org.openapitools.codegen.languages.KotlinClientCodegen org.openapitools.codegen.languages.KotlinServerCodegen +org.openapitools.codegen.languages.KotlinServerDeprecatedCodegen org.openapitools.codegen.languages.KotlinSpringServerCodegen org.openapitools.codegen.languages.KotlinVertxServerCodegen org.openapitools.codegen.languages.KtormSchemaCodegen diff --git a/modules/openapi-generator/src/main/resources/bash/client.mustache b/modules/openapi-generator/src/main/resources/bash/client.mustache index ff63a39c600..3f5dcc0e291 100644 --- a/modules/openapi-generator/src/main/resources/bash/client.mustache +++ b/modules/openapi-generator/src/main/resources/bash/client.mustache @@ -979,7 +979,7 @@ case $key in body_parameters[${body_key}]=${body_value} fi ;; - +\([^=]\):*) + +([^=]):*) # Parse header arguments and convert them into curl # only after the operation argument if [[ "$operation" ]]; then diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-header.mustache index 7beb0990a96..f614d478e96 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-header.mustache @@ -14,24 +14,21 @@ #include #include {{^hasModelImport}}#include {{/hasModelImport}} +#include {{#imports}}{{{import}}} {{/imports}} -{{#apiNamespaceDeclarations}} -namespace {{this}} { -{{/apiNamespaceDeclarations}} - -{{#hasModelImport}} -using namespace {{modelNamespace}};{{/hasModelImport}} +namespace {{apiNamespace}} +{ class {{declspec}} {{classname}} { public: - {{classname}}(std::shared_ptr); - virtual ~{{classname}}() {} + explicit {{classname}}(const std::shared_ptr& rtr); + virtual ~{{classname}}() = default; void init(); - const std::string base = "{{basePathWithoutHost}}"; + static const std::string base; private: void setupRoutes(); @@ -41,9 +38,21 @@ private: {{/operation}} void {{classnameSnakeLowerCase}}_default_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); - std::shared_ptr router; - {{#operation}} + const std::shared_ptr router; + /// + /// Helper function to handle unexpected Exceptions during Parameter parsing and validation. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleParsingException(const std::exception& ex) const noexcept; + + /// + /// Helper function to handle unexpected Exceptions during processing of the request in handler functions. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleOperationException(const std::exception& ex) const noexcept; + + {{#operation}} /// /// {{summary}} /// @@ -54,7 +63,7 @@ private: {{#allParams}} /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} {{/allParams}} - virtual void {{operationIdSnakeCase}}({{#allParams}}const {{{dataType}}} &{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}Pistache::Http::ResponseWriter &response) = 0; + virtual void {{operationIdSnakeCase}}({{#allParams}}const {{#isModel}}{{modelNamespace}}::{{/isModel}}{{{dataType}}} &{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}Pistache::Http::ResponseWriter &response) = 0; {{/vendorExtensions.x-codegen-pistache-is-parsing-supported}} {{^vendorExtensions.x-codegen-pistache-is-parsing-supported}} virtual void {{operationIdSnakeCase}}(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter &response) = 0; @@ -63,9 +72,7 @@ private: }; -{{#apiNamespaceDeclarations}} -} -{{/apiNamespaceDeclarations}} +} // namespace {{apiNamespace}} #endif /* {{classname}}_H_ */ diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-header.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-header.mustache index 18ff119ae20..bd20c1bdf5a 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-header.mustache @@ -22,17 +22,16 @@ {{#imports}}{{{import}}} {{/imports}} -{{#apiNamespaceDeclarations}} -namespace {{this}} { -{{/apiNamespaceDeclarations}} +namespace {{apiNamespace}} +{ {{#hasModelImport}} using namespace {{modelNamespace}};{{/hasModelImport}} class {{classname}}Impl : public {{apiNamespace}}::{{classname}} { public: - {{classname}}Impl(std::shared_ptr); - ~{{classname}}Impl() {} + explicit {{classname}}Impl(const std::shared_ptr& rtr); + ~{{classname}}Impl() override = default; {{#operation}} {{#vendorExtensions.x-codegen-pistache-is-parsing-supported}} @@ -45,11 +44,9 @@ public: }; -{{#apiNamespaceDeclarations}} -} -{{/apiNamespaceDeclarations}} +} // namespace {{apiNamespace}} {{/operations}} -#endif \ No newline at end of file +#endif diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-source.mustache index e5517bb487c..2e25a8034b3 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-source.mustache @@ -10,9 +10,10 @@ namespace {{this}} { {{#hasModelImport}} using namespace {{modelNamespace}};{{/hasModelImport}} -{{classname}}Impl::{{classname}}Impl(std::shared_ptr rtr) +{{classname}}Impl::{{classname}}Impl(const std::shared_ptr& rtr) : {{classname}}(rtr) - { } +{ +} {{#operation}} {{#vendorExtensions.x-codegen-pistache-is-parsing-supported}} @@ -31,4 +32,4 @@ void {{classname}}Impl::{{operationIdSnakeCase}}(const Pistache::Rest::Request & } {{/apiNamespaceDeclarations}} -{{/operations}} \ No newline at end of file +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache index 9225a5610c7..9814ba0cd62 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache @@ -4,16 +4,18 @@ #include "{{classname}}.h" #include "{{prefix}}Helpers.h" -{{#apiNamespaceDeclarations}} -namespace {{this}} { -{{/apiNamespaceDeclarations}} +namespace {{apiNamespace}} +{ using namespace {{helpersNamespace}}; {{#hasModelImport}} using namespace {{modelNamespace}};{{/hasModelImport}} -{{classname}}::{{classname}}(std::shared_ptr rtr) { - router = rtr; +const std::string {{classname}}::base = "{{basePathWithoutHost}}"; + +{{classname}}::{{classname}}(const std::shared_ptr& rtr) + : router(rtr) +{ } void {{classname}}::init() { @@ -31,8 +33,26 @@ void {{classname}}::setupRoutes() { router->addCustomHandler(Routes::bind(&{{classname}}::{{classnameSnakeLowerCase}}_default_handler, this)); } +std::pair {{classname}}::handleParsingException(const std::exception& ex) const noexcept +{ + try { + throw ex; + } catch (nlohmann::detail::exception &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch ({{helpersNamespace}}::ValidationException &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } +} + +std::pair {{classname}}::handleOperationException(const std::exception& ex) const noexcept +{ + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, ex.what()); +} + {{#operation}} void {{classname}}::{{operationIdSnakeCase}}_handler(const Pistache::Rest::Request &{{#hasParams}}request{{/hasParams}}, Pistache::Http::ResponseWriter response) { + try { + {{#vendorExtensions.x-codegen-pistache-is-parsing-supported}} {{#hasPathParams}} // Getting the path params @@ -71,32 +91,40 @@ void {{classname}}::{{operationIdSnakeCase}}_handler(const Pistache::Rest::Reque {{#hasBodyParam}} {{#bodyParam}} {{^isPrimitiveType}} - nlohmann::json::parse(request.body()).get_to({{paramName}}); + nlohmann::json::parse(request.body()).get_to({{paramName}}); + {{paramName}}.validate(); {{/isPrimitiveType}} {{#isPrimitiveType}} - {{paramName}} = request.body(); + {{paramName}} = request.body(); {{/isPrimitiveType}} + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); + return; + } + + try { {{/bodyParam}} {{/hasBodyParam}} - this->{{operationIdSnakeCase}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}response); + this->{{operationIdSnakeCase}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}response); {{/vendorExtensions.x-codegen-pistache-is-parsing-supported}} {{^vendorExtensions.x-codegen-pistache-is-parsing-supported}} try { this->{{operationIdSnakeCase}}(request, response); {{/vendorExtensions.x-codegen-pistache-is-parsing-supported}} - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } {{/operation}} @@ -104,8 +132,6 @@ void {{classname}}::{{classnameSnakeLowerCase}}_default_handler(const Pistache:: response.send(Pistache::Http::Code::Not_Found, "The requested method does not exist"); } -{{#apiNamespaceDeclarations}} -} -{{/apiNamespaceDeclarations}} +} // namespace {{apiNamespace}} {{/operations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-header.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-header.mustache index c39cca04fe1..d3489fad402 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-header.mustache @@ -14,16 +14,80 @@ #include #include -{{#helpersNamespaceDeclarations}} -namespace {{this}} { -{{/helpersNamespaceDeclarations}} +namespace {{helpersNamespace}} +{ + + class ValidationException : public std::runtime_error + { + public: + explicit ValidationException(const std::string& what) + : std::runtime_error(what) + { } + ~ValidationException() override = default; + }; + + /// + /// Validate a string against the full-date definition of RFC 3339, section 5.6. + /// + bool validateRfc3339_date(const std::string& str); + + /// + /// Validate a string against the date-time definition of RFC 3339, section 5.6. + /// + bool validateRfc3339_date_time(const std::string& str); + + namespace sfinae_helpers + { + struct NoType {}; + template NoType operator==(const T1&, const T2&); + + template class EqualsOperatorAvailable + { + public: + enum + { + value = !std::is_same< decltype(std::declval() == std::declval()), NoType >::value + }; + }; + } // namespace sfinae_helpers + + + /// + /// Determine if the given vector only has unique elements. T must provide the == operator. + /// + template + bool hasOnlyUniqueItems(const std::vector& vec) + { + static_assert(sfinae_helpers::EqualsOperatorAvailable::value, + "hasOnlyUniqueItems cannot be called, passed template type does not provide == operator."); + if (vec.size() <= 1) + { + return true; + } + // Compare every element of vec to every other element of vec. + // This isn't an elegant way to do this, since it's O(n^2), + // but it's the best solution working only with the == operator. + // This could be greatly improved if our models provided a valid hash + // and/or the < operator + for (size_t i = 0; i < vec.size() - 1; i++) + { + for (size_t j = i + 1; j < vec.size(); j++) + { + if (vec[i] == vec[j]) + { + return false; + } + } + } + return true; + } std::string toStringValue(const std::string &value); - std::string toStringValue(const int32_t &value); - std::string toStringValue(const int64_t &value); - std::string toStringValue(const bool &value); - std::string toStringValue(const float &value); - std::string toStringValue(const double &value); + std::string toStringValue(const int32_t value); + std::string toStringValue(const int64_t value); + std::string toStringValue(const bool value); + std::string toStringValue(const float value); + std::string toStringValue(const double value); bool fromStringValue(const std::string &inStr, std::string &value); bool fromStringValue(const std::string &inStr, int32_t &value); @@ -57,8 +121,6 @@ namespace {{this}} { return fromStringValue(inStrings, value); } -{{#helpersNamespaceDeclarations}} -} -{{/helpersNamespaceDeclarations}} +} // namespace {{helpersNamespace}} -#endif // {{prefix}}Helpers_H_ \ No newline at end of file +#endif // {{prefix}}Helpers_H_ diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-source.mustache index 82b4e2d81ef..214086354d5 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-source.mustache @@ -1,32 +1,74 @@ {{>licenseInfo}} #include "{{prefix}}Helpers.h" +#include -{{#helpersNamespaceDeclarations}} -namespace {{this}} { -{{/helpersNamespaceDeclarations}} +namespace {{helpersNamespace}} +{ +const std::regex regexRfc3339_date(R"(^(\d{4})\-(\d{2})\-(\d{2})$)"); +const std::regex regexRfc3339_date_time( + R"(^(\d{4})\-(\d{2})\-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|([\+\-])(\d{2}):(\d{2}))$)" +); + + +namespace +{ + // Determine if given year is a leap year + // See RFC 3339, Appendix C https://tools.ietf.org/html/rfc3339#appendix-C + bool isLeapYear(const uint16_t year) { + return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)); + } + + bool validateDateValues(const uint16_t year, const uint16_t month, const uint16_t day) { + return !( + (month == 0 || month > 12) + || (day == 0) + || (month == 2 && day > (28 + (isLeapYear(year) ? 1 : 0))) + || (month <= 7 && day > (30 + month % 2)) + || (month >= 8 && day > (31 - month % 2)) + ); + } + + bool validateTimeValues(const uint16_t hours, const uint16_t minutes, const uint16_t seconds) { + return (hours <= 23) && (minutes <= 59) && (seconds <= 60); + } +} + +bool validateRfc3339_date(const std::string& str) { + std::smatch match; + const bool found = std::regex_search(str, match, regexRfc3339_date); + return found && validateDateValues(std::stoi(match[1]), std::stoi(match[2]), std::stoi(match[3])); +} + +bool validateRfc3339_date_time(const std::string& str) { + std::smatch match; + const bool found = std::regex_search(str, match, regexRfc3339_date_time); + return found + && validateDateValues(std::stoi(match[1]), std::stoi(match[2]), std::stoi(match[3])) + && validateTimeValues(std::stoi(match[4]), std::stoi(match[5]), std::stoi(match[6])); +} std::string toStringValue(const std::string &value){ return std::string(value); } -std::string toStringValue(const int32_t &value){ +std::string toStringValue(const int32_t value){ return std::to_string(value); } -std::string toStringValue(const int64_t &value){ +std::string toStringValue(const int64_t value){ return std::to_string(value); } -std::string toStringValue(const bool &value){ - return value?std::string("true"):std::string("false"); +std::string toStringValue(const bool value){ + return value ? std::string("true") : std::string("false"); } -std::string toStringValue(const float &value){ +std::string toStringValue(const float value){ return std::to_string(value); } -std::string toStringValue(const double &value){ +std::string toStringValue(const double value){ return std::to_string(value); } @@ -56,9 +98,15 @@ bool fromStringValue(const std::string &inStr, int64_t &value){ } bool fromStringValue(const std::string &inStr, bool &value){ - bool result = true; - inStr == "true"?value = true: inStr == "false"?value = false: result = false; - return result; + if (inStr == "true") { + value = true; + return true; + } + if (inStr == "false") { + value = false; + return true; + } + return false; } bool fromStringValue(const std::string &inStr, float &value){ @@ -81,6 +129,4 @@ bool fromStringValue(const std::string &inStr, double &value){ return true; } -{{#helpersNamespaceDeclarations}} -} -{{/helpersNamespaceDeclarations}} \ No newline at end of file +} // namespace {{helpersNamespace}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-header.mustache index c16fdbb0946..cb6d8d98ee0 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-header.mustache @@ -13,9 +13,8 @@ {{/imports}} #include -{{#modelNamespaceDeclarations}} -namespace {{this}} { -{{/modelNamespaceDeclarations}} +namespace {{modelNamespace}} +{ /// /// {{description}} @@ -24,7 +23,7 @@ class {{declspec}} {{classname}} { public: {{classname}}(); - virtual ~{{classname}}(); + virtual ~{{classname}}() = default; {{#isEnum}}{{#allowableValues}} enum class e{{classname}} { // To have a valid default value. @@ -35,7 +34,20 @@ public: {{{name}}}{{^-last}}, {{/-last}} {{/enumVars}} };{{/allowableValues}}{{/isEnum}} - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const {{classname}}& rhs) const; + bool operator!=(const {{classname}}& rhs) const; ///////////////////////////////////////////// /// {{classname}} members @@ -44,7 +56,7 @@ public: /// /// {{description}} /// - {{{dataType}}}{{#isContainer}}&{{/isContainer}} {{getter}}(){{^isContainer}} const{{/isContainer}}; + {{{dataType}}} {{getter}}() const; void {{setter}}({{{dataType}}} const{{^isPrimitiveType}}&{{/isPrimitiveType}} value);{{^required}} bool {{nameInCamelCase}}IsSet() const; void unset{{name}}();{{/required}} @@ -65,11 +77,12 @@ protected: {{#isEnum}} {{classname}}::e{{classname}} m_value = {{classname}}::e{{classname}}::INVALID_VALUE_OPENAPI_GENERATED; {{/isEnum}} + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -{{#modelNamespaceDeclarations}} -} -{{/modelNamespaceDeclarations}} +} // namespace {{modelNamespace}} #endif /* {{classname}}_H_ */ {{/model}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-source.mustache index d603dc2186e..8ef6abf0e4c 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-source.mustache @@ -2,12 +2,12 @@ {{#models}}{{#model}} #include "{{classname}}.h" -{{#isEnum}}#include -#include {{/isEnum}} +#include "{{prefix}}Helpers.h" +{{#isEnum}}#include {{/isEnum}} +#include -{{#modelNamespaceDeclarations}} -namespace {{this}} { -{{/modelNamespaceDeclarations}} +namespace {{modelNamespace}} +{ {{classname}}::{{classname}}() { @@ -18,13 +18,69 @@ namespace {{this}} { {{/required}}{{/vars}} } -{{classname}}::~{{classname}}() +void {{classname}}::validate() const { + std::stringstream msg; + if (!validate(msg)) + { + throw {{helpersNamespace}}::ValidationException(msg.str()); + } } -void {{classname}}::validate() +bool {{classname}}::validate(std::stringstream& msg) const { - // TODO: implement validation + return validate(msg, ""); +} + +bool {{classname}}::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "{{classname}}" : pathPrefix; + + {{#isEnum}}{{! Special case for enum types }} + if (m_value == {{classname}}::e{{classname}}::INVALID_VALUE_OPENAPI_GENERATED) + { + success = false; + msg << _pathPrefix << ": has no value;"; + } + {{/isEnum}} + {{^isEnum}} + {{#vars}} + {{#isArray}} {{! Always generate validation body for array types }} + {{^required}}if ({{nameInCamelCase}}IsSet()){{/required}} + {{#required}}/* {{name}} */ {{/required}}{ + const {{{dataType}}}& value = m_{{name}}; + const std::string currentValuePath = _pathPrefix + ".{{nameInCamelCase}}"; + {{> model-validation-body }} + } + {{/isArray}}{{^isArray}}{{#hasValidation}} {{! Only generate validation if necessary }} + {{^required}}if ({{nameInCamelCase}}IsSet()){{/required}} + {{#required}}/* {{name}} */ {{/required}}{ + const {{{dataType}}}& value = m_{{name}}; + const std::string currentValuePath = _pathPrefix + ".{{nameInCamelCase}}"; + {{> model-validation-body }} + } + {{/hasValidation}}{{/isArray}} + {{/vars}} + {{/isEnum}} + + return success; +} + +bool {{classname}}::operator==(const {{classname}}& rhs) const +{ + return + {{#isEnum}}getValue() == rhs.getValue(){{/isEnum}} + {{^isEnum}}{{#vars}} + {{#required}}({{getter}}() == rhs.{{getter}}()){{/required}} + {{^required}}((!{{nameInCamelCase}}IsSet() && !rhs.{{nameInCamelCase}}IsSet()) || ({{nameInCamelCase}}IsSet() && rhs.{{nameInCamelCase}}IsSet() && {{getter}}() == rhs.{{getter}}())){{/required}}{{^-last}} &&{{/-last}} + {{/vars}}{{/isEnum}} + ; +} + +bool {{classname}}::operator!=(const {{classname}}& rhs) const +{ + return !(*this == rhs); } void to_json(nlohmann::json& j, const {{classname}}& o) @@ -74,7 +130,7 @@ void from_json(const nlohmann::json& j, {{classname}}& o) {{/enumVars}}{{/allowableValues}}{{/isEnum}} } -{{#vars}}{{{dataType}}}{{#isContainer}}&{{/isContainer}} {{classname}}::{{getter}}(){{^isContainer}} const{{/isContainer}} +{{#vars}}{{{dataType}}} {{classname}}::{{getter}}() const { return m_{{name}}; } @@ -102,9 +158,7 @@ void {{classname}}::setValue({{classname}}::e{{classname}} value) m_value = value; }{{/isEnum}} -{{#modelNamespaceDeclarations}} -} -{{/modelNamespaceDeclarations}} +} // namespace {{modelNamespace}} {{/model}} {{/models}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-header.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-header.mustache index bcc64257e40..be0ea874da8 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-header.mustache @@ -14,9 +14,8 @@ #include {{#hasOptional}}#include {{/hasOptional}} -{{#modelNamespaceDeclarations}} -namespace {{this}} { -{{/modelNamespaceDeclarations}} +namespace {{modelNamespace}} +{ struct {{classname}} { @@ -34,9 +33,9 @@ struct {{classname}} void to_json(nlohmann::json& j, const {{classname}}& o); void from_json(const nlohmann::json& j, {{classname}}& o); -{{#modelNamespaceDeclarations}} -} // {{this}} -{{/modelNamespaceDeclarations}} + +} // namespace {{modelNamespace}} + #endif /* {{classname}}_H_ */ {{/model}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-source.mustache index 52d3526e867..987926b7c4e 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-source.mustache @@ -3,9 +3,8 @@ #include "{{classname}}.h" -{{#modelNamespaceDeclarations}} -namespace {{this}} { -{{/modelNamespaceDeclarations}} +namespace {{modelNamespace}} +{ nlohmann::json {{classname}}::to_json() const { @@ -51,9 +50,7 @@ void from_json(const nlohmann::json& j, {{classname}}& o) {{/vars}} } -{{#modelNamespaceDeclarations}} -} // {{this}} -{{/modelNamespaceDeclarations}} +} // namespace {{modelNamespace}} {{/model}} {{/models}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-validation-body.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-validation-body.mustache new file mode 100644 index 00000000000..ef92f2c3fbd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-validation-body.mustache @@ -0,0 +1,124 @@ +{{! +This template generates the validation logic for a model. +This template file calls itself recursively for arrays. +}} +{{! Check for eunm properties that are their own schema }} +{{! These are in their own class with a validate function, the way to check for this is quite a hack +since isEnum, isString and isModel are all false. }} + {{^isString}}{{#allowableValues.enumVars.0.value}} + success = value.validate(msg, currentValuePath) && success; + {{/allowableValues.enumVars.0.value}}{{/isString}} + {{#isModel}}success = value.validate(msg, currentValuePath + ".{{nameInCamelCase}}") && success;{{/isModel}} +{{! Date validation }} + {{#isDate}} + if (!{{helpersNamespace}}::validateRfc3339_date(value)) + { + success = false; + msg << currentValuePath << ": must be a valid RFC 3339 date-full string;"; + } + {{/isDate}} +{{! Date-Time validation }} + {{#isDateTime}} + if (!{{helpersNamespace}}::validateRfc3339_date_time(value)) + { + success = false; + msg << currentValuePath << ": must be a valid RFC 3339 date-time string;"; + } + {{/isDateTime}} +{{! string validation }} + {{#isString}} + {{#minLength}} + if (value.length() < {{minLength}}) + { + success = false; + msg << currentValuePath << ": must be at least {{minLength}} characters long;"; + } + {{/minLength}} + {{#maxLength}} + if (value.length() > {{maxLength}}) + { + success = false; + msg << currentValuePath << ": must be at most {{maxLength}} characters long;"; + } + {{/maxLength}} +{{! +TODO validate regex of string using pattern variable. This has two challenges + - Is compatibility with the given regex pattern guaranteed? + - Creating the std::regex on every validation would be rather slow. Ideally one would + initialize them for the class once as a static const and use them. +}} +{{! string encoded enum validation }} + {{#isEnum}} + {{#allowableValues}} + if ({{#enumVars}} + value != "{{value}}"{{^-last}} &&{{/-last}}{{/enumVars}} + ) { + success = false; + msg << currentValuePath << ": has invalid value \"" << value << "\";"; + } + {{/allowableValues}} + {{/isEnum}} + {{/isString}} +{{! numeric validation }} + {{#isNumeric}} + {{#minimum}} + if (value <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{#isFloat}}static_cast({{/isFloat}}{{minimum}}{{#isFloat}}){{/isFloat}}{{#isLong}}ll{{/isLong}}) + { + success = false; + msg << currentValuePath << ": must be greater than{{^exclusiveMinimum}} or equal to{{/exclusiveMinimum}} {{minimum}};"; + } + {{/minimum}} + {{#maximum}} + if (value >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{#isFloat}}static_cast({{/isFloat}}{{maximum}}{{#isFloat}}){{/isFloat}}{{#isLong}}ll{{/isLong}}) + { + success = false; + msg << currentValuePath << ": must be less than{{^exclusiveMaximum}} or equal to{{/exclusiveMaximum}} {{maximum}};"; + } + {{/maximum}} + {{#multipleOf}} + {{#isInteger}}if (value % {{multipleOf}}{{#isLong}}ll{{/isLong}} != 0){{/isInteger}} + {{#isFloat}}if (std::fmod(value, static_cast({{multipleOf}})) != 0){{/isFloat}} + {{#isDouble}}if (std::fmod(value, {{multipleOf}}) != 0){{/isDouble}} + { + success = false; + msg << currentValuePath << ": must be a multiple of {{multipleOf}};"; + } + {{/multipleOf}} + {{/isNumeric}} +{{! Array validation }} + {{#isArray}} + {{#minItems}} + if (value.size() < {{minItems}}) + { + success = false; + msg << currentValuePath << ": must have at least {{minItems}} elements;"; + } + {{/minItems}} + {{#maxItems}} + if (value.size() > {{maxItems}}) + { + success = false; + msg << currentValuePath << ": must have at most {{maxItems}} elements;"; + } + {{/maxItems}} + {{#uniqueItems}} + if (!{{helpersNamespace}}::hasOnlyUniqueItems(value)) + { + success = false; + msg << currentValuePath << ": may not contain the same item more than once;"; + } + {{/uniqueItems}} + { // Recursive validation of array elements + const std::string oldValuePath = currentValuePath; + int i = 0; + {{! the element var has the same name as the vector, so that the recursive template works - what a wonderful hack }} + for (const {{{items.dataType}}}& value : value) + { {{! and I do a similar hack with currentValuePath... }} + const std::string currentValuePath = oldValuePath + "[" + std::to_string(i) + "]"; + {{#items}} + {{> model-validation-body }} {{! Recursively apply template to array - this is where things will probbaly go wrong }} + {{/items}} + i++; + } + } + {{/isArray}} diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/api-header.mustache index c6ee2f08eb4..17b42e942ea 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/api-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/api-header.mustache @@ -15,9 +15,19 @@ public: {{classname}}(); ~{{classname}}(); + /* Sets the URL Endpoint. + * Note: several fallback endpoints can be configured in request retry policies, see Request::SetShouldRetry */ void SetURL(const FString& Url); + + /* Adds global header params to all requests */ void AddHeaderParam(const FString& Key, const FString& Value); void ClearHeaderParams(); + + /* Sets the retry manager to the user-defined retry manager. User must manage the lifetime of the retry manager. + * If no retry manager is specified and a request needs retries, a default retry manager will be used. + * See also: Request::SetShouldRetry */ + void SetHttpRetryManager(FHttpRetrySystem::FManager& RetryManager); + FHttpRetrySystem::FManager& GetHttpRetryManager(); {{#operations}}{{#operation}}class {{operationIdCamelCase}}Request; class {{operationIdCamelCase}}Response; @@ -27,15 +37,17 @@ public: {{#operations}}{{#operation}}{{#description}}/* {{{description}}} */ {{/description}}bool {{operationIdCamelCase}}(const {{operationIdCamelCase}}Request& Request, const F{{operationIdCamelCase}}Delegate& Delegate = F{{operationIdCamelCase}}Delegate()) const; {{/operation}}{{/operations}} - private: - {{#operations}}{{#operation}}void On{{operationIdCamelCase}}Response(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, F{{operationIdCamelCase}}Delegate Delegate, int AutoRetryCount) const; + {{#operations}}{{#operation}}void On{{operationIdCamelCase}}Response(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, F{{operationIdCamelCase}}Delegate Delegate) const; {{/operation}}{{/operations}} + FHttpRequestRef CreateHttpRequest(const Request& Request) const; bool IsValid() const; void HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const; FString Url; TMap AdditionalHeaderParams; + mutable FHttpRetrySystem::FManager* RetryManager = nullptr; + mutable TUniquePtr DefaultRetryManager; }; {{#cppNamespaceDeclarations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/api-source.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/api-source.mustache index 8a9b3854544..9bd9f3b87bd 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/api-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/api-source.mustache @@ -45,6 +45,40 @@ bool {{classname}}::IsValid() const return true; } +void {{classname}}::SetHttpRetryManager(FHttpRetrySystem::FManager& InRetryManager) +{ + if(RetryManager != &GetHttpRetryManager()) + { + DefaultRetryManager.Reset(); + RetryManager = &InRetryManager; + } +} + +FHttpRetrySystem::FManager& {{classname}}::GetHttpRetryManager() +{ + return *RetryManager; +} + +FHttpRequestRef {{classname}}::CreateHttpRequest(const Request& Request) const +{ + if (!Request.GetRetryParams().IsSet()) + { + return FHttpModule::Get().CreateRequest(); + } + else + { + if (!RetryManager) + { + // Create default retry manager if none was specified + DefaultRetryManager = MakeUnique(6, 60); + RetryManager = DefaultRetryManager.Get(); + } + + const HttpRetryParams& Params = Request.GetRetryParams().GetValue(); + return RetryManager->CreateRequest(Params.RetryLimitCountOverride, Params.RetryTimeoutRelativeSecondsOverride, Params.RetryResponseCodes, Params.RetryVerbs, Params.RetryDomains); + } +} + void {{classname}}::HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const { InOutResponse.SetHttpResponse(HttpResponse); @@ -96,7 +130,7 @@ bool {{classname}}::{{operationIdCamelCase}}(const {{operationIdCamelCase}}Reque if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -106,26 +140,15 @@ bool {{classname}}::{{operationIdCamelCase}}(const {{operationIdCamelCase}}Reque Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &{{classname}}::On{{operationIdCamelCase}}Response, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &{{classname}}::On{{operationIdCamelCase}}Response, Delegate); return HttpRequest->ProcessRequest(); } -void {{classname}}::On{{operationIdCamelCase}}Response(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, F{{operationIdCamelCase}}Delegate Delegate, int AutoRetryCount) const +void {{classname}}::On{{operationIdCamelCase}}Response(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, F{{operationIdCamelCase}}Delegate Delegate) const { {{operationIdCamelCase}}Response Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &{{classname}}::On{{operationIdCamelCase}}Response, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-header.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-header.mustache index 31b0bdabd26..2f5b6255f54 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-header.mustache @@ -5,6 +5,8 @@ #include "Interfaces/IHttpResponse.h" #include "Serialization/JsonWriter.h" #include "Dom/JsonObject.h" +#include "HttpRetrySystem.h" +#include "Containers/Ticker.h" {{#cppNamespaceDeclarations}} namespace {{this}} @@ -12,6 +14,31 @@ namespace {{this}} {{/cppNamespaceDeclarations}} typedef TSharedRef> JsonWriter; +using namespace FHttpRetrySystem; + +struct {{dllapi}} HttpRetryManager : public FManager, public FTickerObjectBase +{ + using FManager::FManager; + + bool Tick(float DeltaTime) final; +}; + +struct {{dllapi}} HttpRetryParams +{ + HttpRetryParams( + const FRetryLimitCountSetting& InRetryLimitCountOverride = FRetryLimitCountSetting(), + const FRetryTimeoutRelativeSecondsSetting& InRetryTimeoutRelativeSecondsOverride = FRetryTimeoutRelativeSecondsSetting(), + const FRetryResponseCodes& InRetryResponseCodes = FRetryResponseCodes(), + const FRetryVerbs& InRetryVerbs = FRetryVerbs(), + const FRetryDomainsPtr& InRetryDomains = FRetryDomainsPtr() + ); + + FRetryLimitCountSetting RetryLimitCountOverride; + FRetryTimeoutRelativeSecondsSetting RetryTimeoutRelativeSecondsOverride; + FRetryResponseCodes RetryResponseCodes; + FRetryVerbs RetryVerbs; + FRetryDomainsPtr RetryDomains; +}; class {{dllapi}} Model { @@ -28,11 +55,12 @@ public: virtual void SetupHttpRequest(const FHttpRequestRef& HttpRequest) const = 0; virtual FString ComputePath() const = 0; - void SetAutoRetryCount(int InCount) { AutoRetryCount = InCount; } - int GetAutoRetryCount() const { return AutoRetryCount; } + /* Enables retry and optionally sets a retry policy for this request */ + void SetShouldRetry(const HttpRetryParams& Params = HttpRetryParams()) { RetryParams = Params; } + const TOptional& GetRetryParams() const { return RetryParams; } private: - int AutoRetryCount = 0; + TOptional RetryParams; }; class {{dllapi}} Response @@ -44,8 +72,6 @@ public: void SetSuccessful(bool InSuccessful) { Successful = InSuccessful; } bool IsSuccessful() const { return Successful; } - void AsyncRetry() const; - virtual void SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode); EHttpResponseCodes::Type GetHttpResponseCode() const { return ResponseCode; } @@ -55,15 +81,11 @@ public: void SetHttpResponse(const FHttpResponsePtr& InHttpResponse) { HttpResponse = InHttpResponse; } const FHttpResponsePtr& GetHttpResponse() const { return HttpResponse; } - void SetHttpRequest(const FHttpRequestPtr& InHttpRequest) { HttpRequest = InHttpRequest; } - const FHttpRequestPtr& GetHttpRequest() const { return HttpRequest; } - private: bool Successful; EHttpResponseCodes::Type ResponseCode; FString ResponseString; FHttpResponsePtr HttpResponse; - FHttpRequestPtr HttpRequest; }; {{#cppNamespaceDeclarations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-source.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-source.mustache index a5ab70a432f..57dc4fb4151 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-source.mustache @@ -1,13 +1,30 @@ {{>licenseInfo}} #include "{{modelNamePrefix}}BaseModel.h" -#include "Async/Async.h" - {{#cppNamespaceDeclarations}} namespace {{this}} { {{/cppNamespaceDeclarations}} +bool HttpRetryManager::Tick(float DeltaTime) +{ + FManager::Update(); + return true; +} + +HttpRetryParams::HttpRetryParams(const FRetryLimitCountSetting& InRetryLimitCountOverride /*= FRetryLimitCountSetting()*/, + const FRetryTimeoutRelativeSecondsSetting& InRetryTimeoutRelativeSecondsOverride /*= FRetryTimeoutRelativeSecondsSetting()*/, + const FRetryResponseCodes& InRetryResponseCodes /*= FRetryResponseCodes()*/, + const FRetryVerbs& InRetryVerbs /*= FRetryVerbs()*/, + const FRetryDomainsPtr& InRetryDomains /*= FRetryDomainsPtr() */) + : RetryLimitCountOverride(InRetryLimitCountOverride) + , RetryTimeoutRelativeSecondsOverride(InRetryTimeoutRelativeSecondsOverride) + , RetryResponseCodes(InRetryResponseCodes) + , RetryVerbs(InRetryVerbs) + , RetryDomains(InRetryDomains) +{ +} + void Response::SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) { ResponseCode = InHttpResponseCode; @@ -18,15 +35,6 @@ void Response::SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) } } -void Response::AsyncRetry() const -{ - // Unfortunately, it is currently usafe to call ProcessRequest() directly here. - // This is because the HttpManager will remove all references to this HttpRequest in FHttpManager::Tick including the new request we just added, instead of removing just one. - // This will lead to the request's destruction and eventually a crash. - // The only solution is therefore to ensure we are taking an extra reference to the request, and that the request is added after the queue is flushed. - Async(EAsyncExecution::TaskGraph, [AddRef = FHttpRequestPtr(GetHttpRequest())](){ AddRef->ProcessRequest(); }); -} - {{#cppNamespaceDeclarations}} } {{/cppNamespaceDeclarations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/crystal/configuration.mustache b/modules/openapi-generator/src/main/resources/crystal/configuration.mustache index 7111ba75e75..cc2e15e93fa 100644 --- a/modules/openapi-generator/src/main/resources/crystal/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/configuration.mustache @@ -197,44 +197,44 @@ module {{moduleName}} # Returns Auth Settings hash for api client. def auth_settings - Hash{ {{#authMethods}}{{#isApiKey}}"{{name}}" => { - type: "api_key", - in: {{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}, - key: "{{keyParamName}}", - value: api_key_with_prefix("{{keyParamName}}") - }, + Hash{ +{{#authMethods}} +{{#isApiKey}} + "{{name}}" => { + type: "api_key", + in: {{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}, + key: "{{keyParamName}}", + value: api_key_with_prefix("{{keyParamName}}") + }, {{/isApiKey}} {{#isBasic}} {{#isBasicBasic}} - "{{name}}" => - { - type: "basic", - in: "header", - key: "Authorization", - value: basic_auth_token - }, + "{{name}}" => { + type: "basic", + in: "header", + key: "Authorization", + value: basic_auth_token + }, {{/isBasicBasic}} {{#isBasicBearer}} - "{{name}}" => - { - type: "bearer", - in: "header", - {{#bearerFormat}} - format: "{{{.}}}", - {{/bearerFormat}} - key: "Authorization", - value: "Bearer #{access_token}" - }, + "{{name}}" => { + type: "bearer", + in: "header", + {{#bearerFormat}} + format: "{{{.}}}", + {{/bearerFormat}} + key: "Authorization", + value: "Bearer #{access_token}" + }, {{/isBasicBearer}} {{/isBasic}} {{#isOAuth}} - "{{name}}" => - { - type: "oauth2", - in: "header", - key: "Authorization", - value: "Bearer #{access_token}" - }, + "{{name}}" => { + type: "oauth2", + in: "header", + key: "Authorization", + value: "Bearer #{access_token}" + }, {{/isOAuth}} {{/authMethods}} } diff --git a/modules/openapi-generator/src/main/resources/crystal/model.mustache b/modules/openapi-generator/src/main/resources/crystal/model.mustache index a19cc5f3f6a..021857ee40e 100644 --- a/modules/openapi-generator/src/main/resources/crystal/model.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/model.mustache @@ -1,5 +1,6 @@ # {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} +require "json" require "time" module {{moduleName}} diff --git a/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache b/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache index c36181c48dc..eaf47753fba 100644 --- a/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache @@ -1,8 +1,10 @@ {{#description}} # {{{description}}} {{/description}} - class {{classname}}{{#parent}} < {{{.}}}{{/parent}} include JSON::Serializable - include JSON::Serializable {{#vars}} + class {{classname}}{{#parent}} < {{{.}}}{{/parent}} + include JSON::Serializable + + {{#vars}} {{#description}} # {{{description}}} {{/description}} diff --git a/modules/openapi-generator/src/main/resources/crystal/shard.mustache b/modules/openapi-generator/src/main/resources/crystal/shard.mustache index 89376ca4593..11b01286538 100644 --- a/modules/openapi-generator/src/main/resources/crystal/shard.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/shard.mustache @@ -1,4 +1,4 @@ -name: {{{moduleName}}} +name: {{{shardName}}} version: {{{shardVersion}}} authors: - {{{shardAuthors}}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/README.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/README.mustache index c5f3c0eadfa..b15d2a25bf1 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/README.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/README.mustache @@ -137,6 +137,9 @@ services.AddHttpClient(httpClient => ```csharp using System.Collections.Generic; using System.Diagnostics; +{{#useHttpClient}} +using System.Net.Http; +{{/useHttpClient}} using {{packageName}}.{{apiPackage}}; using {{packageName}}.Client; using {{packageName}}.{{modelPackage}}; @@ -174,7 +177,15 @@ namespace Example {{/authMethods}} {{/hasAuthMethods}} + {{#useHttpClient}} + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new {{classname}}(httpClient, config, httpClientHandler); + {{/useHttpClient}} + {{^useHttpClient}} var apiInstance = new {{classname}}(config); + {{/useHttpClient}} {{#allParams}} {{#isPrimitiveType}} var {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/api_doc.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/api_doc.mustache index 0fd9f879061..d12ee22ea38 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/api_doc.mustache @@ -22,6 +22,9 @@ Method | HTTP request | Description ```csharp using System.Collections.Generic; using System.Diagnostics; +{{#useHttpClient}} +using System.Net.Http; +{{/useHttpClient}} using {{packageName}}.{{apiPackage}}; using {{packageName}}.Client; using {{packageName}}.{{modelPackage}}; @@ -58,7 +61,15 @@ namespace Example {{/authMethods}} {{/hasAuthMethods}} + {{#useHttpClient}} + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new {{classname}}(httpClient, config, httpClientHandler); + {{/useHttpClient}} + {{^useHttpClient}} var apiInstance = new {{classname}}(config); + {{/useHttpClient}} {{#allParams}} {{#isPrimitiveType}} var {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache index 619bcb6bfbb..5477cb0cc73 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache @@ -98,13 +98,13 @@ namespace {{packageName}}.Client if (type == typeof(byte[])) // return byte array { - return response.Content.ReadAsByteArrayAsync().Result; + return response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); } // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) if (type == typeof(Stream)) { - var bytes = response.Content.ReadAsByteArrayAsync().Result; + var bytes = response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); if (headers != null) { var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) @@ -128,18 +128,18 @@ namespace {{packageName}}.Client if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content.ReadAsStringAsync().Result, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), null, System.Globalization.DateTimeStyles.RoundtripKind); } if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type { - return Convert.ChangeType(response.Content.ReadAsStringAsync().Result, type); + return Convert.ChangeType(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), type); } // at this point, it must be a model (json) try { - return JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result, type, _serializerSettings); + return JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), type, _serializerSettings); } catch (Exception e) { @@ -191,8 +191,9 @@ namespace {{packageName}}.Client /// /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public ApiClient() : this({{packageName}}.Client.GlobalConfiguration.Instance.BasePath) { @@ -200,10 +201,11 @@ namespace {{packageName}}.Client /// /// Initializes a new instance of the . + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public ApiClient(String basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); @@ -399,10 +401,10 @@ namespace {{packageName}}.Client partial void InterceptRequest(HttpRequestMessage req); partial void InterceptResponse(HttpRequestMessage req, HttpResponseMessage response); - private ApiResponse ToApiResponse(HttpResponseMessage response, object responseData, Uri uri) + private async Task> ToApiResponse(HttpResponseMessage response, object responseData, Uri uri) { T result = (T) responseData; - string rawContent = response.Content.ToString(); + string rawContent = await response.Content.ReadAsStringAsync(); var transformed = new ApiResponse(response.StatusCode, new Multimap({{#caseInsensitiveResponseHeaders}}StringComparer.OrdinalIgnoreCase{{/caseInsensitiveResponseHeaders}}), result, rawContent) { @@ -444,7 +446,7 @@ namespace {{packageName}}.Client private ApiResponse Exec(HttpRequestMessage req, IReadableConfiguration configuration) { - return ExecAsync(req, configuration).Result; + return ExecAsync(req, configuration).GetAwaiter().GetResult(); } private async Task> ExecAsync(HttpRequestMessage req, @@ -509,6 +511,11 @@ namespace {{packageName}}.Client } {{/supportsRetry}} + if (!response.IsSuccessStatusCode) + { + return await ToApiResponse(response, default(T), req.RequestUri); + } + object responseData = deserializer.Deserialize(response); // if the response type is oneOf/anyOf, call FromJSON to deserialize the data @@ -523,9 +530,7 @@ namespace {{packageName}}.Client InterceptResponse(req, response); - var result = ToApiResponse(response, responseData, req.RequestUri); - - return result; + return await ToApiResponse(response, responseData, req.RequestUri); } {{#supportsAsync}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache index efa52cfbd41..0a3389d0a45 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache @@ -106,20 +106,22 @@ namespace {{packageName}}.{{apiPackage}} /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public {{classname}}() : this((string)null) { } /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public {{classname}}(String basePath) { this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( @@ -136,11 +138,12 @@ namespace {{packageName}}.{{apiPackage}} /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public {{classname}}({{packageName}}.Client.Configuration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); diff --git a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache index 167b6951e01..f3af060d514 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -84,7 +84,7 @@ class ApiClient { ? '?${urlEncodedQueryParams.join('&')}' : ''; - final url = '$basePath$path$queryString'; + final Uri uri = Uri.parse('$basePath$path$queryString'); if (nullableContentType != null) { headerParams['Content-Type'] = nullableContentType; @@ -96,7 +96,7 @@ class ApiClient { body is MultipartFile && (nullableContentType == null || !nullableContentType.toLowerCase().startsWith('multipart/form-data')) ) { - final request = StreamedRequest(method, Uri.parse(url)); + final request = StreamedRequest(method, uri); request.headers.addAll(headerParams); request.contentLength = body.length; body.finalize().listen( @@ -110,7 +110,7 @@ class ApiClient { } if (body is MultipartRequest) { - final request = MultipartRequest(method, Uri.parse(url)); + final request = MultipartRequest(method, uri); request.fields.addAll(body.fields); request.files.addAll(body.files); request.headers.addAll(body.headers); @@ -125,12 +125,12 @@ class ApiClient { final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; switch(method) { - case 'POST': return await _client.post(url, headers: nullableHeaderParams, body: msgBody,); - case 'PUT': return await _client.put(url, headers: nullableHeaderParams, body: msgBody,); - case 'DELETE': return await _client.delete(url, headers: nullableHeaderParams,); - case 'PATCH': return await _client.patch(url, headers: nullableHeaderParams, body: msgBody,); - case 'HEAD': return await _client.head(url, headers: nullableHeaderParams,); - case 'GET': return await _client.get(url, headers: nullableHeaderParams,); + case 'POST': return await _client.post(uri, headers: nullableHeaderParams, body: msgBody,); + case 'PUT': return await _client.put(uri, headers: nullableHeaderParams, body: msgBody,); + case 'DELETE': return await _client.delete(uri, headers: nullableHeaderParams,); + case 'PATCH': return await _client.patch(uri, headers: nullableHeaderParams, body: msgBody,); + case 'HEAD': return await _client.head(uri, headers: nullableHeaderParams,); + case 'GET': return await _client.get(uri, headers: nullableHeaderParams,); } } on SocketException catch (e, trace) { throw ApiException.withInner(HttpStatus.badRequest, 'Socket operation failed: $method $path', e, trace,); diff --git a/modules/openapi-generator/src/main/resources/dart2/build.yaml.mustache b/modules/openapi-generator/src/main/resources/dart2/build.yaml.mustache index b5399b955db..89a4dd6e1c2 100644 --- a/modules/openapi-generator/src/main/resources/dart2/build.yaml.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/build.yaml.mustache @@ -16,4 +16,3 @@ targets: field_rename: none ignore_unannotated: false include_if_null: false - nullable: true diff --git a/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache b/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache index 9de3cbd2314..93c848aa5c1 100644 --- a/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache @@ -9,15 +9,15 @@ authors: - '{{{pubAuthor}}} <{{{pubAuthorEmail}}}>' homepage: '{{{pubHomepage}}}' environment: - sdk: '>=2.0.0 <3.0.0' + sdk: '>=2.12.0 <3.0.0' dependencies: - http: '>=0.12.0 <0.13.0' - intl: '^0.16.1' + http: '>=0.13.0 <0.14.0' + intl: '^0.17.0' meta: '^1.1.8' {{#json_serializable}} json_annotation: '^3.1.1'{{/json_serializable}} dev_dependencies: - test: '>=1.3.0 <1.16.0' + test: '>=1.16.0 <1.18.0' {{#json_serializable}} - build_runner: '^1.0.0' + build_runner: '^1.10.9' json_serializable: '^3.5.1'{{/json_serializable}} diff --git a/modules/openapi-generator/src/main/resources/erlang-server/rebar.config.mustache b/modules/openapi-generator/src/main/resources/erlang-server/rebar.config.mustache index 7ddca0f3027..743b108f384 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/rebar.config.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/rebar.config.mustache @@ -1,6 +1,6 @@ {deps, [ - {cowboy, {git, "https://github.com/ninenines/cowboy.git", {tag, "2.5.0"}}}, + {cowboy, {git, "https://github.com/ninenines/cowboy.git", {tag, "2.8.0"}}}, {rfc3339, {git, "https://github.com/talentdeficit/rfc3339.git", {tag, "master"}}}, - {jsx, {git, "https://github.com/talentdeficit/jsx.git", {tag, "2.9.0"}}}, - {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.5.2"}}} + {jsx, {git, "https://github.com/talentdeficit/jsx.git", {tag, "v3.1.0"}}}, + {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.5.6"}}} ]}. diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache index 117cdef8fd7..216df66eeac 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache @@ -25,7 +25,6 @@ import kotlinx.serialization.Contextual {{#parcelizeModels}} import android.os.Parcelable import kotlinx.parcelize.Parcelize - {{/parcelizeModels}} {{/multiplatform}} {{#multiplatform}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache index 8adf1980e42..7745b52249a 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache @@ -97,7 +97,7 @@ import {{packageName}}.infrastructure.toMultiValue {{/hasQueryParams}} val localVariableHeaders: MutableMap = mutableMapOf({{#hasFormParams}}"Content-Type" to {{^consumes}}"multipart/form-data"{{/consumes}}{{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}}{{/hasFormParams}}) {{#headerParams}} - {{{paramName}}}?.apply { localVariableHeaders["{{baseName}}"] = {{#isContainer}}this.joinToString(separator = collectionDelimiter("{{collectionFormat}}")){{/isContainer}}{{^isContainer}}this.toString(){{/isContainer}} } + {{{paramName}}}{{^required}}?{{/required}}.apply { localVariableHeaders["{{baseName}}"] = {{#isContainer}}this.joinToString(separator = collectionDelimiter("{{collectionFormat}}")){{/isContainer}}{{^isContainer}}this.toString(){{/isContainer}} } {{/headerParams}} val localVariableConfig = RequestConfig( diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/README.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/README.mustache new file mode 100644 index 00000000000..24c4728fdd3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/README.mustache @@ -0,0 +1,84 @@ +# {{packageName}} - Kotlin Server library for {{appName}} + +## Requires + +* Kotlin 1.1.2 +* Gradle 3.3 + +## Build + +First, create the gradle wrapper script: + +``` +gradle wrapper +``` + +Then, run: + +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Features/Implementation Notes + +* Supports JSON inputs/outputs, File inputs, and Form inputs. +* Supports collection formats for query parameters: csv, tsv, ssv, pipes. +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. + +{{#generateApiDocs}} + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +{{/generateApiDocs}} + +{{#generateModelDocs}} + +## Documentation for Models + +{{#modelPackage}} +{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} +{{/modelPackage}} +{{^modelPackage}} +No model defined in this package +{{/modelPackage}} +{{/generateModelDocs}} + +{{! TODO: optional documentation for authorization? }} +## Documentation for Authorization + +{{^authMethods}} +All endpoints do not require authorization. +{{/authMethods}} +{{#authMethods}} +{{#last}} +Authentication schemes defined for the API: +{{/last}} +{{/authMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/api_doc.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/api_doc.mustache new file mode 100644 index 00000000000..08d90eef4a2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/api_doc.mustache @@ -0,0 +1,65 @@ +# {{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +# **{{operationId}}** +> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) + +{{summary}}{{#notes}} + +{{notes}}{{/notes}} + +### Example +```kotlin +// Import classes: +//import {{{packageName}}}.infrastructure.* +//import {{{modelPackage}}}.* + +{{! TODO: Auth method documentation examples}} +val apiInstance = {{{classname}}}() +{{#allParams}} +val {{{paramName}}} : {{{dataType}}} = {{{example}}} // {{{dataType}}} | {{{description}}} +{{/allParams}} +try { + {{#returnType}}val result : {{{returnType}}} = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}} + println(result){{/returnType}} +} catch (e: ClientException) { + println("4xx response calling {{{classname}}}#{{{operationId}}}") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling {{{classname}}}#{{{operationId}}}") + e.printStackTrace() +} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#generateModelDocs}}[**{{dataType}}**]({{baseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{dataType}}**{{/generateModelDocs}}{{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{#defaultValue}} [default to {{defaultValue}}]{{/defaultValue}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{#generateModelDocs}}[**{{returnType}}**]({{returnBaseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{returnType}}**{{/generateModelDocs}}{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/class_doc.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/class_doc.mustache new file mode 100644 index 00000000000..a3405b25c84 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/class_doc.mustache @@ -0,0 +1,15 @@ +# {{classname}} + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isEnum}}[**inline**](#{{datatypeWithEnum}}){{/isEnum}}{{^isEnum}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}}{{/isEnum}} | {{description}} | {{^required}} [optional]{{/required}}{{#isReadOnly}} [readonly]{{/isReadOnly}} +{{/vars}} +{{#vars}}{{#isEnum}} + +{{!NOTE: see java's resources "pojo_doc.mustache" once enums are fully implemented}} +## Enum: {{baseName}} +Name | Value +---- | -----{{#allowableValues}} +{{name}} | {{#values}}{{.}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}} +{{/isEnum}}{{/vars}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class.mustache new file mode 100644 index 00000000000..e22559b5cc9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class.mustache @@ -0,0 +1,52 @@ +{{#parcelizeModels}} +import android.os.Parcelable +import kotlinx.parcelize.Parcelize + +{{/parcelizeModels}} +{{#serializableModel}} +import java.io.Serializable +{{/serializableModel}} +/** + * {{{description}}} +{{#vars}} + * @param {{name}} {{{description}}} +{{/vars}} + */ +{{#parcelizeModels}} +@Parcelize +{{/parcelizeModels}} +data class {{classname}} ( +{{#requiredVars}} +{{>data_class_req_var}}{{^-last}}, +{{/-last}}{{/requiredVars}}{{#hasRequired}}{{#hasOptional}}, +{{/hasOptional}}{{/hasRequired}}{{#optionalVars}}{{>data_class_opt_var}}{{^-last}}, +{{/-last}}{{/optionalVars}} +) {{^serializableModel}}{{#parcelizeModels}} : Parcelable{{/parcelizeModels}}{{/serializableModel}}{{^parcelizeModels}}{{#serializableModel}}: Serializable {{/serializableModel}}{{/parcelizeModels}}{{#parcelizeModels}}{{#serializableModel}} : Parcelable, Serializable {{/serializableModel}}{{/parcelizeModels}} +{{#vendorExtensions.x-has-data-class-body}} +{ +{{/vendorExtensions.x-has-data-class-body}} +{{#serializableModel}} + companion object { + private const val serialVersionUID: Long = 123 + } +{{/serializableModel}} +{{#hasEnums}} + {{#vars}} + {{#isEnum}} + /** + * {{{description}}} + * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} + */ + enum class {{nameInCamelCase}}(val value: {{dataType}}){ + {{#allowableValues}} + {{#enumVars}} + {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} + {{/allowableValues}} + } +{{/isEnum}} +{{/vars}} +{{/hasEnums}} +{{#vendorExtensions.x-has-data-class-body}} +} +{{/vendorExtensions.x-has-data-class-body}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class_opt_var.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class_opt_var.mustache new file mode 100644 index 00000000000..b1060118732 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class_opt_var.mustache @@ -0,0 +1,4 @@ +{{#description}} + /* {{{description}}} */ +{{/description}} + {{>modelMutable}} {{{name}}}: {{#isEnum}}{{classname}}.{{nameInCamelCase}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}? = {{#defaultvalue}}{{defaultvalue}}{{/defaultvalue}}{{^defaultvalue}}null{{/defaultvalue}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class_req_var.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class_req_var.mustache new file mode 100644 index 00000000000..c79bfec01bd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class_req_var.mustache @@ -0,0 +1,4 @@ +{{#description}} + /* {{{description}}} */ +{{/description}} + {{>modelMutable}} {{{name}}}: {{#isEnum}}{{classname}}.{{nameInCamelCase}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/enum_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/enum_class.mustache new file mode 100644 index 00000000000..791398b9789 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/enum_class.mustache @@ -0,0 +1,9 @@ +/** +* {{{description}}} +* Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} +*/ +enum class {{classname}}(val value: {{dataType}}){ +{{#allowableValues}}{{#enumVars}} + {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} +{{/enumVars}}{{/allowableValues}} +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/enum_doc.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/enum_doc.mustache new file mode 100644 index 00000000000..fcb3d7e61aa --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/enum_doc.mustache @@ -0,0 +1,7 @@ +# {{classname}} + +## Enum + +{{#allowableValues}}{{#enumVars}} + * `{{name}}` (value: `{{{value}}}`) +{{/enumVars}}{{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/ApiKeyAuth.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/ApiKeyAuth.kt.mustache new file mode 100644 index 00000000000..e50c0793be4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/ApiKeyAuth.kt.mustache @@ -0,0 +1,85 @@ +package {{packageName}}.infrastructure + +import io.ktor.application.ApplicationCall +import io.ktor.application.call +import io.ktor.auth.Authentication +import io.ktor.auth.AuthenticationFailedCause +import io.ktor.auth.AuthenticationPipeline +import io.ktor.auth.AuthenticationProvider +import io.ktor.auth.Credential +import io.ktor.auth.Principal +import io.ktor.auth.UnauthorizedResponse +import io.ktor.http.auth.HeaderValueEncoding +import io.ktor.http.auth.HttpAuthHeader +import io.ktor.request.ApplicationRequest +import io.ktor.response.respond + +enum class ApiKeyLocation(val location: String) { + QUERY("query"), + HEADER("header") +} +data class ApiKeyCredential(val value: String): Credential +data class ApiPrincipal(val apiKeyCredential: ApiKeyCredential?) : Principal + + + +/** +* Represents a Api Key authentication provider +* @param name is the name of the provider, or `null` for a default provider +*/ +class ApiKeyAuthenticationProvider(name: String?) : AuthenticationProvider(name) { + internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = { null } + + var apiKeyName: String = ""; + + var apiKeyLocation: ApiKeyLocation = ApiKeyLocation.QUERY; + + /** + * Sets a validation function that will check given [ApiKeyCredential] instance and return [Principal], + * or null if credential does not correspond to an authenticated principal + */ + fun validate(body: suspend ApplicationCall.(ApiKeyCredential) -> Principal?) { + authenticationFunction = body + } +} + +fun Authentication.Configuration.apiKeyAuth(name: String? = null, configure: ApiKeyAuthenticationProvider.() -> Unit) { + val provider = ApiKeyAuthenticationProvider(name).apply(configure) + val apiKeyName = provider.apiKeyName + val apiKeyLocation = provider.apiKeyLocation + val authenticate = provider.authenticationFunction + + provider.pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> + val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) + val principal = credentials?.let { authenticate(call, it) } + + val cause = when { + credentials == null -> AuthenticationFailedCause.NoCredentials + principal == null -> AuthenticationFailedCause.InvalidCredentials + else -> null + } + + if (cause != null) { + context.challenge(apiKeyName, cause) { + // TODO: Verify correct response structure here. + call.respond(UnauthorizedResponse(HttpAuthHeader.Parameterized("API_KEY", mapOf("key" to apiKeyName), HeaderValueEncoding.QUOTED_ALWAYS))) + it.complete() + } + } + + if (principal != null) { + context.principal(principal) + } + } +} + +fun ApplicationRequest.apiKeyAuthenticationCredentials(apiKeyName: String, apiKeyLocation: ApiKeyLocation): ApiKeyCredential? { + val value: String? = when(apiKeyLocation) { + ApiKeyLocation.QUERY -> this.queryParameters[apiKeyName] + ApiKeyLocation.HEADER -> this.headers[apiKeyName] + } + when (value) { + null -> return null + else -> return ApiKeyCredential(value) + } +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/AppMain.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/AppMain.kt.mustache new file mode 100644 index 00000000000..bef736de059 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/AppMain.kt.mustache @@ -0,0 +1,145 @@ +package {{packageName}} + +import com.codahale.metrics.Slf4jReporter +import com.typesafe.config.ConfigFactory +import io.ktor.application.Application +import io.ktor.application.ApplicationStopping +import io.ktor.application.install +import io.ktor.application.log +import io.ktor.client.HttpClient +import io.ktor.client.engine.apache.Apache +import io.ktor.config.HoconApplicationConfig +{{#featureAutoHead}} +import io.ktor.features.AutoHeadResponse +{{/featureAutoHead}} +{{#featureCompression}} +import io.ktor.features.Compression +{{/featureCompression}} +{{#featureCORS}} +import io.ktor.features.CORS +{{/featureCORS}} +{{#featureConditionalHeaders}} +import io.ktor.features.ConditionalHeaders +{{/featureConditionalHeaders}} +import io.ktor.features.ContentNegotiation +import io.ktor.features.DefaultHeaders +{{#featureHSTS}} +import io.ktor.features.HSTS +{{/featureHSTS}} +import io.ktor.gson.GsonConverter +import io.ktor.http.ContentType +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.Locations +import io.ktor.metrics.Metrics +import io.ktor.routing.Routing +import java.util.concurrent.TimeUnit +import io.ktor.util.KtorExperimentalAPI +{{#hasAuthMethods}} +import io.ktor.auth.Authentication +import io.ktor.auth.oauth +import org.openapitools.server.infrastructure.ApiKeyCredential +import org.openapitools.server.infrastructure.ApiPrincipal +import org.openapitools.server.infrastructure.apiKeyAuth +{{/hasAuthMethods}} +{{#generateApis}}{{#apiInfo}}{{#apis}}import {{apiPackage}}.{{classname}} +{{/apis}}{{/apiInfo}}{{/generateApis}} + +@KtorExperimentalAPI +internal val settings = HoconApplicationConfig(ConfigFactory.defaultApplication(HTTP::class.java.classLoader)) + +object HTTP { + val client = HttpClient(Apache) +} + +@KtorExperimentalAPI +@KtorExperimentalLocationsAPI +fun Application.main() { + install(DefaultHeaders) + install(Metrics) { + val reporter = Slf4jReporter.forRegistry(registry) + .outputTo(log) + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .build() + reporter.start(10, TimeUnit.SECONDS) + } +{{#generateApis}} + install(ContentNegotiation) { + register(ContentType.Application.Json, GsonConverter()) + } + {{#featureAutoHead}} + install(AutoHeadResponse) // see http://ktor.io/features/autoheadresponse.html + {{/featureAutoHead}} + {{#featureConditionalHeaders}} + install(ConditionalHeaders) // see http://ktor.io/features/conditional-headers.html + {{/featureConditionalHeaders}} + {{#featureHSTS}} + install(HSTS, ApplicationHstsConfiguration()) // see http://ktor.io/features/hsts.html + {{/featureHSTS}} + {{#featureCORS}} + install(CORS, ApplicationCORSConfiguration()) // see http://ktor.io/features/cors.html + {{/featureCORS}} + {{#featureCompression}} + install(Compression, ApplicationCompressionConfiguration()) // see http://ktor.io/features/compression.html + {{/featureCompression}} + install(Locations) // see http://ktor.io/features/locations.html + {{#hasAuthMethods}} + install(Authentication) { + {{#authMethods}} + {{#isBasic}} + basic("{{{name}}}") { + validate { credentials -> + // TODO: "Apply your basic authentication functionality." + // Accessible in-method via call.principal() + if (credentials.name == "Swagger" && "Codegen" == credentials.password) { + UserIdPrincipal(credentials.name) + } else { + null + } + } + {{/isBasic}} + {{#isApiKey}} + // "Implement API key auth ({{{name}}}) for parameter name '{{{keyParamName}}}'." + apiKeyAuth("{{{name}}}") { + validate { apikeyCredential: ApiKeyCredential -> + when { + apikeyCredential.value == "keyboardcat" -> ApiPrincipal(apikeyCredential) + else -> null + } + } + } + {{/isApiKey}} + {{#isOAuth}} + {{#bodyAllowed}} + {{/bodyAllowed}} + {{^bodyAllowed}} + oauth("{{name}}") { + client = HttpClient(Apache) + providerLookup = { ApplicationAuthProviders["{{{name}}}"] } + urlProvider = { _ -> + // TODO: define a callback url here. + "/" + } + } + {{/bodyAllowed}} + {{/isOAuth}} + {{/authMethods}} + } + {{/hasAuthMethods}} + install(Routing) { + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{classname}}() + {{/operations}} + {{/apis}} + {{/apiInfo}} + } + +{{/generateApis}} + + environment.monitor.subscribe(ApplicationStopping) + { + HTTP.client.close() + } +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Configuration.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Configuration.kt.mustache new file mode 100644 index 00000000000..3b568d21eba --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Configuration.kt.mustache @@ -0,0 +1,114 @@ +package {{packageName}} + +// Use this file to hold package-level internal functions that return receiver object passed to the `install` method. +import io.ktor.auth.OAuthServerSettings +import io.ktor.features.Compression +import io.ktor.features.HSTS +import io.ktor.features.deflate +import io.ktor.features.gzip +import io.ktor.features.minimumSize +import io.ktor.http.HttpMethod +import io.ktor.util.KtorExperimentalAPI +import java.time.Duration +import java.util.concurrent.Executors + +import {{packageName}}.settings + +{{#featureCORS}} +/** + * Application block for [CORS] configuration. + * + * This file may be excluded in .openapi-generator-ignore, + * and application specific configuration can be applied in this function. + * + * See http://ktor.io/features/cors.html + */ +internal fun ApplicationCORSConfiguration(): CORS.Configuration.() -> Unit { + return { + // method(HttpMethod.Options) + // header(HttpHeaders.XForwardedProto) + // anyHost() + // host("my-host") + // host("my-host:80") + // host("my-host", subDomains = listOf("www")) + // host("my-host", schemes = listOf("http", "https")) + // allowCredentials = true + // maxAge = Duration.ofDays(1) + } +} +{{/featureCORS}} + +{{#featureHSTS}} +/** + * Application block for [HSTS] configuration. + * + * This file may be excluded in .openapi-generator-ignore, + * and application specific configuration can be applied in this function. + * + * See http://ktor.io/features/hsts.html + */ +internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit { + return { + maxAge = Duration.ofDays(365) + includeSubDomains = true + preload = false + + // You may also apply any custom directives supported by specific user-agent. For example: + // customDirectives.put("redirectHttpToHttps", "false") + } +} +{{/featureHSTS}} + +{{#featureCompression}} +/** + * Application block for [Compression] configuration. + * + * This file may be excluded in .openapi-generator-ignore, + * and application specific configuration can be applied in this function. + * + * See http://ktor.io/features/compression.html + */ +internal fun ApplicationCompressionConfiguration(): Compression.Configuration.() -> Unit { + return { + gzip { + priority = 1.0 + } + deflate { + priority = 10.0 + minimumSize(1024) // condition + } + } +} +{{/featureCompression}} + +// Defines authentication mechanisms used throughout the application. +@KtorExperimentalAPI +val ApplicationAuthProviders: Map = listOf( +{{#authMethods}} + {{#isOAuth}} + OAuthServerSettings.OAuth2ServerSettings( + name = "{{name}}", + authorizeUrl = "{{authorizationUrl}}", + accessTokenUrl = "{{tokenUrl}}", + requestMethod = HttpMethod.Get, + {{! TODO: flow, doesn't seem to be supported yet by ktor }} + clientId = settings.property("auth.oauth.{{name}}.clientId").getString(), + clientSecret = settings.property("auth.oauth.{{name}}.clientSecret").getString(), + defaultScopes = listOf({{#scopes}}"{{scope}}"{{^-last}}, {{/-last}}{{/scopes}}) + ){{^-last}},{{/-last}} + {{/isOAuth}} +{{/authMethods}} +// OAuthServerSettings.OAuth2ServerSettings( +// name = "facebook", +// authorizeUrl = "https://graph.facebook.com/oauth/authorize", +// accessTokenUrl = "https://graph.facebook.com/oauth/access_token", +// requestMethod = HttpMethod.Post, +// +// clientId = "settings.property("auth.oauth.facebook.clientId").getString()", +// clientSecret = "settings.property("auth.oauth.facebook.clientSecret").getString()", +// defaultScopes = listOf("public_profile") +// ) +).associateBy { it.name } + +// Provides an application-level fixed thread pool on which to execute coroutines (mainly) +internal val ApplicationExecutors = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 4) diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Dockerfile.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Dockerfile.mustache new file mode 100644 index 00000000000..b9158ac26e3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Dockerfile.mustache @@ -0,0 +1,7 @@ +FROM openjdk:8-jre-alpine + +COPY ./build/libs/{{artifactId}}.jar /root/{{artifactId}}.jar + +WORKDIR /root + +CMD ["java", "-server", "-Xms4g", "-Xmx4g", "-XX:+UseG1GC", "-XX:MaxGCPauseMillis=100", "-XX:+UseStringDeduplication", "-jar", "{{artifactId}}.jar"] \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Paths.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Paths.kt.mustache new file mode 100644 index 00000000000..610f48203aa --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Paths.kt.mustache @@ -0,0 +1,28 @@ +{{>licenseInfo}} +package {{packageName}} + +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.Location +{{#imports}}import {{import}} +{{/imports}} + +{{#apiInfo}} +object Paths { +{{#apis}} +{{#operations}} + {{#operation}} + {{^bodyAllowed}} + /** + * {{summary}} + * {{#unescapedNotes}}{{.}}{{/unescapedNotes}} + {{#allParams}}* @param {{paramName}} {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} + {{/allParams}}*/ + @KtorExperimentalLocationsAPI + @Location("{{path}}") class {{operationId}}({{#allParams}}val {{paramName}}: {{{dataType}}}{{^required}}? = null{{/required}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + + {{/bodyAllowed}} + {{/operation}} +{{/operations}} +{{/apis}} +} +{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/README.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/README.mustache new file mode 100644 index 00000000000..4c34e8f6bf2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/README.mustache @@ -0,0 +1,101 @@ +# {{packageName}} - Kotlin Server library for {{appName}} + +{{#unescapedAppDescription}} +{{.}} +{{/unescapedAppDescription}} + +Generated by OpenAPI Generator {{generatorVersion}}{{^hideGenerationTimestamp}} ({{generatedDate}}){{/hideGenerationTimestamp}}. + +## Requires + +* Kotlin 1.3.21 +* Gradle 4.9 + +## Build + +First, create the gradle wrapper script: + +``` +gradle wrapper +``` + +Then, run: + +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Running + +The server builds as a fat jar with a main entrypoint. To start the service, run `java -jar ./build/libs/{{artifactId}}.jar`. + +You may also run in docker: + +``` +docker build -t {{artifactId}} . +docker run -p 8080:8080 {{artifactId}} +``` + +## Features/Implementation Notes + +* Supports JSON inputs/outputs, File inputs, and Form inputs (see ktor documentation for more info). +* ~Supports collection formats for query parameters: csv, tsv, ssv, pipes.~ +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. + +{{#generateApiDocs}} + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +{{/generateApiDocs}} + +{{#generateModelDocs}} + +## Documentation for Models + +{{#modelPackage}} +{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} +{{/modelPackage}} +{{^modelPackage}} +No model defined in this package +{{/modelPackage}} +{{/generateModelDocs}} + +{{! TODO: optional documentation for authorization? }} +## Documentation for Authorization + +{{^authMethods}} +All endpoints do not require authorization. +{{/authMethods}} +{{#authMethods}} +{{#last}} +Authentication schemes defined for the API: +{{/last}} +{{/authMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_api_body.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_api_body.mustache new file mode 100644 index 00000000000..9dcf500f49b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_api_body.mustache @@ -0,0 +1,25 @@ +{{#hasAuthMethods}} +{{>libraries/ktor/_principal}} +if (principal == null) { + call.respond(HttpStatusCode.Unauthorized) +} else { + {{#examples}} + {{#-first}} + {{#lambda.indented}}{{>_response}}{{/lambda.indented}} + {{/-first}} + {{/examples}} + {{^examples}} + call.respond(HttpStatusCode.NotImplemented) + {{/examples}} +} +{{/hasAuthMethods}} +{{^hasAuthMethods}} +{{#examples}} +{{#-first}} +{{>libraries/ktor/_response}} +{{/-first}} +{{/examples}} +{{^examples}} +call.respond(HttpStatusCode.NotImplemented) +{{/examples}} +{{/hasAuthMethods}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_principal.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_principal.mustache new file mode 100644 index 00000000000..d49c5d537f0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_principal.mustache @@ -0,0 +1,11 @@ +{{#authMethods}} +{{#isBasic}} +val principal = call.authentication.principal() +{{/isBasic}} +{{#isApiKey}} +val principal = call.authentication.principal() +{{/isApiKey}} +{{#isOAuth}} +val principal = call.authentication.principal() +{{/isOAuth}} +{{/authMethods}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_response.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_response.mustache new file mode 100644 index 00000000000..fb26fb4a7f1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_response.mustache @@ -0,0 +1,8 @@ +val exampleContentType = "{{{contentType}}}" +val exampleContentString = """{{&example}}""" + +when(exampleContentType) { + "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) + "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) + else -> call.respondText(exampleContentString) +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/api.mustache new file mode 100644 index 00000000000..881e3b108ec --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/api.mustache @@ -0,0 +1,62 @@ +{{>licenseInfo}} +package {{apiPackage}} + +import com.google.gson.Gson +import io.ktor.application.call +import io.ktor.auth.UserIdPrincipal +import io.ktor.auth.authentication +import io.ktor.auth.authenticate +import io.ktor.auth.OAuthAccessTokenResponse +import io.ktor.auth.OAuthServerSettings +import io.ktor.http.ContentType +import io.ktor.http.HttpStatusCode +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.delete +import io.ktor.locations.get +import io.ktor.response.respond +import io.ktor.response.respondText +import io.ktor.routing.Route +import io.ktor.routing.post +import io.ktor.routing.put +import io.ktor.routing.route + +import {{packageName}}.Paths +import {{packageName}}.infrastructure.ApiPrincipal + + +{{#imports}}import {{import}} +{{/imports}} + +{{#operations}} +@KtorExperimentalLocationsAPI +fun Route.{{classname}}() { + val gson = Gson() + val empty = mutableMapOf() +{{#operation}} + {{#bodyAllowed}} + + route("{{path}}") { + {{#hasAuthMethods}} + {{#authMethods}} + authenticate("{{{name}}}") { + {{/authMethods}} + {{/hasAuthMethods}} + {{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}} { + {{#lambda.indented_12}}{{>libraries/ktor/_api_body}}{{/lambda.indented_12}} + } + {{#hasAuthMethods}} + } + {{/hasAuthMethods}} + } + {{/bodyAllowed}} + {{^bodyAllowed}} + + {{! NOTE: Locations can be used on routes without body parameters.}} + {{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}} { _: Paths.{{operationId}} -> + {{#lambda.indented_8}}{{>libraries/ktor/_api_body}}{{/lambda.indented_8}} + } + {{/bodyAllowed}} + +{{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/application.conf.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/application.conf.mustache new file mode 100644 index 00000000000..032be42fa11 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/application.conf.mustache @@ -0,0 +1,27 @@ +ktor { + deployment { + environment = development + port = 8080 + autoreload = true + watch = [ {{packageName}} ] + } + + application { + modules = [ {{packageName}}.AppMainKt.main ] + } +} + +# Typesafe config allows multiple ways to provide configuration values without hard-coding them here. +# Please see https://github.com/lightbend/config for details. +auth { + oauth { +{{#authMethods}} +{{#isOAuth}} + {{name}} { + clientId = "" + clientSecret = "" + } +{{/isOAuth}} +{{/authMethods}} + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/build.gradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/build.gradle.mustache new file mode 100644 index 00000000000..08c317ea666 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/build.gradle.mustache @@ -0,0 +1,68 @@ +group '{{groupId}}' +version '{{artifactVersion}}' + +wrapper { + gradleVersion = '4.9' + distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" +} + +buildscript { + ext.kotlin_version = '1.3.21' + ext.ktor_version = '1.1.3' + ext.shadow_version = '2.0.3' + + repositories { + maven { url "https://repo1.maven.org/maven2" } + maven { + url = "https://plugins.gradle.org/m2/" + } + } + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + classpath "com.github.jengelman.gradle.plugins:shadow:$shadow_version" + } +} + +apply plugin: 'java' +apply plugin: 'kotlin' +apply plugin: 'application' + +mainClassName = "io.ktor.server.netty.DevelopmentEngine" + +// Initialization order with shadow 2.0.1 and Gradle 4.3 is weird. +// See https://github.com/johnrengelman/shadow/issues/336#issuecomment-355402508 +apply plugin: 'com.github.johnrengelman.shadow' + +sourceCompatibility = 1.8 + +compileKotlin { + kotlinOptions.jvmTarget = "1.8" +} + +compileTestKotlin { + kotlinOptions.jvmTarget = "1.8" +} + +shadowJar { + baseName = '{{artifactId}}' + classifier = null + version = null +} + +repositories { + maven { url "https://repo1.maven.org/maven2" } + maven { url "https://dl.bintray.com/kotlin/ktor" } + maven { url "https://dl.bintray.com/kotlin/kotlinx" } +} + +dependencies { + compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + compile "io.ktor:ktor-server-netty:$ktor_version" + compile "io.ktor:ktor-metrics:$ktor_version" + compile "io.ktor:ktor-locations:$ktor_version" + compile "io.ktor:ktor-gson:$ktor_version" + compile "io.ktor:ktor-client-core:$ktor_version" + compile "io.ktor:ktor-client-apache:$ktor_version" + compile "ch.qos.logback:logback-classic:1.2.1" + testCompile group: 'junit', name: 'junit', version: '4.13' +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/gradle.properties b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/gradle.properties new file mode 100644 index 00000000000..5f1ed7bbe02 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/gradle.properties @@ -0,0 +1 @@ +org.gradle.caching=true \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/licenseInfo.mustache new file mode 100644 index 00000000000..3a547de74bb --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/licenseInfo.mustache @@ -0,0 +1,11 @@ +/** +* {{{appName}}} +* {{{appDescription}}} +* +* {{#version}}The version of the OpenAPI document: {{{version}}}{{/version}} +* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/logback.xml b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/logback.xml new file mode 100644 index 00000000000..d0eaba8debd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/logback.xml @@ -0,0 +1,15 @@ + + + + %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/licenseInfo.mustache new file mode 100644 index 00000000000..3a547de74bb --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/licenseInfo.mustache @@ -0,0 +1,11 @@ +/** +* {{{appName}}} +* {{{appDescription}}} +* +* {{#version}}The version of the OpenAPI document: {{{version}}}{{/version}} +* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/model.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/model.mustache new file mode 100644 index 00000000000..780dd84b97e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/model.mustache @@ -0,0 +1,11 @@ +{{>licenseInfo}} +package {{modelPackage}} + +{{#imports}}import {{import}} +{{/imports}} + +{{#models}} +{{#model}} +{{#isEnum}}{{>enum_class}}{{/isEnum}}{{^isEnum}}{{>data_class}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/modelMutable.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/modelMutable.mustache new file mode 100644 index 00000000000..4c7f3900717 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/modelMutable.mustache @@ -0,0 +1 @@ +{{#modelMutable}}var{{/modelMutable}}{{^modelMutable}}val{{/modelMutable}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/model_doc.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/model_doc.mustache new file mode 100644 index 00000000000..e3b71842118 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/model_doc.mustache @@ -0,0 +1,3 @@ +{{#models}}{{#model}} +{{#isEnum}}{{>enum_doc}}{{/isEnum}}{{^isEnum}}{{>class_doc}}{{/isEnum}} +{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/settings.gradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/settings.gradle.mustache new file mode 100644 index 00000000000..448dc07602e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/settings.gradle.mustache @@ -0,0 +1 @@ +rootProject.name = '{{artifactId}}' \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/README.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/README.mustache index 24c4728fdd3..910f1a9c9e2 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/README.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/README.mustache @@ -2,8 +2,8 @@ ## Requires -* Kotlin 1.1.2 -* Gradle 3.3 +* Kotlin 1.4.31 +* Gradle 6.8.2 ## Build diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/data_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/data_class.mustache index e22559b5cc9..215a291253f 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/data_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/data_class.mustache @@ -15,7 +15,7 @@ import java.io.Serializable {{#parcelizeModels}} @Parcelize {{/parcelizeModels}} -data class {{classname}} ( +data class {{classname}}( {{#requiredVars}} {{>data_class_req_var}}{{^-last}}, {{/-last}}{{/requiredVars}}{{#hasRequired}}{{#hasOptional}}, diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/enum_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/enum_class.mustache index 791398b9789..2f24a1de76b 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/enum_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/enum_class.mustache @@ -2,7 +2,7 @@ * {{{description}}} * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} */ -enum class {{classname}}(val value: {{dataType}}){ +enum class {{classname}}(val value: {{dataType}}) { {{#allowableValues}}{{#enumVars}} {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} {{/enumVars}}{{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/ApiKeyAuth.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/ApiKeyAuth.kt.mustache index e50c0793be4..a0abbcddfd0 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/ApiKeyAuth.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/ApiKeyAuth.kt.mustache @@ -1,85 +1,105 @@ package {{packageName}}.infrastructure -import io.ktor.application.ApplicationCall -import io.ktor.application.call -import io.ktor.auth.Authentication -import io.ktor.auth.AuthenticationFailedCause -import io.ktor.auth.AuthenticationPipeline -import io.ktor.auth.AuthenticationProvider -import io.ktor.auth.Credential -import io.ktor.auth.Principal -import io.ktor.auth.UnauthorizedResponse -import io.ktor.http.auth.HeaderValueEncoding -import io.ktor.http.auth.HttpAuthHeader -import io.ktor.request.ApplicationRequest -import io.ktor.response.respond +import io.ktor.application.* +import io.ktor.auth.* +import io.ktor.http.auth.* +import io.ktor.request.* +import io.ktor.response.* enum class ApiKeyLocation(val location: String) { QUERY("query"), HEADER("header") } -data class ApiKeyCredential(val value: String): Credential + +data class ApiKeyCredential(val value: String) : Credential data class ApiPrincipal(val apiKeyCredential: ApiKeyCredential?) : Principal - - /** * Represents a Api Key authentication provider * @param name is the name of the provider, or `null` for a default provider */ -class ApiKeyAuthenticationProvider(name: String?) : AuthenticationProvider(name) { - internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = { null } +class ApiKeyAuthenticationProvider(configuration: Configuration) : AuthenticationProvider(configuration) { - var apiKeyName: String = ""; + private val authenticationFunction = configuration.authenticationFunction - var apiKeyLocation: ApiKeyLocation = ApiKeyLocation.QUERY; + private val apiKeyName: String = configuration.apiKeyName - /** - * Sets a validation function that will check given [ApiKeyCredential] instance and return [Principal], - * or null if credential does not correspond to an authenticated principal - */ - fun validate(body: suspend ApplicationCall.(ApiKeyCredential) -> Principal?) { - authenticationFunction = body - } -} + private val apiKeyLocation: ApiKeyLocation = configuration.apiKeyLocation -fun Authentication.Configuration.apiKeyAuth(name: String? = null, configure: ApiKeyAuthenticationProvider.() -> Unit) { - val provider = ApiKeyAuthenticationProvider(name).apply(configure) - val apiKeyName = provider.apiKeyName - val apiKeyLocation = provider.apiKeyLocation - val authenticate = provider.authenticationFunction + internal fun install() { + pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> + val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) + val principal = credentials?.let { authenticationFunction(call, it) } - provider.pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> - val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) - val principal = credentials?.let { authenticate(call, it) } + val cause = when { + credentials == null -> AuthenticationFailedCause.NoCredentials + principal == null -> AuthenticationFailedCause.InvalidCredentials + else -> null + } - val cause = when { - credentials == null -> AuthenticationFailedCause.NoCredentials - principal == null -> AuthenticationFailedCause.InvalidCredentials - else -> null - } + if (cause != null) { + context.challenge(apiKeyName, cause) { + call.respond( + UnauthorizedResponse( + HttpAuthHeader.Parameterized( + "API_KEY", + mapOf("key" to apiKeyName), + HeaderValueEncoding.QUOTED_ALWAYS + ) + ) + ) + it.complete() + } + } - if (cause != null) { - context.challenge(apiKeyName, cause) { - // TODO: Verify correct response structure here. - call.respond(UnauthorizedResponse(HttpAuthHeader.Parameterized("API_KEY", mapOf("key" to apiKeyName), HeaderValueEncoding.QUOTED_ALWAYS))) - it.complete() + if (principal != null) { + context.principal(principal) } } + } - if (principal != null) { - context.principal(principal) + class Configuration internal constructor(name: String?) : AuthenticationProvider.Configuration(name) { + + internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = { + throw NotImplementedError( + "Api Key auth validate function is not specified. Use apiKeyAuth { validate { ... } } to fix." + ) + } + + var apiKeyName: String = "" + + var apiKeyLocation: ApiKeyLocation = ApiKeyLocation.QUERY + + /** + * Sets a validation function that will check given [ApiKeyCredential] instance and return [Principal], + * or null if credential does not correspond to an authenticated principal + */ + fun validate(body: suspend ApplicationCall.(ApiKeyCredential) -> Principal?) { + authenticationFunction = body } } } -fun ApplicationRequest.apiKeyAuthenticationCredentials(apiKeyName: String, apiKeyLocation: ApiKeyLocation): ApiKeyCredential? { - val value: String? = when(apiKeyLocation) { +fun Authentication.Configuration.apiKeyAuth( + name: String? = null, + configure: ApiKeyAuthenticationProvider.Configuration.() -> Unit +) { + val configuration = ApiKeyAuthenticationProvider.Configuration(name).apply(configure) + val provider = ApiKeyAuthenticationProvider(configuration) + provider.install() + register(provider) +} + +fun ApplicationRequest.apiKeyAuthenticationCredentials( + apiKeyName: String, + apiKeyLocation: ApiKeyLocation +): ApiKeyCredential? { + val value: String? = when (apiKeyLocation) { ApiKeyLocation.QUERY -> this.queryParameters[apiKeyName] ApiKeyLocation.HEADER -> this.headers[apiKeyName] } - when (value) { - null -> return null - else -> return ApiKeyCredential(value) + return when (value) { + null -> null + else -> ApiKeyCredential(value) } } diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache index bef736de059..1556c44ae58 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache @@ -28,15 +28,16 @@ import io.ktor.features.HSTS {{/featureHSTS}} import io.ktor.gson.GsonConverter import io.ktor.http.ContentType +{{#featureLocations}} import io.ktor.locations.KtorExperimentalLocationsAPI import io.ktor.locations.Locations -import io.ktor.metrics.Metrics +{{/featureLocations}} import io.ktor.routing.Routing import java.util.concurrent.TimeUnit -import io.ktor.util.KtorExperimentalAPI {{#hasAuthMethods}} import io.ktor.auth.Authentication import io.ktor.auth.oauth +import io.ktor.metrics.dropwizard.DropwizardMetrics import org.openapitools.server.infrastructure.ApiKeyCredential import org.openapitools.server.infrastructure.ApiPrincipal import org.openapitools.server.infrastructure.apiKeyAuth @@ -44,23 +45,23 @@ import org.openapitools.server.infrastructure.apiKeyAuth {{#generateApis}}{{#apiInfo}}{{#apis}}import {{apiPackage}}.{{classname}} {{/apis}}{{/apiInfo}}{{/generateApis}} -@KtorExperimentalAPI internal val settings = HoconApplicationConfig(ConfigFactory.defaultApplication(HTTP::class.java.classLoader)) object HTTP { val client = HttpClient(Apache) } -@KtorExperimentalAPI +{{#featureLocations}} @KtorExperimentalLocationsAPI +{{/featureLocations}} fun Application.main() { install(DefaultHeaders) - install(Metrics) { + install(DropwizardMetrics) { val reporter = Slf4jReporter.forRegistry(registry) - .outputTo(log) - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .build() + .outputTo(log) + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .build() reporter.start(10, TimeUnit.SECONDS) } {{#generateApis}} @@ -82,7 +83,9 @@ fun Application.main() { {{#featureCompression}} install(Compression, ApplicationCompressionConfiguration()) // see http://ktor.io/features/compression.html {{/featureCompression}} + {{#featureLocations}} install(Locations) // see http://ktor.io/features/locations.html + {{/featureLocations}} {{#hasAuthMethods}} install(Authentication) { {{#authMethods}} @@ -117,8 +120,8 @@ fun Application.main() { client = HttpClient(Apache) providerLookup = { ApplicationAuthProviders["{{{name}}}"] } urlProvider = { _ -> - // TODO: define a callback url here. - "/" + // TODO: define a callback url here. + "/" } } {{/bodyAllowed}} @@ -138,8 +141,7 @@ fun Application.main() { {{/generateApis}} - environment.monitor.subscribe(ApplicationStopping) - { + environment.monitor.subscribe(ApplicationStopping) { HTTP.client.close() } } diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache index 3b568d21eba..a8956ec5905 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache @@ -8,11 +8,7 @@ import io.ktor.features.deflate import io.ktor.features.gzip import io.ktor.features.minimumSize import io.ktor.http.HttpMethod -import io.ktor.util.KtorExperimentalAPI -import java.time.Duration -import java.util.concurrent.Executors - -import {{packageName}}.settings +import java.util.concurrent.TimeUnit {{#featureCORS}} /** @@ -49,7 +45,7 @@ internal fun ApplicationCORSConfiguration(): CORS.Configuration.() -> Unit { */ internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit { return { - maxAge = Duration.ofDays(365) + maxAgeInSeconds = TimeUnit.DAYS.toSeconds(365) includeSubDomains = true preload = false @@ -82,7 +78,6 @@ internal fun ApplicationCompressionConfiguration(): Compression.Configuration.() {{/featureCompression}} // Defines authentication mechanisms used throughout the application. -@KtorExperimentalAPI val ApplicationAuthProviders: Map = listOf( {{#authMethods}} {{#isOAuth}} @@ -109,6 +104,3 @@ val ApplicationAuthProviders: Map = listOflibraries/ktor/_principal}} -if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) -} else { - {{#examples}} - {{#-first}} - {{#lambda.indented}}{{>_response}}{{/lambda.indented}} - {{/-first}} - {{/examples}} - {{^examples}} - call.respond(HttpStatusCode.NotImplemented) - {{/examples}} -} +{{#examples}} +{{#-first}} +{{#lambda.indented}}{{>_response}}{{/lambda.indented}} +{{/-first}} +{{/examples}} +{{^examples}} +call.respond(HttpStatusCode.NotImplemented) +{{/examples}} {{/hasAuthMethods}} {{^hasAuthMethods}} {{#examples}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_principal.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_principal.mustache index d49c5d537f0..09ae65906ea 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_principal.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_principal.mustache @@ -1,11 +1,11 @@ {{#authMethods}} {{#isBasic}} -val principal = call.authentication.principal() +val principal = call.authentication.principal()!! {{/isBasic}} {{#isApiKey}} -val principal = call.authentication.principal() +val principal = call.authentication.principal()!! {{/isApiKey}} {{#isOAuth}} -val principal = call.authentication.principal() +val principal = call.authentication.principal()!! {{/isOAuth}} {{/authMethods}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_response.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_response.mustache index fb26fb4a7f1..931dad98f5e 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_response.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_response.mustache @@ -1,7 +1,7 @@ val exampleContentType = "{{{contentType}}}" val exampleContentString = """{{&example}}""" -when(exampleContentType) { +when (exampleContentType) { "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache index 881e3b108ec..a3d8c124e81 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache @@ -10,17 +10,29 @@ import io.ktor.auth.OAuthAccessTokenResponse import io.ktor.auth.OAuthServerSettings import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.delete -import io.ktor.locations.get import io.ktor.response.respond import io.ktor.response.respondText import io.ktor.routing.Route +{{#featureLocations}} +import {{packageName}}.Paths +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.delete +import io.ktor.locations.get +import io.ktor.locations.post +import io.ktor.locations.put +import io.ktor.locations.options +import io.ktor.locations.head +{{/featureLocations}} +{{^featureLocations}} +import io.ktor.routing.delete +import io.ktor.routing.get import io.ktor.routing.post import io.ktor.routing.put +import io.ktor.routing.options +import io.ktor.routing.head import io.ktor.routing.route +{{/featureLocations}} -import {{packageName}}.Paths import {{packageName}}.infrastructure.ApiPrincipal @@ -28,34 +40,33 @@ import {{packageName}}.infrastructure.ApiPrincipal {{/imports}} {{#operations}} + {{#featureLocations}} @KtorExperimentalLocationsAPI + {{/featureLocations}} fun Route.{{classname}}() { val gson = Gson() val empty = mutableMapOf() {{#operation}} - {{#bodyAllowed}} - + {{#hasAuthMethods}} + {{#authMethods}} + authenticate("{{{name}}}") { + {{/authMethods}} + {{/hasAuthMethods}} + {{^featureLocations}} route("{{path}}") { - {{#hasAuthMethods}} - {{#authMethods}} - authenticate("{{{name}}}") { - {{/authMethods}} - {{/hasAuthMethods}} {{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}} { {{#lambda.indented_12}}{{>libraries/ktor/_api_body}}{{/lambda.indented_12}} } - {{#hasAuthMethods}} - } - {{/hasAuthMethods}} } - {{/bodyAllowed}} - {{^bodyAllowed}} - - {{! NOTE: Locations can be used on routes without body parameters.}} - {{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}} { _: Paths.{{operationId}} -> + {{/featureLocations}} + {{#featureLocations}} + {{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}} { {{#lambda.indented_8}}{{>libraries/ktor/_api_body}}{{/lambda.indented_8}} } - {{/bodyAllowed}} + {{/featureLocations}} + {{#hasAuthMethods}} + } + {{/hasAuthMethods}} {{/operation}} } diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache index 08c317ea666..173686fdf88 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache @@ -2,13 +2,13 @@ group '{{groupId}}' version '{{artifactVersion}}' wrapper { - gradleVersion = '4.9' + gradleVersion = '6.8.2' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.3.21' - ext.ktor_version = '1.1.3' + ext.kotlin_version = '1.4.31' + ext.ktor_version = '1.5.2' ext.shadow_version = '2.0.3' repositories { @@ -29,7 +29,7 @@ apply plugin: 'application' mainClassName = "io.ktor.server.netty.DevelopmentEngine" -// Initialization order with shadow 2.0.1 and Gradle 4.3 is weird. +// Initialization order with shadow 2.0.1 and Gradle 6.8.2 is weird. // See https://github.com/johnrengelman/shadow/issues/336#issuecomment-355402508 apply plugin: 'com.github.johnrengelman.shadow' @@ -59,7 +59,10 @@ dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" compile "io.ktor:ktor-server-netty:$ktor_version" compile "io.ktor:ktor-metrics:$ktor_version" + compile "io.ktor:ktor-auth:$ktor_version" +{{#featureLocations}} compile "io.ktor:ktor-locations:$ktor_version" +{{/featureLocations}} compile "io.ktor:ktor-gson:$ktor_version" compile "io.ktor:ktor-client-core:$ktor_version" compile "io.ktor:ktor-client-apache:$ktor_version" diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/licenseInfo.mustache index 3a547de74bb..d890606a94f 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/licenseInfo.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/licenseInfo.mustache @@ -1,11 +1,11 @@ /** -* {{{appName}}} -* {{{appDescription}}} -* -* {{#version}}The version of the OpenAPI document: {{{version}}}{{/version}} -* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}The version of the OpenAPI document: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. */ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache b/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache index 6e2cf517819..2d1a20a0190 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache @@ -22,3 +22,4 @@ typing >= 3.5.2.2 pyyaml < 5.3; python_version<="2.7" {{/supportPython2}} setuptools >= 21.0.0 +Flask == 1.1.2 diff --git a/modules/openapi-generator/src/main/resources/python-legacy/model.mustache b/modules/openapi-generator/src/main/resources/python-legacy/model.mustache index 5b4048915eb..236b8f8c3a2 100644 --- a/modules/openapi-generator/src/main/resources/python-legacy/model.mustache +++ b/modules/openapi-generator/src/main/resources/python-legacy/model.mustache @@ -2,7 +2,10 @@ {{>partial_header}} -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -203,7 +206,7 @@ class {{classname}}(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/modules/openapi-generator/src/main/resources/python/model.mustache b/modules/openapi-generator/src/main/resources/python/model.mustache index 680b60644c0..c8e1bfaa004 100644 --- a/modules/openapi-generator/src/main/resources/python/model.mustache +++ b/modules/openapi-generator/src/main/resources/python/model.mustache @@ -17,6 +17,9 @@ from {{packageName}}.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from {{packageName}}.exceptions import ApiAttributeError + {{#models}} {{#model}} {{#imports}} diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/invalid_pos_args.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/invalid_pos_args.mustache new file mode 100644 index 00000000000..143d50c8250 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/invalid_pos_args.mustache @@ -0,0 +1,9 @@ + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_composed.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_composed.mustache new file mode 100644 index 00000000000..81a4af3f822 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_composed.mustache @@ -0,0 +1,66 @@ + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """{{classname}} - a model defined in OpenAPI + + Keyword Args: +{{#requiredVars}} +{{#defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}} defaults to {{{defaultValue}}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501 +{{/defaultValue}} +{{^defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}{{/description}} +{{/defaultValue}} +{{/requiredVars}} +{{> model_templates/docstring_init_required_kwargs }} +{{#optionalVars}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}} # noqa: E501 +{{/optionalVars}} + """ + +{{#requiredVars}} +{{#defaultValue}} + {{name}} = kwargs.get('{{name}}', {{{defaultValue}}}) +{{/defaultValue}} +{{/requiredVars}} + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + +{{> model_templates/invalid_pos_args }} + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_normal.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_normal.mustache new file mode 100644 index 00000000000..3b82ba7fc3a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_normal.mustache @@ -0,0 +1,17 @@ +{{> model_templates/method_from_openapi_data_shared }} + +{{#isEnum}} + self.value = value +{{/isEnum}} +{{#requiredVars}} + self.{{name}} = {{name}} +{{/requiredVars}} + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_shared.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_shared.mustache new file mode 100644 index 00000000000..9dd84236b9f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_shared.mustache @@ -0,0 +1,49 @@ + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls{{#requiredVars}}{{^defaultValue}}, {{name}}{{/defaultValue}}{{/requiredVars}}, *args, **kwargs): # noqa: E501 + """{{classname}} - a model defined in OpenAPI + +{{#requiredVars}} +{{#-first}} + Args: +{{/-first}} +{{^defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}{{/description}} +{{/defaultValue}} +{{#-last}} + +{{/-last}} +{{/requiredVars}} + Keyword Args: +{{#requiredVars}} +{{#defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}} defaults to {{{defaultValue}}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501 +{{/defaultValue}} +{{/requiredVars}} +{{> model_templates/docstring_init_required_kwargs }} +{{#optionalVars}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}} # noqa: E501 +{{/optionalVars}} + """ + +{{#requiredVars}} +{{#defaultValue}} + {{name}} = kwargs.get('{{name}}', {{{defaultValue}}}) +{{/defaultValue}} +{{/requiredVars}} + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + +{{> model_templates/invalid_pos_args }} + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_simple.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_simple.mustache new file mode 100644 index 00000000000..0756046ede2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_simple.mustache @@ -0,0 +1,62 @@ + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """{{classname}} - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}}{{#defaultValue}} if omitted defaults to {{{defaultValue}}}{{/defaultValue}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501 + + Keyword Args: + value ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}}{{#defaultValue}} if omitted defaults to {{{defaultValue}}}{{/defaultValue}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501 +{{> model_templates/docstring_init_required_kwargs }} + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) +{{#defaultValue}} + else: + value = {{{defaultValue}}} +{{/defaultValue}} +{{^defaultValue}} + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) +{{/defaultValue}} + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + +{{> model_templates/invalid_pos_args }} + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_composed.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_composed.mustache index ca0505ead96..cc6f4b46bd7 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_composed.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_composed.mustache @@ -16,12 +16,14 @@ Keyword Args: {{#requiredVars}} +{{^isReadOnly}} {{#defaultValue}} {{name}} ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}} defaults to {{{defaultValue}}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501 {{/defaultValue}} {{^defaultValue}} {{name}} ({{{dataType}}}):{{#description}} {{{description}}}{{/description}} {{/defaultValue}} +{{/isReadOnly}} {{/requiredVars}} {{> model_templates/docstring_init_required_kwargs }} {{#optionalVars}} @@ -30,9 +32,11 @@ """ {{#requiredVars}} +{{^isReadOnly}} {{#defaultValue}} {{name}} = kwargs.get('{{name}}', {{{defaultValue}}}) {{/defaultValue}} +{{/isReadOnly}} {{/requiredVars}} _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) @@ -40,15 +44,7 @@ _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - if args: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) +{{> model_templates/invalid_pos_args }} self._data_store = {} self._check_type = _check_type @@ -78,4 +74,7 @@ self._additional_properties_model_instances: # discard variable. continue - setattr(self, var_name, var_value) \ No newline at end of file + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_normal.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_normal.mustache index e670b4ffb4c..bc5e7686f81 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_normal.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_normal.mustache @@ -13,7 +13,9 @@ self.value = value {{/isEnum}} {{#requiredVars}} +{{^isReadOnly}} self.{{name}} = {{name}} +{{/isReadOnly}} {{/requiredVars}} for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ @@ -22,4 +24,7 @@ self.additional_properties_type is None: # discard variable. continue - setattr(self, var_name, var_value) \ No newline at end of file + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_shared.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_shared.mustache index a766c14bac0..0eb4de6a13e 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_shared.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_shared.mustache @@ -1,8 +1,9 @@ @convert_js_args_to_python_args - def __init__(self{{#requiredVars}}{{^defaultValue}}, {{name}}{{/defaultValue}}{{/requiredVars}}, *args, **kwargs): # noqa: E501 + def __init__(self{{#requiredVars}}{{^isReadOnly}}{{^defaultValue}}, {{name}}{{/defaultValue}}{{/isReadOnly}}{{/requiredVars}}, *args, **kwargs): # noqa: E501 """{{classname}} - a model defined in OpenAPI {{#requiredVars}} +{{^isReadOnly}} {{#-first}} Args: {{/-first}} @@ -12,12 +13,15 @@ {{#-last}} {{/-last}} +{{/isReadOnly}} {{/requiredVars}} Keyword Args: {{#requiredVars}} +{{^isReadOnly}} {{#defaultValue}} {{name}} ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}} defaults to {{{defaultValue}}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501 {{/defaultValue}} +{{/isReadOnly}} {{/requiredVars}} {{> model_templates/docstring_init_required_kwargs }} {{#optionalVars}} @@ -26,9 +30,11 @@ """ {{#requiredVars}} +{{^isReadOnly}} {{#defaultValue}} {{name}} = kwargs.get('{{name}}', {{{defaultValue}}}) {{/defaultValue}} +{{/isReadOnly}} {{/requiredVars}} _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) @@ -36,15 +42,7 @@ _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - if args: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) +{{> model_templates/invalid_pos_args }} self._data_store = {} self._check_type = _check_type diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_simple.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_simple.mustache index 9e06a6a22ed..c6950a7d364 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_simple.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_simple.mustache @@ -46,15 +46,7 @@ _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - if args: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) +{{> model_templates/invalid_pos_args }} self._data_store = {} self._check_type = _check_type diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/model_composed.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/model_composed.mustache index 76fe3a8f507..9a5ab0f66b6 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/model_composed.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/model_composed.mustache @@ -24,6 +24,21 @@ class {{classname}}(ModelComposed): {{/optionalVars}} } + read_only_vars = { +{{#requiredVars}} +{{#isReadOnly}} + '{{name}}', # noqa: E501 +{{/isReadOnly}} +{{/requiredVars}} +{{#optionalVars}} +{{#isReadOnly}} + '{{name}}', # noqa: E501 +{{/isReadOnly}} +{{/optionalVars}} + } + +{{> model_templates/method_from_openapi_data_composed }} + {{> model_templates/method_init_composed }} @cached_property diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/model_normal.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/model_normal.mustache index 9aada8f5a08..513aa01e66e 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/model_normal.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/model_normal.mustache @@ -24,6 +24,21 @@ class {{classname}}(ModelNormal): {{/optionalVars}} } + read_only_vars = { +{{#requiredVars}} +{{#isReadOnly}} + '{{name}}', # noqa: E501 +{{/isReadOnly}} +{{/requiredVars}} +{{#optionalVars}} +{{#isReadOnly}} + '{{name}}', # noqa: E501 +{{/isReadOnly}} +{{/optionalVars}} + } + _composed_schemas = {} +{{> model_templates/method_from_openapi_data_normal}} + {{> model_templates/method_init_normal}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/model_simple.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/model_simple.mustache index a4055af756b..1a41a9cf7e2 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/model_simple.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/model_simple.mustache @@ -13,6 +13,10 @@ class {{classname}}(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None -{{> model_templates/method_init_simple}} \ No newline at end of file +{{> model_templates/method_init_simple}} + +{{> model_templates/method_from_openapi_data_simple}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_utils.mustache b/modules/openapi-generator/src/main/resources/python/model_utils.mustache index 3621a5eec51..73e6e7d555b 100644 --- a/modules/openapi-generator/src/main/resources/python/model_utils.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_utils.mustache @@ -21,6 +21,22 @@ none_type = type(None) file_type = io.IOBase +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + class cached_property(object): # this caches the result of the function call for fn with no inputs # use this as a decorator on fuction methods that you want converted @@ -212,6 +228,121 @@ class OpenApiModel(object): return new_inst + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + class ModelSimple(OpenApiModel): """the parent class of models whose type != object in their swagger/openapi""" @@ -911,14 +1042,14 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, _spec_property_naming=spec_property_naming) if issubclass(model_class, ModelSimple): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) elif isinstance(model_data, list): - return model_class(*model_data, **kw_args) + return model_class._new_from_openapi_data(*model_data, **kw_args) if isinstance(model_data, dict): kw_args.update(model_data) - return model_class(**kw_args) + return model_class._new_from_openapi_data(**kw_args) elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) def deserialize_file(response_data, configuration, content_disposition=None): @@ -1280,22 +1411,6 @@ def get_valid_classes_phrase(input_classes): return "is one of [{0}]".format(", ".join(all_class_names)) -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python(kwargs, _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - def get_allof_instances(self, model_args, constant_args): """ Args: diff --git a/modules/openapi-generator/src/main/resources/scala-akka-client/apiInvoker.mustache b/modules/openapi-generator/src/main/resources/scala-akka-client/apiInvoker.mustache index 8c81b0b2d8b..a82135170c4 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-client/apiInvoker.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-client/apiInvoker.mustache @@ -18,6 +18,7 @@ import de.heikoseeberger.akkahttpjson4s.Json4sSupport import org.json4s._ import org.json4s.jackson.JsonMethods._ import org.json4s.jackson.Serialization +import scala.collection.compat._ import scala.collection.immutable import scala.concurrent.{ ExecutionContext, ExecutionContextExecutor, Future } @@ -86,7 +87,7 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC private val http = Http() - val CompressionFilter: HttpMessage ⇒ Boolean = (msg: HttpMessage) => + val CompressionFilter: HttpMessage => Boolean = (msg: HttpMessage) => Seq( { _: HttpMessage => settings.compressionEnabled }, Encoder.DefaultFilter, @@ -115,7 +116,7 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC private def headers(headers: Map[String, Any]): immutable.Seq[HttpHeader] = headers.asFormattedParams .map { case (name, value) => RawHeader(name, value.toString) } - .to[immutable.Seq] + .to(immutable.Seq) private def bodyPart(name: String, value: Any): BodyPart = { @@ -147,9 +148,9 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC case MediaTypes.`multipart/form-data` => Multipart.FormData(Source(params.toList.map { case (name, value) => bodyPart(name, value) })) case MediaTypes.`application/x-www-form-urlencoded` => - FormData(params.mapValues(_.toString)) + FormData(params.view.mapValues(_.toString).toMap) case _: MediaType => // Default : application/x-www-form-urlencoded. - FormData(params.mapValues(_.toString)) + FormData(params.view.mapValues(_.toString).toMap) } ) } @@ -187,7 +188,9 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC params + (keyName -> key.value) case (params, _) => params }.asFormattedParams + .view .mapValues(_.toString) + .toMap .foldRight[Query](Uri.Query.Empty) { case ((name, value), acc) => acc.+:(name, value) } @@ -196,7 +199,9 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC def makeUri(r: ApiRequest[_]): Uri = { val opPath = r.operationPath.replaceAll("\\{format\\}", "json") val opPathWithParams = r.pathParams.asFormattedParams + .view .mapValues(_.toString) + .toMap .foldLeft(opPath) { case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value) } @@ -213,13 +218,13 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC http .singleRequest(request) .map { response => - val decoder: Coder with StreamDecoder = response.encoding match { - case HttpEncodings.gzip ⇒ - Gzip - case HttpEncodings.deflate ⇒ - Deflate - case HttpEncodings.identity ⇒ - NoCoding + val decoder: Decoder with Decoder = response.encoding match { + case HttpEncodings.gzip => + Coders.Gzip + case HttpEncodings.deflate => + Coders.Deflate + case HttpEncodings.identity => + Coders.NoCoding case HttpEncoding(encoding) => throw new IllegalArgumentException(s"Unsupported encoding: $encoding") } @@ -247,13 +252,13 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC request .responseForCode(response.status.intValue) match { case Some((Manifest.Unit, state: ResponseState)) => - Future(responseForState(state, Unit).asInstanceOf[ApiResponse[T]]) + Future(responseForState(state, ()).asInstanceOf[ApiResponse[T]]) case Some((manifest, state: ResponseState)) if manifest == mf => implicit val m: Unmarshaller[HttpEntity, T] = unmarshaller[T](mf, serialization, formats) Unmarshal(response.entity) .to[T] .recoverWith { - case e ⇒ throw ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), e) + case e => throw ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), e) } .map(value => responseForState(state, value)) case None | Some(_) => diff --git a/modules/openapi-generator/src/main/resources/scala-akka-client/apiSettings.mustache b/modules/openapi-generator/src/main/resources/scala-akka-client/apiSettings.mustache index d5856ccc17d..22f56080b01 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-client/apiSettings.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-client/apiSettings.mustache @@ -3,12 +3,12 @@ package {{invokerPackage}} import java.util.concurrent.TimeUnit -import akka.actor.{ ExtendedActorSystem, Extension, ExtensionKey } +import akka.actor.{ActorSystem, ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider} import akka.http.scaladsl.model.StatusCodes.CustomStatusCode import akka.http.scaladsl.model.headers.RawHeader import com.typesafe.config.Config -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.concurrent.duration.FiniteDuration class ApiSettings(config: Config) extends Extension { @@ -32,4 +32,13 @@ class ApiSettings(config: Config) extends Extension { } } -object ApiSettings extends ExtensionKey[ApiSettings] +object ApiSettings extends ExtensionId[ApiSettings] with ExtensionIdProvider { + + override def lookup = ApiSettings + + override def createExtension(system: ExtendedActorSystem): ApiSettings = + new ApiSettings(system) + + // needed to get the type right when used from Java + override def get(system: ActorSystem): ApiSettings = super.get(system) +} diff --git a/modules/openapi-generator/src/main/resources/scala-akka-client/build.sbt.mustache b/modules/openapi-generator/src/main/resources/scala-akka-client/build.sbt.mustache index c26dae841c7..e4c21c19d0c 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-client/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-client/build.sbt.mustache @@ -1,22 +1,26 @@ version := "{{artifactVersion}}" name := "{{artifactId}}" organization := "{{groupId}}" -scalaVersion := "2.12.8" + +scalaVersion := "2.12.13" +crossScalaVersions := Seq(scalaVersion.value, "2.13.4") + libraryDependencies ++= Seq( - "com.typesafe" % "config" % "1.3.3", - "com.typesafe.akka" %% "akka-actor" % "2.5.21", - "com.typesafe.akka" %% "akka-stream" % "2.5.21", - "com.typesafe.akka" %% "akka-http" % "10.1.7", + "com.typesafe" % "config" % "1.4.1", + "com.typesafe.akka" %% "akka-actor" % "2.6.12", + "com.typesafe.akka" %% "akka-stream" % "2.6.12", + "com.typesafe.akka" %% "akka-http" % "10.2.3", {{#joda}} "joda-time" % "joda-time" % "2.10.1", {{/joda}} - "org.json4s" %% "json4s-jackson" % "3.6.5", - "org.json4s" %% "json4s-ext" % "3.6.5", - "de.heikoseeberger" %% "akka-http-json4s" % "1.25.2", + "org.json4s" %% "json4s-jackson" % "3.6.7", + "org.json4s" %% "json4s-ext" % "3.6.7", + "de.heikoseeberger" %% "akka-http-json4s" % "1.27.0", + "org.scala-lang.modules" %% "scala-collection-compat" % "2.4.1", // test dependencies - "org.scalatest" %% "scalatest" % "3.0.5" % "test", - "junit" % "junit" % "4.13.1" % "test" + "org.scalatest" %% "scalatest" % "3.2.3" % "test", + "org.scalatestplus" %% "junit-4-13" % "3.2.3.0" % "test" ) resolvers ++= Seq(Resolver.mavenLocal) diff --git a/modules/openapi-generator/src/main/resources/scala-akka-client/pom.mustache b/modules/openapi-generator/src/main/resources/scala-akka-client/pom.mustache index 78cbec12128..e82df0c17b9 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-client/pom.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-client/pom.mustache @@ -15,18 +15,19 @@ UTF-8 1.8 - 2.12.8 - 3.5.3 - 3.2.11 - 2.5.21 - 10.1.7 + 2.12.13 + 3.6.7 + 3.6.7 + 2.6.12 + 10.2.3 {{#joda}} 2.10.1 {{/joda}} - 1.3.3 - 1.25.2 - 4.13.1 - 3.0.5 + 1.4.1 + 1.27.0 + 2.4.1 + 3.2.3 + 3.2.3.0 3.3.1 @@ -80,6 +81,11 @@ akka-http-json4s_2.12 ${akka.http.json4s.version} + + org.scala-lang.modules + scala-collection-compat_2.12 + ${scala.compat.version} + @@ -89,9 +95,9 @@ test - junit - junit - ${junit.version} + org.scalatestplus + junit-4-13_2.12 + ${scala.test.plus.version} test diff --git a/modules/openapi-generator/src/main/resources/scala-akka-client/project/build.properties.mustache b/modules/openapi-generator/src/main/resources/scala-akka-client/project/build.properties.mustache new file mode 100644 index 00000000000..dc07aed85e0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-akka-client/project/build.properties.mustache @@ -0,0 +1 @@ +sbt.version=1.3.10 \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache index fa99fc62475..28cf170922d 100644 --- a/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache +++ b/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache @@ -30,7 +30,7 @@ class {{classname}}(baseUrl: String) { .header("{{keyParamName}}", apiKey){{/isKeyInHeader}}{{#isKeyInCookie}} .cookie("{{keyParamName}}", apiKey){{/isKeyInCookie}}{{/isApiKey}}{{/authMethods}}{{#formParams.0}}{{^isMultipart}} .body(Map({{#formParams}} - {{>paramFormCreation}}{{^-last}}, {{/-last}}{{/formParams}} + {{>paramFormCreation}}{{^-last}},{{/-last}}{{/formParams}} )){{/isMultipart}}{{#isMultipart}} .multipartBody(Seq({{#formParams}} {{>paramMultipartCreation}}{{^-last}}, {{/-last}}{{/formParams}} diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/build.sbt.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/build.sbt.mustache index a20ba532f44..3072a54368c 100644 --- a/modules/openapi-generator/src/main/resources/scala-sttp/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/scala-sttp/build.sbt.mustache @@ -2,8 +2,8 @@ version := "{{artifactVersion}}" name := "{{artifactId}}" organization := "{{groupId}}" -scalaVersion := "2.13.2" -crossScalaVersions := Seq(scalaVersion.value, "2.12.10") +scalaVersion := "2.13.5" +crossScalaVersions := Seq(scalaVersion.value, "2.12.13") libraryDependencies ++= Seq( "com.softwaremill.sttp.client" %% "core" % "{{sttpClientVersion}}", diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/project/build.properties.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/project/build.properties.mustache index 654fe70c42c..e67343ae796 100644 --- a/modules/openapi-generator/src/main/resources/scala-sttp/project/build.properties.mustache +++ b/modules/openapi-generator/src/main/resources/scala-sttp/project/build.properties.mustache @@ -1 +1 @@ -sbt.version=1.3.12 +sbt.version=1.5.0 diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache index 00d4e010fa0..3036e366290 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache @@ -109,7 +109,7 @@ export function {{classname}}ToJSON(value?: {{classname}} | null): any { {{^isPrimitiveType}} {{#isArray}} {{#uniqueItems}} - '{{baseName}}': {{^required}}value.{{name}} === undefined ? undefined : {{/required}}({{#isNullable}}value.{{name}} === null ? null : {{/isNullable}}Array.from((value.{{name}} as Set).map({{#items}}{{datatype}}{{/items}}ToJSON))), + '{{baseName}}': {{^required}}value.{{name}} === undefined ? undefined : {{/required}}({{#isNullable}}value.{{name}} === null ? null : {{/isNullable}}Array.from(value.{{name}} as Set).map({{#items}}{{datatype}}{{/items}}ToJSON)), {{/uniqueItems}} {{^uniqueItems}} '{{baseName}}': {{^required}}value.{{name}} === undefined ? undefined : {{/required}}({{#isNullable}}value.{{name}} === null ? null : {{/isNullable}}(value.{{name}} as Array).map({{#items}}{{datatype}}{{/items}}ToJSON)), diff --git a/modules/openapi-generator/src/main/resources/typescript/api/api.mustache b/modules/openapi-generator/src/main/resources/typescript/api/api.mustache index 95cb62e631f..1d36944043b 100644 --- a/modules/openapi-generator/src/main/resources/typescript/api/api.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/api/api.mustache @@ -39,8 +39,8 @@ export class {{classname}}RequestFactory extends BaseAPIRequestFactory { * @param {{paramName}} {{description}} {{/allParams}} */ - public async {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: Configuration): Promise { - let config = options || this.configuration; + public async {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}_options?: Configuration): Promise { + let _config = _options || this.configuration; {{#allParams}} {{#required}} @@ -57,7 +57,7 @@ export class {{classname}}RequestFactory extends BaseAPIRequestFactory { .replace('{' + '{{baseName}}' + '}', encodeURIComponent(String({{paramName}}))){{/pathParams}}; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.{{httpMethod}}); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.{{httpMethod}}); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -132,7 +132,7 @@ export class {{classname}}RequestFactory extends BaseAPIRequestFactory { {{/hasAuthMethods}} // Apply auth methods {{#authMethods}} - authMethod = config.authMethods["{{name}}"] + authMethod = _config.authMethods["{{name}}"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/modules/openapi-generator/src/main/resources/typescript/types/ObservableAPI.mustache b/modules/openapi-generator/src/main/resources/typescript/types/ObservableAPI.mustache index b001eba36b4..da871ce94dd 100644 --- a/modules/openapi-generator/src/main/resources/typescript/types/ObservableAPI.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/types/ObservableAPI.mustache @@ -62,8 +62,8 @@ export class Observable{{classname}} { * @param {{paramName}} {{description}} {{/allParams}} */ - public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: Configuration): Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> { - const requestContextPromise = this.requestFactory.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options); + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}_options?: Configuration): Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> { + const requestContextPromise = this.requestFactory.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); diff --git a/modules/openapi-generator/src/main/resources/typescript/types/PromiseAPI.mustache b/modules/openapi-generator/src/main/resources/typescript/types/PromiseAPI.mustache index 4014dec1e06..9d74dd2a746 100644 --- a/modules/openapi-generator/src/main/resources/typescript/types/PromiseAPI.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/types/PromiseAPI.mustache @@ -52,8 +52,8 @@ export class Promise{{classname}} { * @param {{paramName}} {{description}} {{/allParams}} */ - public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: Configuration): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> { - const result = this.api.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options); + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}_options?: Configuration): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> { + const result = this.api.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}_options); return result.toPromise(); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinModelCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinModelCodegenTest.java index 6885057c1c0..19829496e23 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinModelCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinModelCodegenTest.java @@ -9,6 +9,7 @@ import org.openapitools.codegen.DefaultGenerator; import org.openapitools.codegen.languages.AbstractKotlinCodegen; import org.openapitools.codegen.languages.KotlinClientCodegen; import org.openapitools.codegen.languages.KotlinServerCodegen; +import org.openapitools.codegen.languages.KotlinServerDeprecatedCodegen; import org.openapitools.codegen.languages.KotlinSpringServerCodegen; import org.openapitools.codegen.languages.KotlinVertxServerCodegen; import org.testng.annotations.DataProvider; @@ -28,6 +29,7 @@ public class KotlinModelCodegenTest { return new Object[][]{ {new KotlinClientCodegen()}, {new KotlinServerCodegen()}, + {new KotlinServerDeprecatedCodegen()}, {new KotlinSpringServerCodegen()}, {new KotlinVertxServerCodegen()}, }; diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/scala/SttpCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/scala/SttpCodegenTest.java new file mode 100644 index 00000000000..a48225430f0 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/scala/SttpCodegenTest.java @@ -0,0 +1,20 @@ +package org.openapitools.codegen.scala; + +import org.openapitools.codegen.languages.ScalaSttpClientCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class SttpCodegenTest { + + private final ScalaSttpClientCodegen codegen = new ScalaSttpClientCodegen(); + + @Test + public void encodePath() { + Assert.assertEquals(codegen.encodePath("{user_name}"), "${userName}"); + Assert.assertEquals(codegen.encodePath("{userName}"), "${userName}"); + Assert.assertEquals(codegen.encodePath("{UserName}"), "${userName}"); + Assert.assertEquals(codegen.encodePath("user_name"), "user_name"); + Assert.assertEquals(codegen.encodePath("before/{UserName}/after"), "before/${userName}/after"); + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/scalaakka/ScalaAkkaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/scalaakka/ScalaAkkaClientCodegenTest.java index d78b487d286..4304e092bb1 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/scalaakka/ScalaAkkaClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/scalaakka/ScalaAkkaClientCodegenTest.java @@ -472,7 +472,7 @@ public class ScalaAkkaClientCodegenTest { Generator gen = generator.opts(clientOptInput); List files = gen.generate(); - Assert.assertEquals(files.size(), 15); + Assert.assertEquals(files.size(), 16); TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/model/SomeObj.scala"); TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/core/ApiSettings.scala"); @@ -509,7 +509,7 @@ public class ScalaAkkaClientCodegenTest { Generator gen = generator.opts(clientOptInput); List files = gen.generate(); - Assert.assertEquals(files.size(), 15); + Assert.assertEquals(files.size(), 16); TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/model/package/SomeObj.scala"); TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/package/invoker/ApiSettings.scala"); diff --git a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index 27b97c89d8c..683641e5a86 100644 --- a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -2422,3 +2422,26 @@ components: items: type: string nullable: true + Mole: + type: object + required: + - blind + - smell + - hearing + properties: + blind: + type: boolean + readOnly: true + smell: + type: string + readOnly: false + touch: + type: boolean + readOnly: true + taste: + type: string + readOnly: false + hearing: + type: boolean + seeingGhosts: + type: boolean \ No newline at end of file diff --git a/new.sh b/new.sh index 12cfec8cb57..7d33be840e5 100755 --- a/new.sh +++ b/new.sh @@ -178,7 +178,7 @@ public class ${lang_classname} extends DefaultCodegen implements CodegenConfig { outputFolder = "generated-code" + File.separator + "${gen_name_camel}"; modelTemplateFiles.put("model.mustache", ".zz"); apiTemplateFiles.put("api.mustache", ".zz"); - embeddedTemplateDir = templateDir = "${gen_name_camel}-${gen_type}"; + embeddedTemplateDir = templateDir = "${gen_name_camel}"; apiPackage = "Apis"; modelPackage = "Models"; supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); @@ -191,17 +191,17 @@ EOF echo -e "\norg.openapitools.codegen.languages.${lang_classname}" >> "${root}/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig" # Step 3: Create resource files -mkdir -p "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}" -echo "Creating modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}/README.mustache" && \ - touch "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}/README.mustache" -echo "Creating modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}/model.mustache" && \ - touch "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}/model.mustache" -echo "Creating modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}/api.mustache" && \ - touch "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}/api.mustache" +mkdir -p "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}" +echo "Creating modules/openapi-generator/src/main/resources/${gen_name_camel}/README.mustache" && \ + touch "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}/README.mustache" +echo "Creating modules/openapi-generator/src/main/resources/${gen_name_camel}/model.mustache" && \ + touch "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}/model.mustache" +echo "Creating modules/openapi-generator/src/main/resources/${gen_name_camel}/api.mustache" && \ + touch "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}/api.mustache" # Step 4: Create generation config scripts -echo "Creating bin/configs/${gen_name_camel}-${gen_type}-petstore-new.yaml" -cat > "${root}/bin/configs/${gen_name_camel}-${gen_type}-petstore-new.yaml"< "${root}/bin/configs/${gen_name_camel}-petstore-new.yaml"<ProcessRequest(); }); -} - } diff --git a/samples/client/petstore/cpp-ue4/Private/OpenAPIPetApi.cpp b/samples/client/petstore/cpp-ue4/Private/OpenAPIPetApi.cpp index 68a0d933aca..72d2c58ea6e 100644 --- a/samples/client/petstore/cpp-ue4/Private/OpenAPIPetApi.cpp +++ b/samples/client/petstore/cpp-ue4/Private/OpenAPIPetApi.cpp @@ -54,6 +54,40 @@ bool OpenAPIPetApi::IsValid() const return true; } +void OpenAPIPetApi::SetHttpRetryManager(FHttpRetrySystem::FManager& InRetryManager) +{ + if(RetryManager != &GetHttpRetryManager()) + { + DefaultRetryManager.Reset(); + RetryManager = &InRetryManager; + } +} + +FHttpRetrySystem::FManager& OpenAPIPetApi::GetHttpRetryManager() +{ + return *RetryManager; +} + +FHttpRequestRef OpenAPIPetApi::CreateHttpRequest(const Request& Request) const +{ + if (!Request.GetRetryParams().IsSet()) + { + return FHttpModule::Get().CreateRequest(); + } + else + { + if (!RetryManager) + { + // Create default retry manager if none was specified + DefaultRetryManager = MakeUnique(6, 60); + RetryManager = DefaultRetryManager.Get(); + } + + const HttpRetryParams& Params = Request.GetRetryParams().GetValue(); + return RetryManager->CreateRequest(Params.RetryLimitCountOverride, Params.RetryTimeoutRelativeSecondsOverride, Params.RetryResponseCodes, Params.RetryVerbs, Params.RetryDomains); + } +} + void OpenAPIPetApi::HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const { InOutResponse.SetHttpResponse(HttpResponse); @@ -103,7 +137,7 @@ bool OpenAPIPetApi::AddPet(const AddPetRequest& Request, const FAddPetDelegate& if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -113,26 +147,15 @@ bool OpenAPIPetApi::AddPet(const AddPetRequest& Request, const FAddPetDelegate& Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnAddPetResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnAddPetResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnAddPetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddPetDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnAddPetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddPetDelegate Delegate) const { AddPetResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnAddPetResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::DeletePet(const DeletePetRequest& Request, const FDeletePetDelegate& Delegate /*= FDeletePetDelegate()*/) const @@ -140,7 +163,7 @@ bool OpenAPIPetApi::DeletePet(const DeletePetRequest& Request, const FDeletePetD if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -150,26 +173,15 @@ bool OpenAPIPetApi::DeletePet(const DeletePetRequest& Request, const FDeletePetD Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnDeletePetResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnDeletePetResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnDeletePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeletePetDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnDeletePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeletePetDelegate Delegate) const { DeletePetResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnDeletePetResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::FindPetsByStatus(const FindPetsByStatusRequest& Request, const FFindPetsByStatusDelegate& Delegate /*= FFindPetsByStatusDelegate()*/) const @@ -177,7 +189,7 @@ bool OpenAPIPetApi::FindPetsByStatus(const FindPetsByStatusRequest& Request, con if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -187,26 +199,15 @@ bool OpenAPIPetApi::FindPetsByStatus(const FindPetsByStatusRequest& Request, con Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByStatusResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByStatusResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnFindPetsByStatusResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByStatusDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnFindPetsByStatusResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByStatusDelegate Delegate) const { FindPetsByStatusResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByStatusResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::FindPetsByTags(const FindPetsByTagsRequest& Request, const FFindPetsByTagsDelegate& Delegate /*= FFindPetsByTagsDelegate()*/) const @@ -214,7 +215,7 @@ bool OpenAPIPetApi::FindPetsByTags(const FindPetsByTagsRequest& Request, const F if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -224,26 +225,15 @@ bool OpenAPIPetApi::FindPetsByTags(const FindPetsByTagsRequest& Request, const F Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByTagsResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByTagsResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnFindPetsByTagsResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByTagsDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnFindPetsByTagsResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByTagsDelegate Delegate) const { FindPetsByTagsResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByTagsResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::GetPetById(const GetPetByIdRequest& Request, const FGetPetByIdDelegate& Delegate /*= FGetPetByIdDelegate()*/) const @@ -251,7 +241,7 @@ bool OpenAPIPetApi::GetPetById(const GetPetByIdRequest& Request, const FGetPetBy if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -261,26 +251,15 @@ bool OpenAPIPetApi::GetPetById(const GetPetByIdRequest& Request, const FGetPetBy Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnGetPetByIdResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnGetPetByIdResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnGetPetByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPetByIdDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnGetPetByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPetByIdDelegate Delegate) const { GetPetByIdResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnGetPetByIdResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::UpdatePet(const UpdatePetRequest& Request, const FUpdatePetDelegate& Delegate /*= FUpdatePetDelegate()*/) const @@ -288,7 +267,7 @@ bool OpenAPIPetApi::UpdatePet(const UpdatePetRequest& Request, const FUpdatePetD if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -298,26 +277,15 @@ bool OpenAPIPetApi::UpdatePet(const UpdatePetRequest& Request, const FUpdatePetD Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnUpdatePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnUpdatePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetDelegate Delegate) const { UpdatePetResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::UpdatePetWithForm(const UpdatePetWithFormRequest& Request, const FUpdatePetWithFormDelegate& Delegate /*= FUpdatePetWithFormDelegate()*/) const @@ -325,7 +293,7 @@ bool OpenAPIPetApi::UpdatePetWithForm(const UpdatePetWithFormRequest& Request, c if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -335,26 +303,15 @@ bool OpenAPIPetApi::UpdatePetWithForm(const UpdatePetWithFormRequest& Request, c Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetWithFormResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetWithFormResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnUpdatePetWithFormResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetWithFormDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnUpdatePetWithFormResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetWithFormDelegate Delegate) const { UpdatePetWithFormResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetWithFormResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::UploadFile(const UploadFileRequest& Request, const FUploadFileDelegate& Delegate /*= FUploadFileDelegate()*/) const @@ -362,7 +319,7 @@ bool OpenAPIPetApi::UploadFile(const UploadFileRequest& Request, const FUploadFi if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -372,26 +329,15 @@ bool OpenAPIPetApi::UploadFile(const UploadFileRequest& Request, const FUploadFi Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUploadFileResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUploadFileResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnUploadFileResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUploadFileDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnUploadFileResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUploadFileDelegate Delegate) const { UploadFileResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUploadFileResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } } diff --git a/samples/client/petstore/cpp-ue4/Private/OpenAPIStoreApi.cpp b/samples/client/petstore/cpp-ue4/Private/OpenAPIStoreApi.cpp index 32000a95907..ed25814006e 100644 --- a/samples/client/petstore/cpp-ue4/Private/OpenAPIStoreApi.cpp +++ b/samples/client/petstore/cpp-ue4/Private/OpenAPIStoreApi.cpp @@ -54,6 +54,40 @@ bool OpenAPIStoreApi::IsValid() const return true; } +void OpenAPIStoreApi::SetHttpRetryManager(FHttpRetrySystem::FManager& InRetryManager) +{ + if(RetryManager != &GetHttpRetryManager()) + { + DefaultRetryManager.Reset(); + RetryManager = &InRetryManager; + } +} + +FHttpRetrySystem::FManager& OpenAPIStoreApi::GetHttpRetryManager() +{ + return *RetryManager; +} + +FHttpRequestRef OpenAPIStoreApi::CreateHttpRequest(const Request& Request) const +{ + if (!Request.GetRetryParams().IsSet()) + { + return FHttpModule::Get().CreateRequest(); + } + else + { + if (!RetryManager) + { + // Create default retry manager if none was specified + DefaultRetryManager = MakeUnique(6, 60); + RetryManager = DefaultRetryManager.Get(); + } + + const HttpRetryParams& Params = Request.GetRetryParams().GetValue(); + return RetryManager->CreateRequest(Params.RetryLimitCountOverride, Params.RetryTimeoutRelativeSecondsOverride, Params.RetryResponseCodes, Params.RetryVerbs, Params.RetryDomains); + } +} + void OpenAPIStoreApi::HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const { InOutResponse.SetHttpResponse(HttpResponse); @@ -103,7 +137,7 @@ bool OpenAPIStoreApi::DeleteOrder(const DeleteOrderRequest& Request, const FDele if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -113,26 +147,15 @@ bool OpenAPIStoreApi::DeleteOrder(const DeleteOrderRequest& Request, const FDele Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnDeleteOrderResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnDeleteOrderResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIStoreApi::OnDeleteOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteOrderDelegate Delegate, int AutoRetryCount) const +void OpenAPIStoreApi::OnDeleteOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteOrderDelegate Delegate) const { DeleteOrderResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnDeleteOrderResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIStoreApi::GetInventory(const GetInventoryRequest& Request, const FGetInventoryDelegate& Delegate /*= FGetInventoryDelegate()*/) const @@ -140,7 +163,7 @@ bool OpenAPIStoreApi::GetInventory(const GetInventoryRequest& Request, const FGe if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -150,26 +173,15 @@ bool OpenAPIStoreApi::GetInventory(const GetInventoryRequest& Request, const FGe Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnGetInventoryResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnGetInventoryResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIStoreApi::OnGetInventoryResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetInventoryDelegate Delegate, int AutoRetryCount) const +void OpenAPIStoreApi::OnGetInventoryResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetInventoryDelegate Delegate) const { GetInventoryResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnGetInventoryResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIStoreApi::GetOrderById(const GetOrderByIdRequest& Request, const FGetOrderByIdDelegate& Delegate /*= FGetOrderByIdDelegate()*/) const @@ -177,7 +189,7 @@ bool OpenAPIStoreApi::GetOrderById(const GetOrderByIdRequest& Request, const FGe if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -187,26 +199,15 @@ bool OpenAPIStoreApi::GetOrderById(const GetOrderByIdRequest& Request, const FGe Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnGetOrderByIdResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnGetOrderByIdResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIStoreApi::OnGetOrderByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetOrderByIdDelegate Delegate, int AutoRetryCount) const +void OpenAPIStoreApi::OnGetOrderByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetOrderByIdDelegate Delegate) const { GetOrderByIdResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnGetOrderByIdResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIStoreApi::PlaceOrder(const PlaceOrderRequest& Request, const FPlaceOrderDelegate& Delegate /*= FPlaceOrderDelegate()*/) const @@ -214,7 +215,7 @@ bool OpenAPIStoreApi::PlaceOrder(const PlaceOrderRequest& Request, const FPlaceO if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -224,26 +225,15 @@ bool OpenAPIStoreApi::PlaceOrder(const PlaceOrderRequest& Request, const FPlaceO Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnPlaceOrderResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnPlaceOrderResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIStoreApi::OnPlaceOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FPlaceOrderDelegate Delegate, int AutoRetryCount) const +void OpenAPIStoreApi::OnPlaceOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FPlaceOrderDelegate Delegate) const { PlaceOrderResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnPlaceOrderResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } } diff --git a/samples/client/petstore/cpp-ue4/Private/OpenAPIUserApi.cpp b/samples/client/petstore/cpp-ue4/Private/OpenAPIUserApi.cpp index 9fdd937b3b9..8f38a6358f4 100644 --- a/samples/client/petstore/cpp-ue4/Private/OpenAPIUserApi.cpp +++ b/samples/client/petstore/cpp-ue4/Private/OpenAPIUserApi.cpp @@ -54,6 +54,40 @@ bool OpenAPIUserApi::IsValid() const return true; } +void OpenAPIUserApi::SetHttpRetryManager(FHttpRetrySystem::FManager& InRetryManager) +{ + if(RetryManager != &GetHttpRetryManager()) + { + DefaultRetryManager.Reset(); + RetryManager = &InRetryManager; + } +} + +FHttpRetrySystem::FManager& OpenAPIUserApi::GetHttpRetryManager() +{ + return *RetryManager; +} + +FHttpRequestRef OpenAPIUserApi::CreateHttpRequest(const Request& Request) const +{ + if (!Request.GetRetryParams().IsSet()) + { + return FHttpModule::Get().CreateRequest(); + } + else + { + if (!RetryManager) + { + // Create default retry manager if none was specified + DefaultRetryManager = MakeUnique(6, 60); + RetryManager = DefaultRetryManager.Get(); + } + + const HttpRetryParams& Params = Request.GetRetryParams().GetValue(); + return RetryManager->CreateRequest(Params.RetryLimitCountOverride, Params.RetryTimeoutRelativeSecondsOverride, Params.RetryResponseCodes, Params.RetryVerbs, Params.RetryDomains); + } +} + void OpenAPIUserApi::HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const { InOutResponse.SetHttpResponse(HttpResponse); @@ -103,7 +137,7 @@ bool OpenAPIUserApi::CreateUser(const CreateUserRequest& Request, const FCreateU if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -113,26 +147,15 @@ bool OpenAPIUserApi::CreateUser(const CreateUserRequest& Request, const FCreateU Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUserResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUserResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnCreateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUserDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnCreateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUserDelegate Delegate) const { CreateUserResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUserResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::CreateUsersWithArrayInput(const CreateUsersWithArrayInputRequest& Request, const FCreateUsersWithArrayInputDelegate& Delegate /*= FCreateUsersWithArrayInputDelegate()*/) const @@ -140,7 +163,7 @@ bool OpenAPIUserApi::CreateUsersWithArrayInput(const CreateUsersWithArrayInputRe if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -150,26 +173,15 @@ bool OpenAPIUserApi::CreateUsersWithArrayInput(const CreateUsersWithArrayInputRe Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUsersWithArrayInputResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUsersWithArrayInputResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnCreateUsersWithArrayInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithArrayInputDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnCreateUsersWithArrayInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithArrayInputDelegate Delegate) const { CreateUsersWithArrayInputResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUsersWithArrayInputResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::CreateUsersWithListInput(const CreateUsersWithListInputRequest& Request, const FCreateUsersWithListInputDelegate& Delegate /*= FCreateUsersWithListInputDelegate()*/) const @@ -177,7 +189,7 @@ bool OpenAPIUserApi::CreateUsersWithListInput(const CreateUsersWithListInputRequ if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -187,26 +199,15 @@ bool OpenAPIUserApi::CreateUsersWithListInput(const CreateUsersWithListInputRequ Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUsersWithListInputResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUsersWithListInputResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnCreateUsersWithListInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithListInputDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnCreateUsersWithListInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithListInputDelegate Delegate) const { CreateUsersWithListInputResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUsersWithListInputResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::DeleteUser(const DeleteUserRequest& Request, const FDeleteUserDelegate& Delegate /*= FDeleteUserDelegate()*/) const @@ -214,7 +215,7 @@ bool OpenAPIUserApi::DeleteUser(const DeleteUserRequest& Request, const FDeleteU if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -224,26 +225,15 @@ bool OpenAPIUserApi::DeleteUser(const DeleteUserRequest& Request, const FDeleteU Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnDeleteUserResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnDeleteUserResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnDeleteUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteUserDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnDeleteUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteUserDelegate Delegate) const { DeleteUserResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnDeleteUserResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::GetUserByName(const GetUserByNameRequest& Request, const FGetUserByNameDelegate& Delegate /*= FGetUserByNameDelegate()*/) const @@ -251,7 +241,7 @@ bool OpenAPIUserApi::GetUserByName(const GetUserByNameRequest& Request, const FG if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -261,26 +251,15 @@ bool OpenAPIUserApi::GetUserByName(const GetUserByNameRequest& Request, const FG Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnGetUserByNameResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnGetUserByNameResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnGetUserByNameResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserByNameDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnGetUserByNameResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserByNameDelegate Delegate) const { GetUserByNameResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnGetUserByNameResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::LoginUser(const LoginUserRequest& Request, const FLoginUserDelegate& Delegate /*= FLoginUserDelegate()*/) const @@ -288,7 +267,7 @@ bool OpenAPIUserApi::LoginUser(const LoginUserRequest& Request, const FLoginUser if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -298,26 +277,15 @@ bool OpenAPIUserApi::LoginUser(const LoginUserRequest& Request, const FLoginUser Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnLoginUserResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnLoginUserResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnLoginUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginUserDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnLoginUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginUserDelegate Delegate) const { LoginUserResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnLoginUserResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::LogoutUser(const LogoutUserRequest& Request, const FLogoutUserDelegate& Delegate /*= FLogoutUserDelegate()*/) const @@ -325,7 +293,7 @@ bool OpenAPIUserApi::LogoutUser(const LogoutUserRequest& Request, const FLogoutU if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -335,26 +303,15 @@ bool OpenAPIUserApi::LogoutUser(const LogoutUserRequest& Request, const FLogoutU Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnLogoutUserResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnLogoutUserResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnLogoutUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLogoutUserDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnLogoutUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLogoutUserDelegate Delegate) const { LogoutUserResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnLogoutUserResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::UpdateUser(const UpdateUserRequest& Request, const FUpdateUserDelegate& Delegate /*= FUpdateUserDelegate()*/) const @@ -362,7 +319,7 @@ bool OpenAPIUserApi::UpdateUser(const UpdateUserRequest& Request, const FUpdateU if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -372,26 +329,15 @@ bool OpenAPIUserApi::UpdateUser(const UpdateUserRequest& Request, const FUpdateU Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnUpdateUserResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnUpdateUserResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnUpdateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnUpdateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserDelegate Delegate) const { UpdateUserResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnUpdateUserResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } } diff --git a/samples/client/petstore/cpp-ue4/Public/OpenAPIBaseModel.h b/samples/client/petstore/cpp-ue4/Public/OpenAPIBaseModel.h index d73441e1326..53858975245 100644 --- a/samples/client/petstore/cpp-ue4/Public/OpenAPIBaseModel.h +++ b/samples/client/petstore/cpp-ue4/Public/OpenAPIBaseModel.h @@ -16,11 +16,38 @@ #include "Interfaces/IHttpResponse.h" #include "Serialization/JsonWriter.h" #include "Dom/JsonObject.h" +#include "HttpRetrySystem.h" +#include "Containers/Ticker.h" namespace OpenAPI { typedef TSharedRef> JsonWriter; +using namespace FHttpRetrySystem; + +struct OPENAPI_API HttpRetryManager : public FManager, public FTickerObjectBase +{ + using FManager::FManager; + + bool Tick(float DeltaTime) final; +}; + +struct OPENAPI_API HttpRetryParams +{ + HttpRetryParams( + const FRetryLimitCountSetting& InRetryLimitCountOverride = FRetryLimitCountSetting(), + const FRetryTimeoutRelativeSecondsSetting& InRetryTimeoutRelativeSecondsOverride = FRetryTimeoutRelativeSecondsSetting(), + const FRetryResponseCodes& InRetryResponseCodes = FRetryResponseCodes(), + const FRetryVerbs& InRetryVerbs = FRetryVerbs(), + const FRetryDomainsPtr& InRetryDomains = FRetryDomainsPtr() + ); + + FRetryLimitCountSetting RetryLimitCountOverride; + FRetryTimeoutRelativeSecondsSetting RetryTimeoutRelativeSecondsOverride; + FRetryResponseCodes RetryResponseCodes; + FRetryVerbs RetryVerbs; + FRetryDomainsPtr RetryDomains; +}; class OPENAPI_API Model { @@ -37,11 +64,12 @@ public: virtual void SetupHttpRequest(const FHttpRequestRef& HttpRequest) const = 0; virtual FString ComputePath() const = 0; - void SetAutoRetryCount(int InCount) { AutoRetryCount = InCount; } - int GetAutoRetryCount() const { return AutoRetryCount; } + /* Enables retry and optionally sets a retry policy for this request */ + void SetShouldRetry(const HttpRetryParams& Params = HttpRetryParams()) { RetryParams = Params; } + const TOptional& GetRetryParams() const { return RetryParams; } private: - int AutoRetryCount = 0; + TOptional RetryParams; }; class OPENAPI_API Response @@ -53,8 +81,6 @@ public: void SetSuccessful(bool InSuccessful) { Successful = InSuccessful; } bool IsSuccessful() const { return Successful; } - void AsyncRetry() const; - virtual void SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode); EHttpResponseCodes::Type GetHttpResponseCode() const { return ResponseCode; } @@ -64,15 +90,11 @@ public: void SetHttpResponse(const FHttpResponsePtr& InHttpResponse) { HttpResponse = InHttpResponse; } const FHttpResponsePtr& GetHttpResponse() const { return HttpResponse; } - void SetHttpRequest(const FHttpRequestPtr& InHttpRequest) { HttpRequest = InHttpRequest; } - const FHttpRequestPtr& GetHttpRequest() const { return HttpRequest; } - private: bool Successful; EHttpResponseCodes::Type ResponseCode; FString ResponseString; FHttpResponsePtr HttpResponse; - FHttpRequestPtr HttpRequest; }; } diff --git a/samples/client/petstore/cpp-ue4/Public/OpenAPIPetApi.h b/samples/client/petstore/cpp-ue4/Public/OpenAPIPetApi.h index bde6403c491..db422a0eccc 100644 --- a/samples/client/petstore/cpp-ue4/Public/OpenAPIPetApi.h +++ b/samples/client/petstore/cpp-ue4/Public/OpenAPIPetApi.h @@ -24,9 +24,19 @@ public: OpenAPIPetApi(); ~OpenAPIPetApi(); + /* Sets the URL Endpoint. + * Note: several fallback endpoints can be configured in request retry policies, see Request::SetShouldRetry */ void SetURL(const FString& Url); + + /* Adds global header params to all requests */ void AddHeaderParam(const FString& Key, const FString& Value); void ClearHeaderParams(); + + /* Sets the retry manager to the user-defined retry manager. User must manage the lifetime of the retry manager. + * If no retry manager is specified and a request needs retries, a default retry manager will be used. + * See also: Request::SetShouldRetry */ + void SetHttpRetryManager(FHttpRetrySystem::FManager& RetryManager); + FHttpRetrySystem::FManager& GetHttpRetryManager(); class AddPetRequest; class AddPetResponse; @@ -63,22 +73,24 @@ public: bool UpdatePetWithForm(const UpdatePetWithFormRequest& Request, const FUpdatePetWithFormDelegate& Delegate = FUpdatePetWithFormDelegate()) const; bool UploadFile(const UploadFileRequest& Request, const FUploadFileDelegate& Delegate = FUploadFileDelegate()) const; - private: - void OnAddPetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddPetDelegate Delegate, int AutoRetryCount) const; - void OnDeletePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeletePetDelegate Delegate, int AutoRetryCount) const; - void OnFindPetsByStatusResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByStatusDelegate Delegate, int AutoRetryCount) const; - void OnFindPetsByTagsResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByTagsDelegate Delegate, int AutoRetryCount) const; - void OnGetPetByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPetByIdDelegate Delegate, int AutoRetryCount) const; - void OnUpdatePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetDelegate Delegate, int AutoRetryCount) const; - void OnUpdatePetWithFormResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetWithFormDelegate Delegate, int AutoRetryCount) const; - void OnUploadFileResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUploadFileDelegate Delegate, int AutoRetryCount) const; + void OnAddPetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddPetDelegate Delegate) const; + void OnDeletePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeletePetDelegate Delegate) const; + void OnFindPetsByStatusResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByStatusDelegate Delegate) const; + void OnFindPetsByTagsResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByTagsDelegate Delegate) const; + void OnGetPetByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPetByIdDelegate Delegate) const; + void OnUpdatePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetDelegate Delegate) const; + void OnUpdatePetWithFormResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetWithFormDelegate Delegate) const; + void OnUploadFileResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUploadFileDelegate Delegate) const; + FHttpRequestRef CreateHttpRequest(const Request& Request) const; bool IsValid() const; void HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const; FString Url; TMap AdditionalHeaderParams; + mutable FHttpRetrySystem::FManager* RetryManager = nullptr; + mutable TUniquePtr DefaultRetryManager; }; } diff --git a/samples/client/petstore/cpp-ue4/Public/OpenAPIStoreApi.h b/samples/client/petstore/cpp-ue4/Public/OpenAPIStoreApi.h index 5f537732732..934a1b277c7 100644 --- a/samples/client/petstore/cpp-ue4/Public/OpenAPIStoreApi.h +++ b/samples/client/petstore/cpp-ue4/Public/OpenAPIStoreApi.h @@ -24,9 +24,19 @@ public: OpenAPIStoreApi(); ~OpenAPIStoreApi(); + /* Sets the URL Endpoint. + * Note: several fallback endpoints can be configured in request retry policies, see Request::SetShouldRetry */ void SetURL(const FString& Url); + + /* Adds global header params to all requests */ void AddHeaderParam(const FString& Key, const FString& Value); void ClearHeaderParams(); + + /* Sets the retry manager to the user-defined retry manager. User must manage the lifetime of the retry manager. + * If no retry manager is specified and a request needs retries, a default retry manager will be used. + * See also: Request::SetShouldRetry */ + void SetHttpRetryManager(FHttpRetrySystem::FManager& RetryManager); + FHttpRetrySystem::FManager& GetHttpRetryManager(); class DeleteOrderRequest; class DeleteOrderResponse; @@ -47,18 +57,20 @@ public: bool GetOrderById(const GetOrderByIdRequest& Request, const FGetOrderByIdDelegate& Delegate = FGetOrderByIdDelegate()) const; bool PlaceOrder(const PlaceOrderRequest& Request, const FPlaceOrderDelegate& Delegate = FPlaceOrderDelegate()) const; - private: - void OnDeleteOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteOrderDelegate Delegate, int AutoRetryCount) const; - void OnGetInventoryResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetInventoryDelegate Delegate, int AutoRetryCount) const; - void OnGetOrderByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetOrderByIdDelegate Delegate, int AutoRetryCount) const; - void OnPlaceOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FPlaceOrderDelegate Delegate, int AutoRetryCount) const; + void OnDeleteOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteOrderDelegate Delegate) const; + void OnGetInventoryResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetInventoryDelegate Delegate) const; + void OnGetOrderByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetOrderByIdDelegate Delegate) const; + void OnPlaceOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FPlaceOrderDelegate Delegate) const; + FHttpRequestRef CreateHttpRequest(const Request& Request) const; bool IsValid() const; void HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const; FString Url; TMap AdditionalHeaderParams; + mutable FHttpRetrySystem::FManager* RetryManager = nullptr; + mutable TUniquePtr DefaultRetryManager; }; } diff --git a/samples/client/petstore/cpp-ue4/Public/OpenAPIUserApi.h b/samples/client/petstore/cpp-ue4/Public/OpenAPIUserApi.h index e60ce675403..809c4950125 100644 --- a/samples/client/petstore/cpp-ue4/Public/OpenAPIUserApi.h +++ b/samples/client/petstore/cpp-ue4/Public/OpenAPIUserApi.h @@ -24,9 +24,19 @@ public: OpenAPIUserApi(); ~OpenAPIUserApi(); + /* Sets the URL Endpoint. + * Note: several fallback endpoints can be configured in request retry policies, see Request::SetShouldRetry */ void SetURL(const FString& Url); + + /* Adds global header params to all requests */ void AddHeaderParam(const FString& Key, const FString& Value); void ClearHeaderParams(); + + /* Sets the retry manager to the user-defined retry manager. User must manage the lifetime of the retry manager. + * If no retry manager is specified and a request needs retries, a default retry manager will be used. + * See also: Request::SetShouldRetry */ + void SetHttpRetryManager(FHttpRetrySystem::FManager& RetryManager); + FHttpRetrySystem::FManager& GetHttpRetryManager(); class CreateUserRequest; class CreateUserResponse; @@ -63,22 +73,24 @@ public: bool LogoutUser(const LogoutUserRequest& Request, const FLogoutUserDelegate& Delegate = FLogoutUserDelegate()) const; bool UpdateUser(const UpdateUserRequest& Request, const FUpdateUserDelegate& Delegate = FUpdateUserDelegate()) const; - private: - void OnCreateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUserDelegate Delegate, int AutoRetryCount) const; - void OnCreateUsersWithArrayInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithArrayInputDelegate Delegate, int AutoRetryCount) const; - void OnCreateUsersWithListInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithListInputDelegate Delegate, int AutoRetryCount) const; - void OnDeleteUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteUserDelegate Delegate, int AutoRetryCount) const; - void OnGetUserByNameResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserByNameDelegate Delegate, int AutoRetryCount) const; - void OnLoginUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginUserDelegate Delegate, int AutoRetryCount) const; - void OnLogoutUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLogoutUserDelegate Delegate, int AutoRetryCount) const; - void OnUpdateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserDelegate Delegate, int AutoRetryCount) const; + void OnCreateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUserDelegate Delegate) const; + void OnCreateUsersWithArrayInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithArrayInputDelegate Delegate) const; + void OnCreateUsersWithListInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithListInputDelegate Delegate) const; + void OnDeleteUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteUserDelegate Delegate) const; + void OnGetUserByNameResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserByNameDelegate Delegate) const; + void OnLoginUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginUserDelegate Delegate) const; + void OnLogoutUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLogoutUserDelegate Delegate) const; + void OnUpdateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserDelegate Delegate) const; + FHttpRequestRef CreateHttpRequest(const Request& Request) const; bool IsValid() const; void HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const; FString Url; TMap AdditionalHeaderParams; + mutable FHttpRetrySystem::FManager* RetryManager = nullptr; + mutable TUniquePtr DefaultRetryManager; }; } diff --git a/samples/client/petstore/crystal/shard.yml b/samples/client/petstore/crystal/shard.yml index 06fc3300e05..a4c86a06e2a 100644 --- a/samples/client/petstore/crystal/shard.yml +++ b/samples/client/petstore/crystal/shard.yml @@ -1,4 +1,4 @@ -name: Petstore +name: petstore version: 1.0.0 authors: - diff --git a/samples/client/petstore/crystal/src/petstore/configuration.cr b/samples/client/petstore/crystal/src/petstore/configuration.cr index 833cd490005..5eab84ae97d 100644 --- a/samples/client/petstore/crystal/src/petstore/configuration.cr +++ b/samples/client/petstore/crystal/src/petstore/configuration.cr @@ -205,19 +205,19 @@ module Petstore # Returns Auth Settings hash for api client. def auth_settings - Hash{ "api_key" => { - type: "api_key", - in: "header", - key: "api_key", - value: api_key_with_prefix("api_key") - }, - "petstore_auth" => - { - type: "oauth2", - in: "header", - key: "Authorization", - value: "Bearer #{access_token}" - }, + Hash{ + "api_key" => { + type: "api_key", + in: "header", + key: "api_key", + value: api_key_with_prefix("api_key") + }, + "petstore_auth" => { + type: "oauth2", + in: "header", + key: "Authorization", + value: "Bearer #{access_token}" + }, } end diff --git a/samples/client/petstore/crystal/src/petstore/models/api_response.cr b/samples/client/petstore/crystal/src/petstore/models/api_response.cr index 30ffb012154..3359594145f 100644 --- a/samples/client/petstore/crystal/src/petstore/models/api_response.cr +++ b/samples/client/petstore/crystal/src/petstore/models/api_response.cr @@ -8,20 +8,20 @@ #OpenAPI Generator version: 6.0.0-SNAPSHOT # +require "json" require "time" module Petstore # Describes the result of uploading an image resource - class ApiResponse include JSON::Serializable - include JSON::Serializable + class ApiResponse + include JSON::Serializable + @[JSON::Field(key: code, type: Int32)] property code : Int32 - @[JSON::Field(key: type, type: String)] property _type : String - @[JSON::Field(key: message, type: String)] property message : String diff --git a/samples/client/petstore/crystal/src/petstore/models/category.cr b/samples/client/petstore/crystal/src/petstore/models/category.cr index 9e52c988bbb..0fb84faf74b 100644 --- a/samples/client/petstore/crystal/src/petstore/models/category.cr +++ b/samples/client/petstore/crystal/src/petstore/models/category.cr @@ -8,16 +8,17 @@ #OpenAPI Generator version: 6.0.0-SNAPSHOT # +require "json" require "time" module Petstore # A category for a pet - class Category include JSON::Serializable - include JSON::Serializable + class Category + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] property id : Int64 - @[JSON::Field(key: name, type: String)] property name : String diff --git a/samples/client/petstore/crystal/src/petstore/models/order.cr b/samples/client/petstore/crystal/src/petstore/models/order.cr index 31f9b155e53..656c61b86b7 100644 --- a/samples/client/petstore/crystal/src/petstore/models/order.cr +++ b/samples/client/petstore/crystal/src/petstore/models/order.cr @@ -8,33 +8,30 @@ #OpenAPI Generator version: 6.0.0-SNAPSHOT # +require "json" require "time" module Petstore # An order for a pets from the pet store - class Order include JSON::Serializable - include JSON::Serializable + class Order + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] property id : Int64 - @[JSON::Field(key: petId, type: Int64)] property pet_id : Int64 - @[JSON::Field(key: quantity, type: Int32)] property quantity : Int32 - @[JSON::Field(key: shipDate, type: Time)] property ship_date : Time - # Order Status @[JSON::Field(key: status, type: String)] property status : String - @[JSON::Field(key: complete, type: Bool)] property complete : Bool diff --git a/samples/client/petstore/crystal/src/petstore/models/pet.cr b/samples/client/petstore/crystal/src/petstore/models/pet.cr index 8d15de33c87..c6471d5672a 100644 --- a/samples/client/petstore/crystal/src/petstore/models/pet.cr +++ b/samples/client/petstore/crystal/src/petstore/models/pet.cr @@ -8,32 +8,29 @@ #OpenAPI Generator version: 6.0.0-SNAPSHOT # +require "json" require "time" module Petstore # A pet for sale in the pet store - class Pet include JSON::Serializable - include JSON::Serializable + class Pet + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] property id : Int64 - @[JSON::Field(key: category, type: Category)] property category : Category - @[JSON::Field(key: name, type: String)] property name : String - @[JSON::Field(key: photoUrls, type: Array(String))] property photo_urls : Array(String) - @[JSON::Field(key: tags, type: Array(Tag))] property tags : Array(Tag) - # pet status in the store @[JSON::Field(key: status, type: String)] property status : String diff --git a/samples/client/petstore/crystal/src/petstore/models/tag.cr b/samples/client/petstore/crystal/src/petstore/models/tag.cr index 0a012104c5a..ab09edc3291 100644 --- a/samples/client/petstore/crystal/src/petstore/models/tag.cr +++ b/samples/client/petstore/crystal/src/petstore/models/tag.cr @@ -8,16 +8,17 @@ #OpenAPI Generator version: 6.0.0-SNAPSHOT # +require "json" require "time" module Petstore # A tag for a pet - class Tag include JSON::Serializable - include JSON::Serializable + class Tag + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] property id : Int64 - @[JSON::Field(key: name, type: String)] property name : String diff --git a/samples/client/petstore/crystal/src/petstore/models/user.cr b/samples/client/petstore/crystal/src/petstore/models/user.cr index 12330d212d0..8c0fbfde5dc 100644 --- a/samples/client/petstore/crystal/src/petstore/models/user.cr +++ b/samples/client/petstore/crystal/src/petstore/models/user.cr @@ -8,40 +8,35 @@ #OpenAPI Generator version: 6.0.0-SNAPSHOT # +require "json" require "time" module Petstore # A User who is purchasing from the pet store - class User include JSON::Serializable - include JSON::Serializable + class User + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] property id : Int64 - @[JSON::Field(key: username, type: String)] property username : String - @[JSON::Field(key: firstName, type: String)] property first_name : String - @[JSON::Field(key: lastName, type: String)] property last_name : String - @[JSON::Field(key: email, type: String)] property email : String - @[JSON::Field(key: password, type: String)] property password : String - @[JSON::Field(key: phone, type: String)] property phone : String - # User Status @[JSON::Field(key: userStatus, type: Int32)] property user_status : Int32 diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/README.md index e16da183ea8..48379909c58 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/README.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/README.md @@ -83,6 +83,7 @@ services.AddHttpClient(httpClient => ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -96,7 +97,10 @@ namespace Example Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new AnotherFakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new AnotherFakeApi(httpClient, config, httpClientHandler); var modelClient = new ModelClient(); // ModelClient | client model try diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/AnotherFakeApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/AnotherFakeApi.md index 93fca7e408a..83cdaf2ae93 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/AnotherFakeApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/AnotherFakeApi.md @@ -19,6 +19,7 @@ To test special tags and operation ID starting with number ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -31,7 +32,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new AnotherFakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new AnotherFakeApi(httpClient, config, httpClientHandler); var modelClient = new ModelClient(); // ModelClient | client model try diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/DefaultApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/DefaultApi.md index 6f5de6b6851..ec724183283 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/DefaultApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/DefaultApi.md @@ -17,6 +17,7 @@ Method | HTTP request | Description ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -29,7 +30,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new DefaultApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new DefaultApi(httpClient, config, httpClientHandler); try { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeApi.md index af8d565abfb..947fbb114ef 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeApi.md @@ -31,6 +31,7 @@ Health check endpoint ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -43,7 +44,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); try { @@ -98,6 +102,7 @@ Test serialization of outer boolean types ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -110,7 +115,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var body = true; // bool? | Input boolean as post body (optional) try @@ -168,6 +176,7 @@ Test serialization of object with outer number type ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -180,7 +189,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body (optional) try @@ -238,6 +250,7 @@ Test serialization of outer number types ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -250,7 +263,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var body = 8.14; // decimal? | Input number as post body (optional) try @@ -308,6 +324,7 @@ Test serialization of outer string types ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -320,7 +337,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var body = body_example; // string | Input string as post body (optional) try @@ -376,6 +396,7 @@ Array of Enums ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -388,7 +409,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); try { @@ -443,6 +467,7 @@ For this test, the body for this request much reference a schema named `File`. ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -455,7 +480,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass | try @@ -510,6 +538,7 @@ No authorization required ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -522,7 +551,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var query = query_example; // string | var user = new User(); // User | @@ -581,6 +613,7 @@ To test \"client\" model ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -593,7 +626,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var modelClient = new ModelClient(); // ModelClient | client model try @@ -652,6 +688,7 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -668,7 +705,10 @@ namespace Example config.Username = "YOUR_USERNAME"; config.Password = "YOUR_PASSWORD"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var number = 8.14; // decimal | None var _double = 1.2D; // double | None var patternWithoutDelimiter = patternWithoutDelimiter_example; // string | None @@ -753,6 +793,7 @@ To test enum parameters ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -765,7 +806,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var enumHeaderStringArray = enumHeaderStringArray_example; // List | Header parameter enum test (string array) (optional) var enumHeaderString = enumHeaderString_example; // string | Header parameter enum test (string) (optional) (default to -efg) var enumQueryStringArray = enumQueryStringArray_example; // List | Query parameter enum test (string array) (optional) @@ -838,6 +882,7 @@ Fake endpoint to test group parameters (optional) ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -853,7 +898,10 @@ namespace Example // Configure Bearer token for authorization: bearer_test config.AccessToken = "YOUR_BEARER_TOKEN"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var requiredStringGroup = 56; // int | Required String in group parameters var requiredBooleanGroup = true; // bool | Required Boolean in group parameters var requiredInt64Group = 789; // long | Required Integer in group parameters @@ -919,6 +967,7 @@ test inline additionalProperties ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -931,7 +980,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var requestBody = new Dictionary(); // Dictionary | request body try @@ -987,6 +1039,7 @@ test json serialization of form data ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -999,7 +1052,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var param = param_example; // string | field1 var param2 = param2_example; // string | field2 @@ -1059,6 +1115,7 @@ To test the collection format in query parameters ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -1071,7 +1128,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var pipe = new List(); // List | var ioutil = new List(); // List | var http = new List(); // List | diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeClassnameTags123Api.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeClassnameTags123Api.md index 13235fbd10f..4c748ad71c8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeClassnameTags123Api.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeClassnameTags123Api.md @@ -19,6 +19,7 @@ To test class name in snake case ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -36,7 +37,10 @@ namespace Example // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key_query", "Bearer"); - var apiInstance = new FakeClassnameTags123Api(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeClassnameTags123Api(httpClient, config, httpClientHandler); var modelClient = new ModelClient(); // ModelClient | client model try diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/PetApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/PetApi.md index 47820f406dd..9f4ec108d05 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/PetApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/PetApi.md @@ -25,6 +25,7 @@ Add a new pet to the store ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -40,7 +41,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var pet = new Pet(); // Pet | Pet object that needs to be added to the store try @@ -96,6 +100,7 @@ Deletes a pet ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -111,7 +116,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var petId = 789; // long | Pet id to delete var apiKey = apiKey_example; // string | (optional) @@ -171,6 +179,7 @@ Multiple status values can be provided with comma separated strings ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -186,7 +195,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var status = status_example; // List | Status values that need to be considered for filter try @@ -246,6 +258,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -261,7 +274,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var tags = new List(); // List | Tags to filter by try @@ -321,6 +337,7 @@ Returns a single pet ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -338,7 +355,10 @@ namespace Example // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var petId = 789; // long | ID of pet to return try @@ -397,6 +417,7 @@ Update an existing pet ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -412,7 +433,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var pet = new Pet(); // Pet | Pet object that needs to be added to the store try @@ -470,6 +494,7 @@ Updates a pet in the store with form data ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -485,7 +510,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var petId = 789; // long | ID of pet that needs to be updated var name = name_example; // string | Updated name of the pet (optional) var status = status_example; // string | Updated status of the pet (optional) @@ -545,6 +573,7 @@ uploads an image ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -560,7 +589,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var petId = 789; // long | ID of pet to update var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional) var file = BINARY_DATA_HERE; // System.IO.Stream | file to upload (optional) @@ -621,6 +653,7 @@ uploads an image (required) ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -636,7 +669,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var petId = 789; // long | ID of pet to update var requiredFile = BINARY_DATA_HERE; // System.IO.Stream | file to upload var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/StoreApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/StoreApi.md index 24e2480d5de..248bf31f849 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/StoreApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/StoreApi.md @@ -22,6 +22,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -34,7 +35,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new StoreApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new StoreApi(httpClient, config, httpClientHandler); var orderId = orderId_example; // string | ID of the order that needs to be deleted try @@ -93,6 +97,7 @@ Returns a map of status codes to quantities ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -110,7 +115,10 @@ namespace Example // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); - var apiInstance = new StoreApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new StoreApi(httpClient, config, httpClientHandler); try { @@ -165,6 +173,7 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -177,7 +186,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new StoreApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new StoreApi(httpClient, config, httpClientHandler); var orderId = 789; // long | ID of pet that needs to be fetched try @@ -236,6 +248,7 @@ Place an order for a pet ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -248,7 +261,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new StoreApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new StoreApi(httpClient, config, httpClientHandler); var order = new Order(); // Order | order placed for purchasing the pet try diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/UserApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/UserApi.md index aa12c26c69f..417d9002cf9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/UserApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/UserApi.md @@ -26,6 +26,7 @@ This can only be done by the logged in user. ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -38,7 +39,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var user = new User(); // User | Created user object try @@ -94,6 +98,7 @@ Creates list of users with given input array ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -106,7 +111,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var user = new List(); // List | List of user object try @@ -162,6 +170,7 @@ Creates list of users with given input array ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -174,7 +183,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var user = new List(); // List | List of user object try @@ -232,6 +244,7 @@ This can only be done by the logged in user. ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -244,7 +257,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var username = username_example; // string | The name that needs to be deleted try @@ -301,6 +317,7 @@ Get user by user name ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -313,7 +330,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var username = username_example; // string | The name that needs to be fetched. Use user1 for testing. try @@ -372,6 +392,7 @@ Logs user into the system ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -384,7 +405,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var username = username_example; // string | The user name for login var password = password_example; // string | The password for login in clear text @@ -444,6 +468,7 @@ Logs out current logged in user session ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -456,7 +481,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); try { @@ -510,6 +538,7 @@ This can only be done by the logged in user. ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -522,7 +551,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var username = username_example; // string | name that need to be deleted var user = new User(); // User | Updated user object diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTests.cs index eca3164a17f..1af712abb4d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTests.cs @@ -16,6 +16,8 @@ using System.Linq; using System.Reflection; using Xunit; +using System.Net.Http; + using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; @@ -34,6 +36,7 @@ namespace Org.OpenAPITools.Test private PetApi instance; private long petId = 11088; + private long notExsistentPetId = 99999; /// /// Create a Pet object @@ -73,8 +76,10 @@ namespace Org.OpenAPITools.Test } public PetApiTests() - { - instance = new PetApi(); + { + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + instance = new PetApi(httpClient, httpClientHandler); // create pet Pet p = createPet(); @@ -153,7 +158,9 @@ namespace Org.OpenAPITools.Test c1.Timeout = 10000; c1.UserAgent = "TEST_USER_AGENT"; - PetApi petApi = new PetApi(c1); + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + PetApi petApi = new PetApi(httpClient, c1, httpClientHandler); Pet response = petApi.GetPetById(petId); Assert.IsType(response); @@ -198,6 +205,25 @@ namespace Org.OpenAPITools.Test Assert.Equal("sample category name2", response.Category.Name); } + /// + /// Test GetPetById on an not existent Id + /// + [Fact] + public void TestGetPetById_TestException() + { + PetApi petApi = new PetApi(); + + var exception = Assert.Throws(() => + { + petApi.GetPetById(notExsistentPetId); + }); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.ErrorContent); + Assert.Equal("Error calling GetPetById: {\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.Message); + } + /* a simple test for binary response. no longer in use. [Fact] public void TestGetByIdBinaryResponse() @@ -241,7 +267,25 @@ namespace Org.OpenAPITools.Test Assert.Equal(56, response.Category.Id); Assert.Equal("sample category name2", response.Category.Name); } - + + [Fact] + public void TestGetPetByIdWithHttpInfoAsync_Test404Response() + { + PetApi petApi = new PetApi(); + petApi.ExceptionFactory = null; + var response = petApi.GetPetByIdWithHttpInfoAsync(notExsistentPetId).Result; + Pet result = response.Data; + + Assert.IsType>(response); + Assert.Equal(404, (int)response.StatusCode); + Assert.True(response.Headers.ContainsKey("Content-Type")); + Assert.Equal("application/json", response.Headers["Content-Type"][0]); + + Assert.Null(result); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", response.RawContent); + Assert.Equal("Not Found", response.ErrorText); + } + /// /// Test UpdatePet /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTestsV2.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTestsV2.cs new file mode 100644 index 00000000000..e00f3d61467 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTestsV2.cs @@ -0,0 +1,579 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Reflection; +using System.Threading.Tasks; +using Xunit; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing PetApi + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class PetApiTestsV2 : IDisposable + { + // CONFIGURE TESTING PARAMETERS HERE + // see the Integration Test Wiki for details: https://github.com/OpenAPITools/openapi-generator/wiki/Integration-Tests + private const string BasePath = "http://petstore.swagger.io/v2"; + private const long PetId = 100000; + private const long NotExistentId = 100001; + + private readonly HttpClient _httpClient = new HttpClient(); + private readonly PetApi _petApi; + + public PetApiTestsV2() + { + // prepare the client + _petApi = new PetApi(_httpClient, new Configuration + { + BasePath = BasePath, + Timeout = 10000, + UserAgent = "TEST_USER_AGENT" + }); + + // add a sample pet for the expected PetId + _petApi.AddPet(BuildSamplePet()); + + // ensure there is not a pet for that ID + try + { + _petApi.DeletePet(NotExistentId); + } + catch (ApiException ex) when (ex.ErrorCode == 404) { } + } + + #region Get + + /// + /// Test GetPetById with an existent Id + /// + [Fact] + public void GetPetById_GivenExistentId_ReturnsPet() + { + Pet expected = BuildSamplePet(); + + Pet response = _petApi.GetPetById(PetId); + + Assert.IsType(response); + Assert.Equal(expected.Name, response.Name); + Assert.Equal(expected.Status, response.Status); + Assert.IsType>(response.Tags); + Assert.Equal(expected.Tags[0].Id, response.Tags[0].Id); + Assert.Equal(expected.Tags[0].Name, response.Tags[0].Name); + Assert.IsType>(response.PhotoUrls); + Assert.Equal(expected.PhotoUrls[0], response.PhotoUrls[0]); + Assert.IsType(response.Category); + Assert.Equal(expected.Category.Id, response.Category.Id); + Assert.Equal(expected.Category.Name, response.Category.Name); + } + + /// + /// Test GetPetById with a not existent Id + /// + [Fact] + public void GetPetById_GivenNotExistentId_ThrowsApiException() + { + var exception = Assert.Throws(() => + { + _petApi.GetPetById(NotExistentId); + }); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.ErrorContent); + Assert.Equal("Error calling GetPetById: {\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.Message); + } + + /// + /// Test GetPetByIdWithHttpInfo with an existent Id + /// + [Fact] + public void GetPetByIdWithHttpInfo_GivenExistentId_Returns200Response() + { + Pet expected = BuildSamplePet(); + + ApiResponse response = _petApi.GetPetByIdWithHttpInfo(PetId); + Pet result = response.Data; + + Assert.IsType>(response); + Assert.Equal(200, (int)response.StatusCode); + Assert.True(response.Headers.ContainsKey("Content-Type")); + Assert.Equal("application/json", response.Headers["Content-Type"][0]); + + Assert.Equal(expected.Name, result.Name); + Assert.Equal(expected.Status, result.Status); + Assert.IsType>(result.Tags); + Assert.Equal(expected.Tags[0].Id, result.Tags[0].Id); + Assert.Equal(expected.Tags[0].Name, result.Tags[0].Name); + Assert.IsType>(result.PhotoUrls); + Assert.Equal(expected.PhotoUrls[0], result.PhotoUrls[0]); + Assert.IsType(result.Category); + Assert.Equal(expected.Category.Id, result.Category.Id); + Assert.Equal(expected.Category.Name, result.Category.Name); + } + + /// + /// Test GetPetByIdWithHttpInfo with a not existent Id and the ExceptionFactory disabled + /// + [Fact] + public void GetPetByIdWithHttpInfo_GivenNotExistentId_ThrowsApiException() + { + var exception = Assert.Throws(() => + { + _petApi.GetPetByIdWithHttpInfo(NotExistentId); + }); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.ErrorContent); + Assert.Equal("Error calling GetPetById: {\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.Message); + } + + /// + /// Test GetPetByIdWithHttpInfo with a not existent Id and the ExceptionFactory disabled + /// + [Fact] + public void GetPetByIdWithHttpInfo_WithoutExceptionFactory_GivenNotExistentId_Returns404Response() + { + _petApi.ExceptionFactory = null; + ApiResponse response = _petApi.GetPetByIdWithHttpInfo(NotExistentId); + Pet result = response.Data; + + Assert.IsType>(response); + Assert.Equal(404, (int)response.StatusCode); + Assert.True(response.Headers.ContainsKey("Content-Type")); + Assert.Equal("application/json", response.Headers["Content-Type"][0]); + + Assert.Null(result); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", response.RawContent); + Assert.Equal("Not Found", response.ErrorText); + } + + #endregion + + #region Get Async + + /// + /// Test GetPetByIdAsync with an existent Id. + /// + [Fact] + public async Task GetPetByIdAsync_GivenExistentId_ReturnsPet() + { + Pet expected = BuildSamplePet(); + + Pet response = await _petApi.GetPetByIdAsync(PetId); + + Assert.IsType(response); + Assert.Equal(expected.Name, response.Name); + Assert.Equal(expected.Status, response.Status); + Assert.IsType>(response.Tags); + Assert.Equal(expected.Tags[0].Id, response.Tags[0].Id); + Assert.Equal(expected.Tags[0].Name, response.Tags[0].Name); + Assert.IsType>(response.PhotoUrls); + Assert.Equal(expected.PhotoUrls[0], response.PhotoUrls[0]); + Assert.IsType(response.Category); + Assert.Equal(expected.Category.Id, response.Category.Id); + Assert.Equal(expected.Category.Name, response.Category.Name); + } + + /// + /// Test GetPetByIdAsync with a not existent Id. + /// + [Fact] + public async Task GetPetByIdAsync_GivenNotExistentId_ThrowsApiException() + { + var exception = await Assert.ThrowsAsync(() => _petApi.GetPetByIdAsync(NotExistentId)); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.ErrorContent); + Assert.Equal("Error calling GetPetById: {\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.Message); + } + + /// + /// Test GetPetByIdWithHttpInfoAsync with an existent Id. + /// + [Fact] + public async Task GetPetByIdWithHttpInfoAsync_GivenExistentId_Returns200Response() + { + Pet expected = BuildSamplePet(); + + ApiResponse response = await _petApi.GetPetByIdWithHttpInfoAsync(PetId); + Pet result = response.Data; + + Assert.IsType>(response); + Assert.Equal(200, (int)response.StatusCode); + Assert.True(response.Headers.ContainsKey("Content-Type")); + Assert.Equal("application/json", response.Headers["Content-Type"][0]); + + Assert.Equal(expected.Name, result.Name); + Assert.Equal(expected.Status, result.Status); + Assert.IsType>(result.Tags); + Assert.Equal(expected.Tags[0].Id, result.Tags[0].Id); + Assert.Equal(expected.Tags[0].Name, result.Tags[0].Name); + Assert.IsType>(result.PhotoUrls); + Assert.Equal(expected.PhotoUrls[0], result.PhotoUrls[0]); + Assert.IsType(result.Category); + Assert.Equal(expected.Category.Id, result.Category.Id); + Assert.Equal(expected.Category.Name, result.Category.Name); + } + + /// + /// Test GetPetByIdWithHttpInfoAsync with a not existent Id and the ExceptionFactory disabled. + /// + [Fact] + public async Task GetPetByIdWithHttpInfoAsync_GivenNotExistentId_ThrowsApiException() + { + var exception = await Assert.ThrowsAsync(() => _petApi.GetPetByIdWithHttpInfoAsync(NotExistentId)); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.ErrorContent); + Assert.Equal("Error calling GetPetById: {\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.Message); + } + + /// + /// Test GetPetByIdWithHttpInfoAsync with a not existent Id and the ExceptionFactory disabled. + /// + [Fact] + public async Task GetPetByIdWithHttpInfoAsync_WithoutExceptionFactory_GivenNotExistentId_Returns404Response() + { + _petApi.ExceptionFactory = null; + ApiResponse response = await _petApi.GetPetByIdWithHttpInfoAsync(NotExistentId); + Pet result = response.Data; + + Assert.IsType>(response); + Assert.Equal(404, (int)response.StatusCode); + Assert.True(response.Headers.ContainsKey("Content-Type")); + Assert.Equal("application/json", response.Headers["Content-Type"][0]); + + Assert.Null(result); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", response.RawContent); + Assert.Equal("Not Found", response.ErrorText); + } + + #endregion + + #region Find + + /// + /// Test FindPetsByStatus filtering available pets. + /// + [Fact(Skip = "too much elements to fetch, the server cut the json content")] + public void FindPetsByStatus_ReturnsListOfPetsFiltered() + { + List pets = _petApi.FindPetsByStatus(new List(new[] { "available" })); + + foreach (Pet pet in pets) + { + Assert.IsType(pet); + Assert.Equal(Pet.StatusEnum.Available, pet.Status); + } + } + + #endregion + + #region Add + + /// + /// Test AddPet with an existent Id. The current server beavior is to update the Pet. + /// + [Fact] + public void AddPet_GivenExistentId_UpdateThePet() + { + Pet pet = BuildSamplePet(); + + _petApi.AddPet(pet); + } + + #endregion + + #region AddAsync + + /// + /// Test AddPetAsync with an existent Id. The current server beavior is to update the Pet. + /// + [Fact] + public async Task AddPetAsync_GivenExistentId_UpdateThePet() + { + Pet pet = BuildSamplePet(); + + await _petApi.AddPetAsync(pet); + } + + #endregion + + #region Update + + /// + /// Test UpdatePet with an existent Id. + /// + [Fact] + public void UpdatePet_GivenExistentId_UpdateThePet() + { + Pet pet = BuildSamplePet(); + + _petApi.UpdatePet(pet); + } + + /// + /// Test UpdatePet with a not existent Id. The current server beavior is to create the Pet. + /// + [Fact] + public void UpdatePet_GivenNotExistentId_UpdateThePet() + { + Pet pet = BuildSamplePet(i => i.Id = NotExistentId); + + _petApi.UpdatePet(pet); + } + + /// + /// Test UpdatePetWithForm with an existent Id. + /// + [Fact] + public void UpdatePetWithForm_GivenExistentId_UpdatesTheFields() + { + Pet expected = BuildSamplePet(pet => + { + pet.Name = "name updated"; + pet.Status = Pet.StatusEnum.Pending; + }); + + _petApi.UpdatePetWithForm(PetId, "name updated", "pending"); + + Pet response = _petApi.GetPetById(PetId); + + Assert.IsType(response); + Assert.Equal(expected.Name, response.Name); + Assert.Equal(expected.Status, response.Status); + Assert.IsType>(response.Tags); + Assert.Equal(expected.Tags[0].Id, response.Tags[0].Id); + Assert.Equal(expected.Tags[0].Name, response.Tags[0].Name); + Assert.IsType>(response.PhotoUrls); + Assert.Equal(expected.PhotoUrls[0], response.PhotoUrls[0]); + Assert.IsType(response.Category); + Assert.Equal(expected.Category.Id, response.Category.Id); + Assert.Equal(expected.Category.Name, response.Category.Name); + + _petApi.UpdatePetWithForm(PetId, "name updated twice"); + + response = _petApi.GetPetById(PetId); + + Assert.Equal("name updated twice", response.Name); + } + + /// + /// Test UploadFile with an existent Id. + /// + [Fact(Skip = "generates 500 code at the time of test")] + public void UploadFile_UploadFileUsingFormParameters_UpdatesTheFields() + { + var assembly = Assembly.GetExecutingAssembly(); + using Stream imageStream = assembly.GetManifestResourceStream("Org.OpenAPITools.Test.linux-logo.png"); + _petApi.UploadFile(PetId, "metadata sample", imageStream); + } + + /// + /// Test UploadFile with an existent Id. + /// + [Fact(Skip = "generates 500 code at the time of test")] + public void UploadFile_UploadFileAlone_UpdatesTheField() + { + var assembly = Assembly.GetExecutingAssembly(); + using Stream imageStream = assembly.GetManifestResourceStream("Org.OpenAPITools.Test.linux-logo.png"); + _petApi.UploadFile(petId: PetId, file: imageStream); + } + + #endregion + + #region UpdateAsync + + /// + /// Test UpdatePetAsync with an existent Id. + /// + [Fact] + public async Task UpdatePetAsync_GivenExistentId_UpdateThePet() + { + Pet pet = BuildSamplePet(); + + await _petApi.UpdatePetAsync(pet); + } + + /// + /// Test UpdatePetAsync with a not existent Id. The current server beavior is to create the Pet. + /// + [Fact] + public async Task UpdatePetAsync_GivenNotExistentId_UpdateThePet() + { + Pet pet = BuildSamplePet(i => i.Id = NotExistentId); + + await _petApi.UpdatePetAsync(pet); + } + + /// + /// Test UpdatePetWithFormAsync with an existent Id. + /// + [Fact] + public async Task UpdatePetWithFormAsync_GivenExistentId_UpdatesTheFields() + { + Pet expected = BuildSamplePet(pet => + { + pet.Name = "name updated"; + pet.Status = Pet.StatusEnum.Pending; + }); + + await _petApi.UpdatePetWithFormAsync(PetId, "name updated", "pending"); + + Pet response = await _petApi.GetPetByIdAsync(PetId); + + Assert.IsType(response); + Assert.Equal(expected.Name, response.Name); + Assert.Equal(expected.Status, response.Status); + Assert.IsType>(response.Tags); + Assert.Equal(expected.Tags[0].Id, response.Tags[0].Id); + Assert.Equal(expected.Tags[0].Name, response.Tags[0].Name); + Assert.IsType>(response.PhotoUrls); + Assert.Equal(expected.PhotoUrls[0], response.PhotoUrls[0]); + Assert.IsType(response.Category); + Assert.Equal(expected.Category.Id, response.Category.Id); + Assert.Equal(expected.Category.Name, response.Category.Name); + + await _petApi.UpdatePetWithFormAsync(PetId, "name updated twice"); + + response = await _petApi.GetPetByIdAsync(PetId); + + Assert.Equal("name updated twice", response.Name); + } + + /// + /// Test UploadFileAsync with an existent Id. + /// + [Fact(Skip = "generates 500 code at the time of test")] + public async Task UploadFileAsync_UploadFileUsingFormParameters_UpdatesTheFields() + { + var assembly = Assembly.GetExecutingAssembly(); + await using Stream imageStream = assembly.GetManifestResourceStream("Org.OpenAPITools.Test.linux-logo.png"); + await _petApi.UploadFileAsync(PetId, "metadata sample", imageStream); + } + + /// + /// Test UploadFileAsync with an existent Id. + /// + [Fact(Skip = "generates 500 code at the time of test")] + public async Task UploadFileAsync_UploadFileAlone_UpdatesTheField() + { + var assembly = Assembly.GetExecutingAssembly(); + await using Stream imageStream = assembly.GetManifestResourceStream("Org.OpenAPITools.Test.linux-logo.png"); + await _petApi.UploadFileAsync(petId: PetId, file: imageStream); + } + + #endregion + + #region Delete + + /// + /// Test DeletePet with an existent Id. + /// + [Fact] + public void DeletePet_GivenExistentId_DeleteThePet() + { + _petApi.DeletePet(PetId); + + var exception = Assert.Throws(() => _petApi.GetPetById(PetId)); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + } + + /// + /// Test DeletePet with a not existent Id. The current server beavior is to return 404. + /// + [Fact] + public void DeletePet_GivenNotExistentId_ThrowsApiException() + { + var exception = Assert.Throws(() => _petApi.DeletePet(NotExistentId)); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + } + + #endregion + + #region DeleteAsync + + /// + /// Test DeletePet with an existent Id. + /// + [Fact] + public async Task DeletePetAsync_GivenExistentId_DeleteThePet() + { + await _petApi.DeletePetAsync(PetId); + + var exception = Assert.Throws(() => _petApi.GetPetById(PetId)); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + } + + /// + /// Test DeletePet with a not existent Id. The current server beavior is to return 404. + /// + [Fact] + public async Task DeletePetAsync_GivenNotExistentId_ThrowsApiException() + { + var exception = await Assert.ThrowsAsync(() => _petApi.DeletePetAsync(NotExistentId)); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + } + + #endregion + + private static Pet BuildSamplePet(Action callback = null) + { + var pet = new Pet( + name: "csharp test", + photoUrls: new List { "http://petstore.com/csharp_test" }) + { + Id = PetId, + Status = Pet.StatusEnum.Available, + Category = new Category { Id = 10, Name = "sample category" }, + Tags = new List { new Tag { Id = 100, Name = "sample tag" } } + }; + + callback?.Invoke(pet); + + return pet; + } + + public void Dispose() + { + // remove the pet after testing + try + { + _petApi.DeletePet(PetId); + } + catch (ApiException ex) when (ex.ErrorCode == 404) { } + + _petApi.Dispose(); + _httpClient.Dispose(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index dcc1208d75c..20f33144c2a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,7 +8,10 @@ - + + + + @@ -18,9 +21,7 @@ - - - - + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index 83a938cf365..8498781b05c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -100,20 +100,22 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public AnotherFakeApi() : this((string)null) { } /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public AnotherFakeApi(String basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( @@ -128,11 +130,12 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public AnotherFakeApi(Org.OpenAPITools.Client.Configuration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/DefaultApi.cs index 84b91a9a171..299f2875b21 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -93,20 +93,22 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public DefaultApi() : this((string)null) { } /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public DefaultApi(String basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( @@ -121,11 +123,12 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public DefaultApi(Org.OpenAPITools.Client.Configuration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs index 305a59a6b5b..66f86c619fc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs @@ -817,20 +817,22 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public FakeApi() : this((string)null) { } /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public FakeApi(String basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( @@ -845,11 +847,12 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public FakeApi(Org.OpenAPITools.Client.Configuration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index f9c9d3b33ce..efec560791e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -100,20 +100,22 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public FakeClassnameTags123Api() : this((string)null) { } /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public FakeClassnameTags123Api(String basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( @@ -128,11 +130,12 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public FakeClassnameTags123Api(Org.OpenAPITools.Client.Configuration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs index b43e10ad1ff..7f9a79b6bb3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs @@ -462,20 +462,22 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public PetApi() : this((string)null) { } /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public PetApi(String basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( @@ -490,11 +492,12 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public PetApi(Org.OpenAPITools.Client.Configuration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/StoreApi.cs index f174edf5062..d7b0b43698a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/StoreApi.cs @@ -225,20 +225,22 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public StoreApi() : this((string)null) { } /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public StoreApi(String basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( @@ -253,11 +255,12 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public StoreApi(Org.OpenAPITools.Client.Configuration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/UserApi.cs index 0426a00745e..9b4826f955e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/UserApi.cs @@ -397,20 +397,22 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public UserApi() : this((string)null) { } /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public UserApi(String basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( @@ -425,11 +427,12 @@ namespace Org.OpenAPITools.Api /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public UserApi(Org.OpenAPITools.Client.Configuration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs index 26695dd48d4..526a4311117 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs @@ -98,13 +98,13 @@ namespace Org.OpenAPITools.Client if (type == typeof(byte[])) // return byte array { - return response.Content.ReadAsByteArrayAsync().Result; + return response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); } // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) if (type == typeof(Stream)) { - var bytes = response.Content.ReadAsByteArrayAsync().Result; + var bytes = response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); if (headers != null) { var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) @@ -128,18 +128,18 @@ namespace Org.OpenAPITools.Client if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content.ReadAsStringAsync().Result, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), null, System.Globalization.DateTimeStyles.RoundtripKind); } if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type { - return Convert.ChangeType(response.Content.ReadAsStringAsync().Result, type); + return Convert.ChangeType(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), type); } // at this point, it must be a model (json) try { - return JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result, type, _serializerSettings); + return JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), type, _serializerSettings); } catch (Exception e) { @@ -191,8 +191,9 @@ namespace Org.OpenAPITools.Client /// /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public ApiClient() : this(Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath) { @@ -200,10 +201,11 @@ namespace Org.OpenAPITools.Client /// /// Initializes a new instance of the . + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. /// - [Obsolete("Constructors without HttpClient have non-trivial drawbacks and are thus considered deprecated. Check README.md for details.")] public ApiClient(String basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); @@ -397,10 +399,10 @@ namespace Org.OpenAPITools.Client partial void InterceptRequest(HttpRequestMessage req); partial void InterceptResponse(HttpRequestMessage req, HttpResponseMessage response); - private ApiResponse ToApiResponse(HttpResponseMessage response, object responseData, Uri uri) + private async Task> ToApiResponse(HttpResponseMessage response, object responseData, Uri uri) { T result = (T) responseData; - string rawContent = response.Content.ToString(); + string rawContent = await response.Content.ReadAsStringAsync(); var transformed = new ApiResponse(response.StatusCode, new Multimap(), result, rawContent) { @@ -442,7 +444,7 @@ namespace Org.OpenAPITools.Client private ApiResponse Exec(HttpRequestMessage req, IReadableConfiguration configuration) { - return ExecAsync(req, configuration).Result; + return ExecAsync(req, configuration).GetAwaiter().GetResult(); } private async Task> ExecAsync(HttpRequestMessage req, @@ -503,6 +505,11 @@ namespace Org.OpenAPITools.Client response = await _httpClient.SendAsync(req, cancellationToken).ConfigureAwait(false); } + if (!response.IsSuccessStatusCode) + { + return await ToApiResponse(response, default(T), req.RequestUri); + } + object responseData = deserializer.Deserialize(response); // if the response type is oneOf/anyOf, call FromJSON to deserialize the data @@ -517,9 +524,7 @@ namespace Org.OpenAPITools.Client InterceptResponse(req, response); - var result = ToApiResponse(response, responseData, req.RequestUri); - - return result; + return await ToApiResponse(response, responseData, req.RequestUri); } #region IAsynchronousClient diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.sbt b/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.sbt index 289532fdd68..020460f4527 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.sbt +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.sbt @@ -10,8 +10,8 @@ lazy val root = (project in file(".")). resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.24", - "com.squareup.okhttp3" % "okhttp" % "3.14.7", - "com.squareup.okhttp3" % "logging-interceptor" % "3.14.7", + "com.squareup.okhttp3" % "okhttp" % "4.9.1", + "com.squareup.okhttp3" % "logging-interceptor" % "4.9.1", "com.google.code.gson" % "gson" % "2.8.6", "org.apache.commons" % "commons-lang3" % "3.10", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1", diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt index d3bf50f4d7f..c36bbc5ca08 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt @@ -10,8 +10,8 @@ lazy val root = (project in file(".")). resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.24", - "com.squareup.okhttp3" % "okhttp" % "3.14.7", - "com.squareup.okhttp3" % "logging-interceptor" % "3.14.7", + "com.squareup.okhttp3" % "okhttp" % "4.9.1", + "com.squareup.okhttp3" % "logging-interceptor" % "4.9.1", "com.google.code.gson" % "gson" % "2.8.6", "org.apache.commons" % "commons-lang3" % "3.10", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1", diff --git a/samples/client/petstore/java/okhttp-gson/build.sbt b/samples/client/petstore/java/okhttp-gson/build.sbt index ae1791028e0..6dfd0d7f733 100644 --- a/samples/client/petstore/java/okhttp-gson/build.sbt +++ b/samples/client/petstore/java/okhttp-gson/build.sbt @@ -10,8 +10,8 @@ lazy val root = (project in file(".")). resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.24", - "com.squareup.okhttp3" % "okhttp" % "3.14.7", - "com.squareup.okhttp3" % "logging-interceptor" % "3.14.7", + "com.squareup.okhttp3" % "okhttp" % "4.9.1", + "com.squareup.okhttp3" % "logging-interceptor" % "4.9.1", "com.google.code.gson" % "gson" % "2.8.6", "org.apache.commons" % "commons-lang3" % "3.10", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1", diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java index c8b45d5a903..b8a53e2f947 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java @@ -57,6 +57,9 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TimeZone; + +import javax.annotation.Nullable; + import java.time.OffsetDateTime; import org.openapitools.client.auth.Authentication; @@ -87,43 +90,56 @@ public class ApiClient extends JavaTimeFormatter { private final WebClient webClient; private final DateFormat dateFormat; + private final ObjectMapper objectMapper; private Map authentications; public ApiClient() { this.dateFormat = createDefaultDateFormat(); - ObjectMapper mapper = new ObjectMapper(); - mapper.setDateFormat(dateFormat); - mapper.registerModule(new JavaTimeModule()); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNullableModule jnm = new JsonNullableModule(); - mapper.registerModule(jnm); - - this.webClient = buildWebClient(mapper); + this.objectMapper = createDefaultObjectMapper(this.dateFormat); + this.webClient = buildWebClient(this.objectMapper); this.init(); } + public ApiClient(WebClient webClient) { + this(Optional.ofNullable(webClient).orElseGet(() -> buildWebClient()), createDefaultDateFormat()); + } + public ApiClient(ObjectMapper mapper, DateFormat format) { this(buildWebClient(mapper.copy()), format); } public ApiClient(WebClient webClient, ObjectMapper mapper, DateFormat format) { - this(Optional.ofNullable(webClient).orElseGet(() ->buildWebClient(mapper.copy())), format); + this(Optional.ofNullable(webClient).orElseGet(() -> buildWebClient(mapper.copy())), format); } private ApiClient(WebClient webClient, DateFormat format) { this.webClient = webClient; this.dateFormat = format; + this.objectMapper = createDefaultObjectMapper(format); this.init(); } - public DateFormat createDefaultDateFormat() { + public static DateFormat createDefaultDateFormat() { DateFormat dateFormat = new RFC3339DateFormat(); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat; } + public static ObjectMapper createDefaultObjectMapper(@Nullable DateFormat dateFormat) { + if (null == dateFormat) { + dateFormat = createDefaultDateFormat(); + } + ObjectMapper mapper = new ObjectMapper(); + mapper.setDateFormat(dateFormat); + mapper.registerModule(new JavaTimeModule()); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNullableModule jnm = new JsonNullableModule(); + mapper.registerModule(jnm); + return mapper; + } + protected void init() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); @@ -136,20 +152,45 @@ public class ApiClient extends JavaTimeFormatter { } /** - * Build the WebClient used to make HTTP requests. + * Build the WebClientBuilder used to make WebClient. + * @param mapper ObjectMapper used for serialize/deserialize * @return WebClient */ - public static WebClient buildWebClient(ObjectMapper mapper) { + public static WebClient.Builder buildWebClientBuilder(ObjectMapper mapper) { ExchangeStrategies strategies = ExchangeStrategies .builder() .codecs(clientDefaultCodecsConfigurer -> { clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(mapper, MediaType.APPLICATION_JSON)); clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(mapper, MediaType.APPLICATION_JSON)); }).build(); - WebClient.Builder webClient = WebClient.builder().exchangeStrategies(strategies); - return webClient.build(); + WebClient.Builder webClientBuilder = WebClient.builder().exchangeStrategies(strategies); + return webClientBuilder; } + /** + * Build the WebClientBuilder used to make WebClient. + * @return WebClient + */ + public static WebClient.Builder buildWebClientBuilder() { + return buildWebClientBuilder(createDefaultObjectMapper(null)); + } + + /** + * Build the WebClient used to make HTTP requests. + * @param mapper ObjectMapper used for serialize/deserialize + * @return WebClient + */ + public static WebClient buildWebClient(ObjectMapper mapper) { + return buildWebClientBuilder(mapper).build(); + } + + /** + * Build the WebClient used to make HTTP requests. + * @return WebClient + */ + public static WebClient buildWebClient() { + return buildWebClientBuilder(createDefaultObjectMapper(null)).build(); + } /** * Get the current base path @@ -337,6 +378,22 @@ public class ApiClient extends JavaTimeFormatter { return dateFormat.format(date); } + /** + * Get the ObjectMapper used to make HTTP requests. + * @return ObjectMapper objectMapper + */ + public ObjectMapper getObjectMapper() { + return objectMapper; + } + + /** + * Get the WebClient used to make HTTP requests. + * @return WebClient webClient + */ + public WebClient getWebClient() { + return webClient; + } + /** * Format the given parameter object into string. * @param param the object to convert @@ -640,10 +697,10 @@ public class ApiClient extends JavaTimeFormatter { } // collectionFormat is assumed to be "csv" by default - if(collectionFormat == null) { - collectionFormat = CollectionFormat.CSV; - } + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } - return collectionFormat.collectionToString(values); + return collectionFormat.collectionToString(values); } } diff --git a/samples/client/petstore/javascript-flowtyped/.openapi-generator/VERSION b/samples/client/petstore/javascript-flowtyped/.openapi-generator/VERSION index d99e7162d01..6555596f931 100644 --- a/samples/client/petstore/javascript-flowtyped/.openapi-generator/VERSION +++ b/samples/client/petstore/javascript-flowtyped/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/javascript-flowtyped/src/api.js b/samples/client/petstore/javascript-flowtyped/src/api.js index 7e681e862c7..bcf2a932d3b 100644 --- a/samples/client/petstore/javascript-flowtyped/src/api.js +++ b/samples/client/petstore/javascript-flowtyped/src/api.js @@ -46,7 +46,6 @@ export type FetchArgs = { options: {}; } - /** * * @export @@ -310,9 +309,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -350,9 +349,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -389,9 +388,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -428,9 +427,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -468,8 +467,8 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication api_key required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("api_key") - : configuration.apiKey; + ? configuration.apiKey("api_key") + : configuration.apiKey; localVarHeaderParameter["api_key"] = localVarApiKeyValue; } @@ -502,9 +501,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -543,9 +542,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -589,9 +588,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -765,6 +764,7 @@ export const PetApi = function(configuration?: Configuration, fetch: FetchAPI = } }; + /** * StoreApi - fetch parameter creator * @export @@ -813,8 +813,8 @@ export const StoreApiFetchParamCreator = function (configuration?: Configuration // authentication api_key required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("api_key") - : configuration.apiKey; + ? configuration.apiKey("api_key") + : configuration.apiKey; localVarHeaderParameter["api_key"] = localVarApiKeyValue; } @@ -968,6 +968,7 @@ export const StoreApi = function(configuration?: Configuration, fetch: FetchAPI } }; + /** * UserApi - fetch parameter creator * @export @@ -1364,6 +1365,7 @@ export const UserApi = function(configuration?: Configuration, fetch: FetchAPI = } }; + export type ApiTypes = { PetApi: PetApiType, diff --git a/samples/client/petstore/kotlin-json-request-string/build.gradle b/samples/client/petstore/kotlin-json-request-string/build.gradle index 60e5056e031..4e47e29cc51 100644 --- a/samples/client/petstore/kotlin-json-request-string/build.gradle +++ b/samples/client/petstore/kotlin-json-request-string/build.gradle @@ -18,6 +18,7 @@ buildscript { } apply plugin: 'kotlin' +apply plugin: 'kotlin-parcelize' repositories { maven { url "https://repo1.maven.org/maven2" } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt index fafca8738f6..5e349f9f96e 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt @@ -13,6 +13,8 @@ package org.openapitools.client.models import com.squareup.moshi.Json +import android.os.Parcelable +import kotlinx.parcelize.Parcelize /** * Describes the result of uploading an image resource @@ -20,6 +22,7 @@ import com.squareup.moshi.Json * @param type * @param message */ +@Parcelize data class ApiResponse ( @Json(name = "code") @@ -28,5 +31,5 @@ data class ApiResponse ( val type: kotlin.String? = null, @Json(name = "message") val message: kotlin.String? = null -) +) : Parcelable diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Category.kt index a4c17c3b49d..38cc2226846 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -13,17 +13,20 @@ package org.openapitools.client.models import com.squareup.moshi.Json +import android.os.Parcelable +import kotlinx.parcelize.Parcelize /** * A category for a pet * @param id * @param name */ +@Parcelize data class Category ( @Json(name = "id") val id: kotlin.Long? = null, @Json(name = "name") val name: kotlin.String? = null -) +) : Parcelable diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Order.kt index 2bdaec85131..7e9d9fc4644 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -13,6 +13,8 @@ package org.openapitools.client.models import com.squareup.moshi.Json +import android.os.Parcelable +import kotlinx.parcelize.Parcelize /** * An order for a pets from the pet store @@ -23,6 +25,7 @@ import com.squareup.moshi.Json * @param status Order Status * @param complete */ +@Parcelize data class Order ( @Json(name = "id") @@ -38,7 +41,7 @@ data class Order ( val status: Order.Status? = null, @Json(name = "complete") val complete: kotlin.Boolean? = null -) { +) : Parcelable { /** * Order Status diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Pet.kt index 0e38da34b79..35de5ef28a2 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -15,6 +15,8 @@ import org.openapitools.client.models.Category import org.openapitools.client.models.Tag import com.squareup.moshi.Json +import android.os.Parcelable +import kotlinx.parcelize.Parcelize /** * A pet for sale in the pet store @@ -25,6 +27,7 @@ import com.squareup.moshi.Json * @param tags * @param status pet status in the store */ +@Parcelize data class Pet ( @Json(name = "name") @@ -40,7 +43,7 @@ data class Pet ( /* pet status in the store */ @Json(name = "status") val status: Pet.Status? = null -) { +) : Parcelable { /** * pet status in the store diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Tag.kt index 6e619023a5c..dc72586b991 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -13,17 +13,20 @@ package org.openapitools.client.models import com.squareup.moshi.Json +import android.os.Parcelable +import kotlinx.parcelize.Parcelize /** * A tag for a pet * @param id * @param name */ +@Parcelize data class Tag ( @Json(name = "id") val id: kotlin.Long? = null, @Json(name = "name") val name: kotlin.String? = null -) +) : Parcelable diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/User.kt index af1e270325d..9a840f06e7f 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/User.kt @@ -13,6 +13,8 @@ package org.openapitools.client.models import com.squareup.moshi.Json +import android.os.Parcelable +import kotlinx.parcelize.Parcelize /** * A User who is purchasing from the pet store @@ -25,6 +27,7 @@ import com.squareup.moshi.Json * @param phone * @param userStatus User Status */ +@Parcelize data class User ( @Json(name = "id") @@ -44,5 +47,5 @@ data class User ( /* User Status */ @Json(name = "userStatus") val userStatus: kotlin.Int? = null -) +) : Parcelable diff --git a/samples/client/petstore/nim/petstore/apis/api_pet.nim b/samples/client/petstore/nim/petstore/apis/api_pet.nim index 3644e392340..b2f77c2bdbb 100644 --- a/samples/client/petstore/nim/petstore/apis/api_pet.nim +++ b/samples/client/petstore/nim/petstore/apis/api_pet.nim @@ -39,10 +39,12 @@ template constructResult[T](response: Response): untyped = (none(T.typedesc), response) -proc addPet*(httpClient: HttpClient, body: Pet): Response = +proc addPet*(httpClient: HttpClient, pet: Pet): (Option[Pet], Response) = ## Add a new pet to the store httpClient.headers["Content-Type"] = "application/json" - httpClient.post(basepath & "/pet", $(%body)) + + let response = httpClient.post(basepath & "/pet", $(%pet)) + constructResult[Pet](response) proc deletePet*(httpClient: HttpClient, petId: int64, apiKey: string): Response = @@ -78,10 +80,12 @@ proc getPetById*(httpClient: HttpClient, petId: int64): (Option[Pet], Response) constructResult[Pet](response) -proc updatePet*(httpClient: HttpClient, body: Pet): Response = +proc updatePet*(httpClient: HttpClient, pet: Pet): (Option[Pet], Response) = ## Update an existing pet httpClient.headers["Content-Type"] = "application/json" - httpClient.put(basepath & "/pet", $(%body)) + + let response = httpClient.put(basepath & "/pet", $(%pet)) + constructResult[Pet](response) proc updatePetWithForm*(httpClient: HttpClient, petId: int64, name: string, status: string): Response = diff --git a/samples/client/petstore/nim/petstore/apis/api_store.nim b/samples/client/petstore/nim/petstore/apis/api_store.nim index 3c518e8dd31..a2f018b7cf3 100644 --- a/samples/client/petstore/nim/petstore/apis/api_store.nim +++ b/samples/client/petstore/nim/petstore/apis/api_store.nim @@ -57,10 +57,10 @@ proc getOrderById*(httpClient: HttpClient, orderId: int64): (Option[Order], Resp constructResult[Order](response) -proc placeOrder*(httpClient: HttpClient, body: Order): (Option[Order], Response) = +proc placeOrder*(httpClient: HttpClient, order: Order): (Option[Order], Response) = ## Place an order for a pet httpClient.headers["Content-Type"] = "application/json" - let response = httpClient.post(basepath & "/store/order", $(%body)) + let response = httpClient.post(basepath & "/store/order", $(%order)) constructResult[Order](response) diff --git a/samples/client/petstore/nim/petstore/apis/api_user.nim b/samples/client/petstore/nim/petstore/apis/api_user.nim index 87bef06818e..618477db595 100644 --- a/samples/client/petstore/nim/petstore/apis/api_user.nim +++ b/samples/client/petstore/nim/petstore/apis/api_user.nim @@ -38,22 +38,22 @@ template constructResult[T](response: Response): untyped = (none(T.typedesc), response) -proc createUser*(httpClient: HttpClient, body: User): Response = +proc createUser*(httpClient: HttpClient, user: User): Response = ## Create user httpClient.headers["Content-Type"] = "application/json" - httpClient.post(basepath & "/user", $(%body)) + httpClient.post(basepath & "/user", $(%user)) -proc createUsersWithArrayInput*(httpClient: HttpClient, body: seq[User]): Response = +proc createUsersWithArrayInput*(httpClient: HttpClient, user: seq[User]): Response = ## Creates list of users with given input array httpClient.headers["Content-Type"] = "application/json" - httpClient.post(basepath & "/user/createWithArray", $(%body)) + httpClient.post(basepath & "/user/createWithArray", $(%user)) -proc createUsersWithListInput*(httpClient: HttpClient, body: seq[User]): Response = +proc createUsersWithListInput*(httpClient: HttpClient, user: seq[User]): Response = ## Creates list of users with given input array httpClient.headers["Content-Type"] = "application/json" - httpClient.post(basepath & "/user/createWithList", $(%body)) + httpClient.post(basepath & "/user/createWithList", $(%user)) proc deleteUser*(httpClient: HttpClient, username: string): Response = @@ -84,8 +84,8 @@ proc logoutUser*(httpClient: HttpClient): Response = httpClient.get(basepath & "/user/logout") -proc updateUser*(httpClient: HttpClient, username: string, body: User): Response = +proc updateUser*(httpClient: HttpClient, username: string, user: User): Response = ## Updated user httpClient.headers["Content-Type"] = "application/json" - httpClient.put(basepath & fmt"/user/{username}", $(%body)) + httpClient.put(basepath & fmt"/user/{username}", $(%user)) diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_any_type.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_any_type.py index 30e6e9b8176..01457faa3a3 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_any_type.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_any_type.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesAnyType(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_array.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_array.py index 2f939711e0a..c7283e16136 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_array.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_array.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesArray(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_boolean.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_boolean.py index 32b58c24ffa..3a8ec8f66aa 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_boolean.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_boolean.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesBoolean(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_class.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_class.py index dff68969974..52c475c4460 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_class.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -339,7 +342,7 @@ class AdditionalPropertiesClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_integer.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_integer.py index bba82b9c8cf..d9ee889d7a3 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_integer.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_integer.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesInteger(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_number.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_number.py index 9adeedb7e79..756fc037970 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_number.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_number.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesNumber(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_object.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_object.py index 85f94ac205d..bfbe2db1bef 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_object.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_object.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesObject(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_string.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_string.py index ee8d6383348..7c33a16fe8f 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_string.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_string.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesString(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/animal.py b/samples/client/petstore/python-asyncio/petstore_api/models/animal.py index a791a5173ba..eee29f37f88 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/animal.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/animal.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -118,7 +121,7 @@ class Animal(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/api_response.py b/samples/client/petstore/python-asyncio/petstore_api/models/api_response.py index ab5e7999dd2..bddac1eb10a 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/api_response.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/api_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class ApiResponse(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/array_of_array_of_number_only.py b/samples/client/petstore/python-asyncio/petstore_api/models/array_of_array_of_number_only.py index c9b65c7e531..2975adc20e3 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/array_of_array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ArrayOfArrayOfNumberOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/array_of_number_only.py b/samples/client/petstore/python-asyncio/petstore_api/models/array_of_number_only.py index 870286e0fc0..2a3400e7666 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/array_of_number_only.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ArrayOfNumberOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/array_test.py b/samples/client/petstore/python-asyncio/petstore_api/models/array_test.py index 04d2cb6ec60..11394dcb7bc 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/array_test.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/array_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class ArrayTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/big_cat.py b/samples/client/petstore/python-asyncio/petstore_api/models/big_cat.py index 7136aa86720..9a108ce3717 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/big_cat.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/big_cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -85,7 +88,7 @@ class BigCat(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/big_cat_all_of.py b/samples/client/petstore/python-asyncio/petstore_api/models/big_cat_all_of.py index 127e7c6da31..6d6c9aeb5c0 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/big_cat_all_of.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/big_cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -85,7 +88,7 @@ class BigCatAllOf(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/capitalization.py b/samples/client/petstore/python-asyncio/petstore_api/models/capitalization.py index 064dc2eb2ff..cb8b0d98584 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/capitalization.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/capitalization.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -211,7 +214,7 @@ class Capitalization(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/cat.py b/samples/client/petstore/python-asyncio/petstore_api/models/cat.py index 3b6e6aa4c2e..0d9a0b20bf1 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/cat.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class Cat(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/cat_all_of.py b/samples/client/petstore/python-asyncio/petstore_api/models/cat_all_of.py index 7755fd65b0c..0633bbf58d0 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/cat_all_of.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class CatAllOf(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/category.py b/samples/client/petstore/python-asyncio/petstore_api/models/category.py index c3dd5a4b9a1..ef52dcbf8c9 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/category.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/category.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -106,7 +109,7 @@ class Category(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/class_model.py b/samples/client/petstore/python-asyncio/petstore_api/models/class_model.py index cd9439763d2..84c0de65b47 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/class_model.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/class_model.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ClassModel(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/client.py b/samples/client/petstore/python-asyncio/petstore_api/models/client.py index f896b35240c..8d7c83ecfe6 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/client.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/client.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class Client(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/dog.py b/samples/client/petstore/python-asyncio/petstore_api/models/dog.py index 39514284d5f..61acd35cdfe 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/dog.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/dog.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class Dog(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/dog_all_of.py b/samples/client/petstore/python-asyncio/petstore_api/models/dog_all_of.py index 207103a4874..3a052c3258a 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/dog_all_of.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/dog_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class DogAllOf(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/enum_arrays.py b/samples/client/petstore/python-asyncio/petstore_api/models/enum_arrays.py index b87cd37456e..eb4f3ea4ca3 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/enum_arrays.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -119,7 +122,7 @@ class EnumArrays(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/enum_class.py b/samples/client/petstore/python-asyncio/petstore_api/models/enum_class.py index 4b11877863a..79aac3570cb 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/enum_class.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/enum_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ class EnumClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/enum_test.py b/samples/client/petstore/python-asyncio/petstore_api/models/enum_test.py index d1778410dee..1f3d7cb29b8 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/enum_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -208,7 +211,7 @@ class EnumTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/file.py b/samples/client/petstore/python-asyncio/petstore_api/models/file.py index e40cd04b014..2c1cccac0e1 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/file.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/file.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -81,7 +84,7 @@ class File(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/file_schema_test_class.py b/samples/client/petstore/python-asyncio/petstore_api/models/file_schema_test_class.py index d266755d260..c5a23842d4f 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/file_schema_test_class.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/file_schema_test_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class FileSchemaTestClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/format_test.py b/samples/client/petstore/python-asyncio/petstore_api/models/format_test.py index c193f9313e9..452582251a5 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/format_test.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/format_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -463,7 +466,7 @@ class FormatTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/has_only_read_only.py b/samples/client/petstore/python-asyncio/petstore_api/models/has_only_read_only.py index dac8cfaff93..7175c2acc72 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/has_only_read_only.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/has_only_read_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class HasOnlyReadOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/list.py b/samples/client/petstore/python-asyncio/petstore_api/models/list.py index b4425722474..6e1dea4e33b 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/list.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/list.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class List(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/map_test.py b/samples/client/petstore/python-asyncio/petstore_api/models/map_test.py index 406f35db750..21bd2ccda98 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/map_test.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/map_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -165,7 +168,7 @@ class MapTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-asyncio/petstore_api/models/mixed_properties_and_additional_properties_class.py index 14428a6536a..9e727b07d5c 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/model200_response.py b/samples/client/petstore/python-asyncio/petstore_api/models/model200_response.py index 5c90147467b..db587fd24e2 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/model200_response.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/model200_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class Model200Response(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/model_return.py b/samples/client/petstore/python-asyncio/petstore_api/models/model_return.py index 88174ef2308..5354fd56e2c 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/model_return.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/model_return.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ModelReturn(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/name.py b/samples/client/petstore/python-asyncio/petstore_api/models/name.py index 528988ebd43..0191a3a934a 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/name.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -158,7 +161,7 @@ class Name(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/number_only.py b/samples/client/petstore/python-asyncio/petstore_api/models/number_only.py index ebbcc8996d0..59a252e0bb6 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/number_only.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class NumberOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/order.py b/samples/client/petstore/python-asyncio/petstore_api/models/order.py index 6513d48a3a5..a267324d0d1 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/order.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/order.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -217,7 +220,7 @@ class Order(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/outer_composite.py b/samples/client/petstore/python-asyncio/petstore_api/models/outer_composite.py index 44124e13c09..e26160ab430 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/outer_composite.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/outer_composite.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class OuterComposite(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/outer_enum.py b/samples/client/petstore/python-asyncio/petstore_api/models/outer_enum.py index 77624ba1540..27cdfd1fb79 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/outer_enum.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/outer_enum.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ class OuterEnum(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/pet.py b/samples/client/petstore/python-asyncio/petstore_api/models/pet.py index e71589429ca..22bb4a585e4 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/pet.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/pet.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -219,7 +222,7 @@ class Pet(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/read_only_first.py b/samples/client/petstore/python-asyncio/petstore_api/models/read_only_first.py index 3a320fe64f0..c2888eba750 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/read_only_first.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/read_only_first.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class ReadOnlyFirst(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/special_model_name.py b/samples/client/petstore/python-asyncio/petstore_api/models/special_model_name.py index 7669a508789..4c848e1887c 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/special_model_name.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/special_model_name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class SpecialModelName(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/tag.py b/samples/client/petstore/python-asyncio/petstore_api/models/tag.py index dbac885ad8e..a3e6789078d 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/tag.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/tag.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class Tag(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_default.py b/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_default.py index c890f553192..582b4c8d6dc 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_default.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_default.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -188,7 +191,7 @@ class TypeHolderDefault(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_example.py b/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_example.py index d52425d442e..268595ed868 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_example.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_example.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -215,7 +218,7 @@ class TypeHolderExample(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/user.py b/samples/client/petstore/python-asyncio/petstore_api/models/user.py index b70d84a6b40..7ae2898f6c5 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/user.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/user.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -263,7 +266,7 @@ class User(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/xml_item.py b/samples/client/petstore/python-asyncio/petstore_api/models/xml_item.py index d63ab77acfd..5e6fecdd71c 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/xml_item.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/xml_item.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -807,7 +810,7 @@ class XmlItem(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_any_type.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_any_type.py index 30e6e9b8176..01457faa3a3 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_any_type.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_any_type.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesAnyType(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_array.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_array.py index 2f939711e0a..c7283e16136 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_array.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_array.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesArray(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_boolean.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_boolean.py index 32b58c24ffa..3a8ec8f66aa 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_boolean.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_boolean.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesBoolean(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py index dff68969974..52c475c4460 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -339,7 +342,7 @@ class AdditionalPropertiesClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_integer.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_integer.py index bba82b9c8cf..d9ee889d7a3 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_integer.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_integer.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesInteger(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_number.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_number.py index 9adeedb7e79..756fc037970 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_number.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_number.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesNumber(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_object.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_object.py index 85f94ac205d..bfbe2db1bef 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_object.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_object.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesObject(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_string.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_string.py index ee8d6383348..7c33a16fe8f 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_string.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_string.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesString(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/animal.py b/samples/client/petstore/python-legacy/petstore_api/models/animal.py index a791a5173ba..eee29f37f88 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/animal.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/animal.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -118,7 +121,7 @@ class Animal(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/api_response.py b/samples/client/petstore/python-legacy/petstore_api/models/api_response.py index ab5e7999dd2..bddac1eb10a 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/api_response.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/api_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class ApiResponse(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py b/samples/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py index c9b65c7e531..2975adc20e3 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ArrayOfArrayOfNumberOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py b/samples/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py index 870286e0fc0..2a3400e7666 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ArrayOfNumberOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/array_test.py b/samples/client/petstore/python-legacy/petstore_api/models/array_test.py index 04d2cb6ec60..11394dcb7bc 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/array_test.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/array_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class ArrayTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/big_cat.py b/samples/client/petstore/python-legacy/petstore_api/models/big_cat.py index 7136aa86720..9a108ce3717 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/big_cat.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/big_cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -85,7 +88,7 @@ class BigCat(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/big_cat_all_of.py b/samples/client/petstore/python-legacy/petstore_api/models/big_cat_all_of.py index 127e7c6da31..6d6c9aeb5c0 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/big_cat_all_of.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/big_cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -85,7 +88,7 @@ class BigCatAllOf(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/capitalization.py b/samples/client/petstore/python-legacy/petstore_api/models/capitalization.py index 064dc2eb2ff..cb8b0d98584 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/capitalization.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/capitalization.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -211,7 +214,7 @@ class Capitalization(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/cat.py b/samples/client/petstore/python-legacy/petstore_api/models/cat.py index 3b6e6aa4c2e..0d9a0b20bf1 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/cat.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class Cat(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/cat_all_of.py b/samples/client/petstore/python-legacy/petstore_api/models/cat_all_of.py index 7755fd65b0c..0633bbf58d0 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/cat_all_of.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class CatAllOf(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/category.py b/samples/client/petstore/python-legacy/petstore_api/models/category.py index c3dd5a4b9a1..ef52dcbf8c9 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/category.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/category.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -106,7 +109,7 @@ class Category(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/class_model.py b/samples/client/petstore/python-legacy/petstore_api/models/class_model.py index cd9439763d2..84c0de65b47 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/class_model.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/class_model.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ClassModel(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/client.py b/samples/client/petstore/python-legacy/petstore_api/models/client.py index f896b35240c..8d7c83ecfe6 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/client.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/client.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class Client(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/dog.py b/samples/client/petstore/python-legacy/petstore_api/models/dog.py index 39514284d5f..61acd35cdfe 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/dog.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/dog.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class Dog(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/dog_all_of.py b/samples/client/petstore/python-legacy/petstore_api/models/dog_all_of.py index 207103a4874..3a052c3258a 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/dog_all_of.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/dog_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class DogAllOf(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/enum_arrays.py b/samples/client/petstore/python-legacy/petstore_api/models/enum_arrays.py index b87cd37456e..eb4f3ea4ca3 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/enum_arrays.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -119,7 +122,7 @@ class EnumArrays(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/enum_class.py b/samples/client/petstore/python-legacy/petstore_api/models/enum_class.py index 4b11877863a..79aac3570cb 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/enum_class.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/enum_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ class EnumClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/enum_test.py b/samples/client/petstore/python-legacy/petstore_api/models/enum_test.py index d1778410dee..1f3d7cb29b8 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/enum_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -208,7 +211,7 @@ class EnumTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/file.py b/samples/client/petstore/python-legacy/petstore_api/models/file.py index e40cd04b014..2c1cccac0e1 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/file.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/file.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -81,7 +84,7 @@ class File(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py b/samples/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py index d266755d260..c5a23842d4f 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class FileSchemaTestClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/format_test.py b/samples/client/petstore/python-legacy/petstore_api/models/format_test.py index c193f9313e9..452582251a5 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/format_test.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/format_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -463,7 +466,7 @@ class FormatTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py b/samples/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py index dac8cfaff93..7175c2acc72 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class HasOnlyReadOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/list.py b/samples/client/petstore/python-legacy/petstore_api/models/list.py index b4425722474..6e1dea4e33b 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/list.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/list.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class List(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/map_test.py b/samples/client/petstore/python-legacy/petstore_api/models/map_test.py index 406f35db750..21bd2ccda98 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/map_test.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/map_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -165,7 +168,7 @@ class MapTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py index 14428a6536a..9e727b07d5c 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/model200_response.py b/samples/client/petstore/python-legacy/petstore_api/models/model200_response.py index 5c90147467b..db587fd24e2 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/model200_response.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/model200_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class Model200Response(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/model_return.py b/samples/client/petstore/python-legacy/petstore_api/models/model_return.py index 88174ef2308..5354fd56e2c 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/model_return.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/model_return.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ModelReturn(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/name.py b/samples/client/petstore/python-legacy/petstore_api/models/name.py index 528988ebd43..0191a3a934a 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/name.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -158,7 +161,7 @@ class Name(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/number_only.py b/samples/client/petstore/python-legacy/petstore_api/models/number_only.py index ebbcc8996d0..59a252e0bb6 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/number_only.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class NumberOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/order.py b/samples/client/petstore/python-legacy/petstore_api/models/order.py index 6513d48a3a5..a267324d0d1 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/order.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/order.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -217,7 +220,7 @@ class Order(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/outer_composite.py b/samples/client/petstore/python-legacy/petstore_api/models/outer_composite.py index 44124e13c09..e26160ab430 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/outer_composite.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/outer_composite.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class OuterComposite(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/outer_enum.py b/samples/client/petstore/python-legacy/petstore_api/models/outer_enum.py index 77624ba1540..27cdfd1fb79 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/outer_enum.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/outer_enum.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ class OuterEnum(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/pet.py b/samples/client/petstore/python-legacy/petstore_api/models/pet.py index e71589429ca..22bb4a585e4 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/pet.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/pet.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -219,7 +222,7 @@ class Pet(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/read_only_first.py b/samples/client/petstore/python-legacy/petstore_api/models/read_only_first.py index 3a320fe64f0..c2888eba750 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/read_only_first.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/read_only_first.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class ReadOnlyFirst(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/special_model_name.py b/samples/client/petstore/python-legacy/petstore_api/models/special_model_name.py index 7669a508789..4c848e1887c 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/special_model_name.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/special_model_name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class SpecialModelName(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/tag.py b/samples/client/petstore/python-legacy/petstore_api/models/tag.py index dbac885ad8e..a3e6789078d 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/tag.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/tag.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class Tag(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/type_holder_default.py b/samples/client/petstore/python-legacy/petstore_api/models/type_holder_default.py index c890f553192..582b4c8d6dc 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/type_holder_default.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/type_holder_default.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -188,7 +191,7 @@ class TypeHolderDefault(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/type_holder_example.py b/samples/client/petstore/python-legacy/petstore_api/models/type_holder_example.py index d52425d442e..268595ed868 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/type_holder_example.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/type_holder_example.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -215,7 +218,7 @@ class TypeHolderExample(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/user.py b/samples/client/petstore/python-legacy/petstore_api/models/user.py index b70d84a6b40..7ae2898f6c5 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/user.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/user.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -263,7 +266,7 @@ class User(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/xml_item.py b/samples/client/petstore/python-legacy/petstore_api/models/xml_item.py index d63ab77acfd..5e6fecdd71c 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/xml_item.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/xml_item.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -807,7 +810,7 @@ class XmlItem(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_any_type.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_any_type.py index 30e6e9b8176..01457faa3a3 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_any_type.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_any_type.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesAnyType(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_array.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_array.py index 2f939711e0a..c7283e16136 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_array.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_array.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesArray(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_boolean.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_boolean.py index 32b58c24ffa..3a8ec8f66aa 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_boolean.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_boolean.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesBoolean(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_class.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_class.py index dff68969974..52c475c4460 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_class.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -339,7 +342,7 @@ class AdditionalPropertiesClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_integer.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_integer.py index bba82b9c8cf..d9ee889d7a3 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_integer.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_integer.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesInteger(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_number.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_number.py index 9adeedb7e79..756fc037970 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_number.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_number.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesNumber(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_object.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_object.py index 85f94ac205d..bfbe2db1bef 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_object.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_object.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesObject(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_string.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_string.py index ee8d6383348..7c33a16fe8f 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_string.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_string.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class AdditionalPropertiesString(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/animal.py b/samples/client/petstore/python-tornado/petstore_api/models/animal.py index a791a5173ba..eee29f37f88 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/animal.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/animal.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -118,7 +121,7 @@ class Animal(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/api_response.py b/samples/client/petstore/python-tornado/petstore_api/models/api_response.py index ab5e7999dd2..bddac1eb10a 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/api_response.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/api_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class ApiResponse(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/array_of_array_of_number_only.py b/samples/client/petstore/python-tornado/petstore_api/models/array_of_array_of_number_only.py index c9b65c7e531..2975adc20e3 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/array_of_array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ArrayOfArrayOfNumberOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/array_of_number_only.py b/samples/client/petstore/python-tornado/petstore_api/models/array_of_number_only.py index 870286e0fc0..2a3400e7666 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/array_of_number_only.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ArrayOfNumberOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/array_test.py b/samples/client/petstore/python-tornado/petstore_api/models/array_test.py index 04d2cb6ec60..11394dcb7bc 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/array_test.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/array_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class ArrayTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/big_cat.py b/samples/client/petstore/python-tornado/petstore_api/models/big_cat.py index 7136aa86720..9a108ce3717 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/big_cat.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/big_cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -85,7 +88,7 @@ class BigCat(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/big_cat_all_of.py b/samples/client/petstore/python-tornado/petstore_api/models/big_cat_all_of.py index 127e7c6da31..6d6c9aeb5c0 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/big_cat_all_of.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/big_cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -85,7 +88,7 @@ class BigCatAllOf(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/capitalization.py b/samples/client/petstore/python-tornado/petstore_api/models/capitalization.py index 064dc2eb2ff..cb8b0d98584 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/capitalization.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/capitalization.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -211,7 +214,7 @@ class Capitalization(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/cat.py b/samples/client/petstore/python-tornado/petstore_api/models/cat.py index 3b6e6aa4c2e..0d9a0b20bf1 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/cat.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class Cat(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/cat_all_of.py b/samples/client/petstore/python-tornado/petstore_api/models/cat_all_of.py index 7755fd65b0c..0633bbf58d0 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/cat_all_of.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class CatAllOf(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/category.py b/samples/client/petstore/python-tornado/petstore_api/models/category.py index c3dd5a4b9a1..ef52dcbf8c9 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/category.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/category.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -106,7 +109,7 @@ class Category(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/class_model.py b/samples/client/petstore/python-tornado/petstore_api/models/class_model.py index cd9439763d2..84c0de65b47 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/class_model.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/class_model.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ClassModel(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/client.py b/samples/client/petstore/python-tornado/petstore_api/models/client.py index f896b35240c..8d7c83ecfe6 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/client.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/client.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class Client(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/dog.py b/samples/client/petstore/python-tornado/petstore_api/models/dog.py index 39514284d5f..61acd35cdfe 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/dog.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/dog.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class Dog(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/dog_all_of.py b/samples/client/petstore/python-tornado/petstore_api/models/dog_all_of.py index 207103a4874..3a052c3258a 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/dog_all_of.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/dog_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class DogAllOf(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/enum_arrays.py b/samples/client/petstore/python-tornado/petstore_api/models/enum_arrays.py index b87cd37456e..eb4f3ea4ca3 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/enum_arrays.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -119,7 +122,7 @@ class EnumArrays(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/enum_class.py b/samples/client/petstore/python-tornado/petstore_api/models/enum_class.py index 4b11877863a..79aac3570cb 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/enum_class.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/enum_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ class EnumClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/enum_test.py b/samples/client/petstore/python-tornado/petstore_api/models/enum_test.py index d1778410dee..1f3d7cb29b8 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/enum_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -208,7 +211,7 @@ class EnumTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/file.py b/samples/client/petstore/python-tornado/petstore_api/models/file.py index e40cd04b014..2c1cccac0e1 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/file.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/file.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -81,7 +84,7 @@ class File(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/file_schema_test_class.py b/samples/client/petstore/python-tornado/petstore_api/models/file_schema_test_class.py index d266755d260..c5a23842d4f 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/file_schema_test_class.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/file_schema_test_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class FileSchemaTestClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/format_test.py b/samples/client/petstore/python-tornado/petstore_api/models/format_test.py index c193f9313e9..452582251a5 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/format_test.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/format_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -463,7 +466,7 @@ class FormatTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/has_only_read_only.py b/samples/client/petstore/python-tornado/petstore_api/models/has_only_read_only.py index dac8cfaff93..7175c2acc72 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/has_only_read_only.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/has_only_read_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class HasOnlyReadOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/list.py b/samples/client/petstore/python-tornado/petstore_api/models/list.py index b4425722474..6e1dea4e33b 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/list.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/list.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class List(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/map_test.py b/samples/client/petstore/python-tornado/petstore_api/models/map_test.py index 406f35db750..21bd2ccda98 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/map_test.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/map_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -165,7 +168,7 @@ class MapTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-tornado/petstore_api/models/mixed_properties_and_additional_properties_class.py index 14428a6536a..9e727b07d5c 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/model200_response.py b/samples/client/petstore/python-tornado/petstore_api/models/model200_response.py index 5c90147467b..db587fd24e2 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/model200_response.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/model200_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class Model200Response(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/model_return.py b/samples/client/petstore/python-tornado/petstore_api/models/model_return.py index 88174ef2308..5354fd56e2c 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/model_return.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/model_return.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ModelReturn(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/name.py b/samples/client/petstore/python-tornado/petstore_api/models/name.py index 528988ebd43..0191a3a934a 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/name.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -158,7 +161,7 @@ class Name(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/number_only.py b/samples/client/petstore/python-tornado/petstore_api/models/number_only.py index ebbcc8996d0..59a252e0bb6 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/number_only.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class NumberOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/order.py b/samples/client/petstore/python-tornado/petstore_api/models/order.py index 6513d48a3a5..a267324d0d1 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/order.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/order.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -217,7 +220,7 @@ class Order(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/outer_composite.py b/samples/client/petstore/python-tornado/petstore_api/models/outer_composite.py index 44124e13c09..e26160ab430 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/outer_composite.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/outer_composite.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class OuterComposite(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/outer_enum.py b/samples/client/petstore/python-tornado/petstore_api/models/outer_enum.py index 77624ba1540..27cdfd1fb79 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/outer_enum.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/outer_enum.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ class OuterEnum(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/pet.py b/samples/client/petstore/python-tornado/petstore_api/models/pet.py index e71589429ca..22bb4a585e4 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/pet.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/pet.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -219,7 +222,7 @@ class Pet(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/read_only_first.py b/samples/client/petstore/python-tornado/petstore_api/models/read_only_first.py index 3a320fe64f0..c2888eba750 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/read_only_first.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/read_only_first.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class ReadOnlyFirst(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/special_model_name.py b/samples/client/petstore/python-tornado/petstore_api/models/special_model_name.py index 7669a508789..4c848e1887c 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/special_model_name.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/special_model_name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class SpecialModelName(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/tag.py b/samples/client/petstore/python-tornado/petstore_api/models/tag.py index dbac885ad8e..a3e6789078d 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/tag.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/tag.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class Tag(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/type_holder_default.py b/samples/client/petstore/python-tornado/petstore_api/models/type_holder_default.py index c890f553192..582b4c8d6dc 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/type_holder_default.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/type_holder_default.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -188,7 +191,7 @@ class TypeHolderDefault(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/type_holder_example.py b/samples/client/petstore/python-tornado/petstore_api/models/type_holder_example.py index d52425d442e..268595ed868 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/type_holder_example.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/type_holder_example.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -215,7 +218,7 @@ class TypeHolderExample(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/user.py b/samples/client/petstore/python-tornado/petstore_api/models/user.py index b70d84a6b40..7ae2898f6c5 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/user.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/user.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -263,7 +266,7 @@ class User(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/xml_item.py b/samples/client/petstore/python-tornado/petstore_api/models/xml_item.py index d63ab77acfd..5e6fecdd71c 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/xml_item.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/xml_item.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -807,7 +810,7 @@ class XmlItem(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py b/samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py index 7239795cf4a..34ae88833fb 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesAnyType(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesAnyType(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesAnyType - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesAnyType(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_array.py b/samples/client/petstore/python/petstore_api/model/additional_properties_array.py index 7d9403758a0..55f44f411c2 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_array.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_array.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesArray(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesArray(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesArray - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesArray(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py b/samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py index ca129b766ec..b9c5c258e3c 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesBoolean(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesBoolean(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesBoolean - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesBoolean(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_class.py b/samples/client/petstore/python/petstore_api/model/additional_properties_class.py index 39719e00dcf..7e4d3d93c5f 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_class.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_class.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesClass(ModelNormal): @@ -110,8 +113,95 @@ class AdditionalPropertiesClass(ModelNormal): 'anytype_3': 'anytype_3', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_string ({str: (str,)}): [optional] # noqa: E501 + map_number ({str: (float,)}): [optional] # noqa: E501 + map_integer ({str: (int,)}): [optional] # noqa: E501 + map_boolean ({str: (bool,)}): [optional] # noqa: E501 + map_array_integer ({str: ([int],)}): [optional] # noqa: E501 + map_array_anytype ({str: ([bool, date, datetime, dict, float, int, list, str, none_type],)}): [optional] # noqa: E501 + map_map_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_map_anytype ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type,)},)}): [optional] # noqa: E501 + anytype_1 (bool, date, datetime, dict, float, int, list, str, none_type): [optional] # noqa: E501 + anytype_2 (bool, date, datetime, dict, float, int, list, str, none_type): no type is set for this. [optional] # noqa: E501 + anytype_3 (bool, date, datetime, dict, float, int, list, str, none_type): because of a bug in swagger-parser, this should have values {str: (str, int, float...)} but instead we get any type. See https://github.com/swagger-api/swagger-parser/issues/1378. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -200,3 +290,6 @@ class AdditionalPropertiesClass(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_integer.py b/samples/client/petstore/python/petstore_api/model/additional_properties_integer.py index 87d78bf3600..f6f80f89c7a 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_integer.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_integer.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesInteger(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesInteger(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesInteger - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesInteger(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_number.py b/samples/client/petstore/python/petstore_api/model/additional_properties_number.py index b10bd036ff3..6c094699462 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_number.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_number.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesNumber(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesNumber(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesNumber - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesNumber(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_object.py b/samples/client/petstore/python/petstore_api/model/additional_properties_object.py index 000653f13a7..1fa671aff9b 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_object.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_object.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesObject(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesObject(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesObject - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesObject(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_string.py b/samples/client/petstore/python/petstore_api/model/additional_properties_string.py index 7f1f94aa6b6..0afa8a9e637 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_string.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_string.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesString(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesString(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesString - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesString(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/animal.py b/samples/client/petstore/python/petstore_api/model/animal.py index c53b1e1ad28..fda6c283ebd 100644 --- a/samples/client/petstore/python/petstore_api/model/animal.py +++ b/samples/client/petstore/python/petstore_api/model/animal.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.cat import Cat @@ -106,8 +109,89 @@ class Animal(ModelNormal): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """Animal - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -190,3 +274,6 @@ class Animal(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/animal_farm.py b/samples/client/petstore/python/petstore_api/model/animal_farm.py index fb58224ebd4..59bde51a290 100644 --- a/samples/client/petstore/python/petstore_api/model/animal_farm.py +++ b/samples/client/petstore/python/petstore_api/model/animal_farm.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -90,6 +93,8 @@ class AnimalFarm(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -189,3 +194,97 @@ class AnimalFarm(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """AnimalFarm - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([Animal]): # noqa: E501 + + Keyword Args: + value ([Animal]): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python/petstore_api/model/api_response.py b/samples/client/petstore/python/petstore_api/model/api_response.py index 53adb5aba12..d1f3b363bef 100644 --- a/samples/client/petstore/python/petstore_api/model/api_response.py +++ b/samples/client/petstore/python/petstore_api/model/api_response.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ApiResponse(ModelNormal): @@ -94,8 +97,87 @@ class ApiResponse(ModelNormal): 'message': 'message', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ApiResponse - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + code (int): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + message (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -176,3 +258,6 @@ class ApiResponse(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py b/samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py index 8b6a2c42d0e..16d9bda29f1 100644 --- a/samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py +++ b/samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ArrayOfArrayOfNumberOnly(ModelNormal): @@ -90,8 +93,85 @@ class ArrayOfArrayOfNumberOnly(ModelNormal): 'array_array_number': 'ArrayArrayNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_array_number ([[float]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ArrayOfArrayOfNumberOnly(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/array_of_number_only.py b/samples/client/petstore/python/petstore_api/model/array_of_number_only.py index 7b754dc283e..0e44ab61aff 100644 --- a/samples/client/petstore/python/petstore_api/model/array_of_number_only.py +++ b/samples/client/petstore/python/petstore_api/model/array_of_number_only.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ArrayOfNumberOnly(ModelNormal): @@ -90,8 +93,85 @@ class ArrayOfNumberOnly(ModelNormal): 'array_number': 'ArrayNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_number ([float]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ArrayOfNumberOnly(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/array_test.py b/samples/client/petstore/python/petstore_api/model/array_test.py index 9691a1e6037..64c180d11bc 100644 --- a/samples/client/petstore/python/petstore_api/model/array_test.py +++ b/samples/client/petstore/python/petstore_api/model/array_test.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.read_only_first import ReadOnlyFirst @@ -100,8 +103,87 @@ class ArrayTest(ModelNormal): 'array_array_of_model': 'array_array_of_model', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_of_string ([str]): [optional] # noqa: E501 + array_array_of_integer ([[int]]): [optional] # noqa: E501 + array_array_of_model ([[ReadOnlyFirst]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -182,3 +264,6 @@ class ArrayTest(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/capitalization.py b/samples/client/petstore/python/petstore_api/model/capitalization.py index 6d939535cee..2f1323481dc 100644 --- a/samples/client/petstore/python/petstore_api/model/capitalization.py +++ b/samples/client/petstore/python/petstore_api/model/capitalization.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Capitalization(ModelNormal): @@ -100,8 +103,90 @@ class Capitalization(ModelNormal): 'att_name': 'ATT_NAME', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Capitalization - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + small_camel (str): [optional] # noqa: E501 + capital_camel (str): [optional] # noqa: E501 + small_snake (str): [optional] # noqa: E501 + capital_snake (str): [optional] # noqa: E501 + sca_eth_flow_points (str): [optional] # noqa: E501 + att_name (str): Name of the pet . [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -185,3 +270,6 @@ class Capitalization(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/cat.py b/samples/client/petstore/python/petstore_api/model/cat.py index eeea79359fc..be46fe5abd8 100644 --- a/samples/client/petstore/python/petstore_api/model/cat.py +++ b/samples/client/petstore/python/petstore_api/model/cat.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -105,6 +108,100 @@ class Cat(ModelComposed): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Cat - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -202,6 +299,9 @@ class Cat(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/cat_all_of.py b/samples/client/petstore/python/petstore_api/model/cat_all_of.py index 7efba680b4d..a5bef948f72 100644 --- a/samples/client/petstore/python/petstore_api/model/cat_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/cat_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class CatAllOf(ModelNormal): @@ -90,8 +93,85 @@ class CatAllOf(ModelNormal): 'declawed': 'declawed', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """CatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class CatAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/category.py b/samples/client/petstore/python/petstore_api/model/category.py index 4936b4f0e44..b40329c9424 100644 --- a/samples/client/petstore/python/petstore_api/model/category.py +++ b/samples/client/petstore/python/petstore_api/model/category.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Category(ModelNormal): @@ -92,8 +95,90 @@ class Category(ModelNormal): 'id': 'id', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Category - a model defined in OpenAPI + + Args: + + Keyword Args: + name (str): defaults to "default-name" # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + """ + + name = kwargs.get('name', "default-name") + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -177,3 +262,6 @@ class Category(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/child.py b/samples/client/petstore/python/petstore_api/model/child.py index 8fad3bf107b..556f58a84d2 100644 --- a/samples/client/petstore/python/petstore_api/model/child.py +++ b/samples/client/petstore/python/petstore_api/model/child.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_all_of import ChildAllOf @@ -102,6 +105,100 @@ class Child(ModelComposed): 'inter_net': 'interNet', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Child - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + tele_vision (bool): [optional] # noqa: E501 + inter_net (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -199,6 +296,9 @@ class Child(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/child_all_of.py b/samples/client/petstore/python/petstore_api/model/child_all_of.py index 9db852ec725..e38d28f52d1 100644 --- a/samples/client/petstore/python/petstore_api/model/child_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/child_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildAllOf(ModelNormal): @@ -90,8 +93,85 @@ class ChildAllOf(ModelNormal): 'inter_net': 'interNet', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + inter_net (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ChildAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/child_cat.py b/samples/client/petstore/python/petstore_api/model/child_cat.py index d054cb7a97a..3644df82fc5 100644 --- a/samples/client/petstore/python/petstore_api/model/child_cat.py +++ b/samples/client/petstore/python/petstore_api/model/child_cat.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat_all_of import ChildCatAllOf @@ -103,6 +106,99 @@ class ChildCat(ModelComposed): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildCat - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -199,6 +295,9 @@ class ChildCat(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/child_cat_all_of.py b/samples/client/petstore/python/petstore_api/model/child_cat_all_of.py index 3d732d085fb..48b725d7c3c 100644 --- a/samples/client/petstore/python/petstore_api/model/child_cat_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/child_cat_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildCatAllOf(ModelNormal): @@ -90,8 +93,85 @@ class ChildCatAllOf(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildCatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ChildCatAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/child_dog.py b/samples/client/petstore/python/petstore_api/model/child_dog.py index 6244359fea2..65f1a37e383 100644 --- a/samples/client/petstore/python/petstore_api/model/child_dog.py +++ b/samples/client/petstore/python/petstore_api/model/child_dog.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_dog_all_of import ChildDogAllOf @@ -103,6 +106,99 @@ class ChildDog(ModelComposed): 'bark': 'bark', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildDog - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bark (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -199,6 +295,9 @@ class ChildDog(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/child_dog_all_of.py b/samples/client/petstore/python/petstore_api/model/child_dog_all_of.py index d3a0d89c4da..40d4f048f87 100644 --- a/samples/client/petstore/python/petstore_api/model/child_dog_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/child_dog_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildDogAllOf(ModelNormal): @@ -90,8 +93,85 @@ class ChildDogAllOf(ModelNormal): 'bark': 'bark', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildDogAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bark (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ChildDogAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/child_lizard.py b/samples/client/petstore/python/petstore_api/model/child_lizard.py index b56925a0c92..cfb0e5426f7 100644 --- a/samples/client/petstore/python/petstore_api/model/child_lizard.py +++ b/samples/client/petstore/python/petstore_api/model/child_lizard.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_lizard_all_of import ChildLizardAllOf @@ -103,6 +106,99 @@ class ChildLizard(ModelComposed): 'loves_rocks': 'lovesRocks', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildLizard - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + loves_rocks (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -199,6 +295,9 @@ class ChildLizard(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py b/samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py index 1c8f29548b5..b0e9771c580 100644 --- a/samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildLizardAllOf(ModelNormal): @@ -90,8 +93,85 @@ class ChildLizardAllOf(ModelNormal): 'loves_rocks': 'lovesRocks', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildLizardAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + loves_rocks (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ChildLizardAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/class_model.py b/samples/client/petstore/python/petstore_api/model/class_model.py index 9e65a937365..a3f2b58f87f 100644 --- a/samples/client/petstore/python/petstore_api/model/class_model.py +++ b/samples/client/petstore/python/petstore_api/model/class_model.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ClassModel(ModelNormal): @@ -90,8 +93,85 @@ class ClassModel(ModelNormal): '_class': '_class', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ClassModel - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ClassModel(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/client.py b/samples/client/petstore/python/petstore_api/model/client.py index 6218de1e19e..3dca32f7926 100644 --- a/samples/client/petstore/python/petstore_api/model/client.py +++ b/samples/client/petstore/python/petstore_api/model/client.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Client(ModelNormal): @@ -90,8 +93,85 @@ class Client(ModelNormal): 'client': 'client', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Client - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + client (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class Client(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/dog.py b/samples/client/petstore/python/petstore_api/model/dog.py index 3452f0d040a..4a20dafa46c 100644 --- a/samples/client/petstore/python/petstore_api/model/dog.py +++ b/samples/client/petstore/python/petstore_api/model/dog.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -105,6 +108,100 @@ class Dog(ModelComposed): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Dog - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -202,6 +299,9 @@ class Dog(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/dog_all_of.py b/samples/client/petstore/python/petstore_api/model/dog_all_of.py index 962903d3a38..dbc36cb2c8f 100644 --- a/samples/client/petstore/python/petstore_api/model/dog_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/dog_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class DogAllOf(ModelNormal): @@ -90,8 +93,85 @@ class DogAllOf(ModelNormal): 'breed': 'breed', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """DogAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class DogAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/enum_arrays.py b/samples/client/petstore/python/petstore_api/model/enum_arrays.py index db56838d7e4..da42763d9c3 100644 --- a/samples/client/petstore/python/petstore_api/model/enum_arrays.py +++ b/samples/client/petstore/python/petstore_api/model/enum_arrays.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class EnumArrays(ModelNormal): @@ -100,8 +103,86 @@ class EnumArrays(ModelNormal): 'array_enum': 'array_enum', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """EnumArrays - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_symbol (str): [optional] # noqa: E501 + array_enum ([str]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -181,3 +262,6 @@ class EnumArrays(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/enum_class.py b/samples/client/petstore/python/petstore_api/model/enum_class.py index 63be703c38e..a9e7723b255 100644 --- a/samples/client/petstore/python/petstore_api/model/enum_class.py +++ b/samples/client/petstore/python/petstore_api/model/enum_class.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class EnumClass(ModelSimple): @@ -89,6 +92,8 @@ class EnumClass(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -184,3 +189,93 @@ class EnumClass(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """EnumClass - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + + Keyword Args: + value (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "-efg" + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python/petstore_api/model/enum_test.py b/samples/client/petstore/python/petstore_api/model/enum_test.py index ee14c70b46f..a3f47184d1a 100644 --- a/samples/client/petstore/python/petstore_api/model/enum_test.py +++ b/samples/client/petstore/python/petstore_api/model/enum_test.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.string_enum import StringEnum @@ -122,8 +125,92 @@ class EnumTest(ModelNormal): 'string_enum': 'stringEnum', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, enum_string_required, *args, **kwargs): # noqa: E501 + """EnumTest - a model defined in OpenAPI + + Args: + enum_string_required (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enum_string (str): [optional] # noqa: E501 + enum_integer (int): [optional] # noqa: E501 + enum_number (float): [optional] # noqa: E501 + string_enum (StringEnum): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.enum_string_required = enum_string_required + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -209,3 +296,6 @@ class EnumTest(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/file.py b/samples/client/petstore/python/petstore_api/model/file.py index 137d0026324..849f5727dc9 100644 --- a/samples/client/petstore/python/petstore_api/model/file.py +++ b/samples/client/petstore/python/petstore_api/model/file.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class File(ModelNormal): @@ -90,8 +93,85 @@ class File(ModelNormal): 'source_uri': 'sourceURI', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """File - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + source_uri (str): Test capitalization. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class File(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/file_schema_test_class.py b/samples/client/petstore/python/petstore_api/model/file_schema_test_class.py index 3722125ae48..f7e154e47b7 100644 --- a/samples/client/petstore/python/petstore_api/model/file_schema_test_class.py +++ b/samples/client/petstore/python/petstore_api/model/file_schema_test_class.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.file import File @@ -98,8 +101,86 @@ class FileSchemaTestClass(ModelNormal): 'files': 'files', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """FileSchemaTestClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + file (File): [optional] # noqa: E501 + files ([File]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -179,3 +260,6 @@ class FileSchemaTestClass(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/format_test.py b/samples/client/petstore/python/petstore_api/model/format_test.py index 7b415af7ad2..1d3ef5f76b4 100644 --- a/samples/client/petstore/python/petstore_api/model/format_test.py +++ b/samples/client/petstore/python/petstore_api/model/format_test.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class FormatTest(ModelNormal): @@ -149,8 +152,103 @@ class FormatTest(ModelNormal): 'uuid': 'uuid', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, number, byte, date, password, *args, **kwargs): # noqa: E501 + """FormatTest - a model defined in OpenAPI + + Args: + number (float): + byte (str): + date (date): + password (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + integer (int): [optional] # noqa: E501 + int32 (int): [optional] # noqa: E501 + int64 (int): [optional] # noqa: E501 + float (float): [optional] # noqa: E501 + double (float): [optional] # noqa: E501 + string (str): [optional] # noqa: E501 + binary (file_type): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + uuid (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.number = number + self.byte = byte + self.date = date + self.password = password + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -247,3 +345,6 @@ class FormatTest(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/grandparent.py b/samples/client/petstore/python/petstore_api/model/grandparent.py index 728b1e1d129..b92e3acdcf3 100644 --- a/samples/client/petstore/python/petstore_api/model/grandparent.py +++ b/samples/client/petstore/python/petstore_api/model/grandparent.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Grandparent(ModelNormal): @@ -90,8 +93,85 @@ class Grandparent(ModelNormal): 'radio_waves': 'radioWaves', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Grandparent - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class Grandparent(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/grandparent_animal.py b/samples/client/petstore/python/petstore_api/model/grandparent_animal.py index 089f5a4a07c..fd77a46211f 100644 --- a/samples/client/petstore/python/petstore_api/model/grandparent_animal.py +++ b/samples/client/petstore/python/petstore_api/model/grandparent_animal.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat import ChildCat @@ -110,8 +113,88 @@ class GrandparentAnimal(ModelNormal): 'pet_type': 'pet_type', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, pet_type, *args, **kwargs): # noqa: E501 + """GrandparentAnimal - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.pet_type = pet_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -193,3 +276,6 @@ class GrandparentAnimal(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/has_only_read_only.py b/samples/client/petstore/python/petstore_api/model/has_only_read_only.py index 4ea0bb08721..33d1c15b58d 100644 --- a/samples/client/petstore/python/petstore_api/model/has_only_read_only.py +++ b/samples/client/petstore/python/petstore_api/model/has_only_read_only.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class HasOnlyReadOnly(ModelNormal): @@ -92,8 +95,88 @@ class HasOnlyReadOnly(ModelNormal): 'foo': 'foo', # noqa: E501 } + read_only_vars = { + 'bar', # noqa: E501 + 'foo', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """HasOnlyReadOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + foo (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +256,6 @@ class HasOnlyReadOnly(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/list.py b/samples/client/petstore/python/petstore_api/model/list.py index 11b46f10b56..4b71d9deec0 100644 --- a/samples/client/petstore/python/petstore_api/model/list.py +++ b/samples/client/petstore/python/petstore_api/model/list.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class List(ModelNormal): @@ -90,8 +93,85 @@ class List(ModelNormal): '_123_list': '123-list', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """List - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _123_list (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class List(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/map_test.py b/samples/client/petstore/python/petstore_api/model/map_test.py index a5418b39e73..39c3b180e88 100644 --- a/samples/client/petstore/python/petstore_api/model/map_test.py +++ b/samples/client/petstore/python/petstore_api/model/map_test.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.string_boolean_map import StringBooleanMap @@ -106,8 +109,88 @@ class MapTest(ModelNormal): 'indirect_map': 'indirect_map', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MapTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_map_of_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_of_enum_string ({str: (str,)}): [optional] # noqa: E501 + direct_map ({str: (bool,)}): [optional] # noqa: E501 + indirect_map (StringBooleanMap): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -189,3 +272,6 @@ class MapTest(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py index 67b3f79d9e5..f46cd0b8972 100644 --- a/samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -100,8 +103,87 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): 'map': 'map', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + uuid (str): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + map ({str: (Animal,)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -182,3 +264,6 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/model200_response.py b/samples/client/petstore/python/petstore_api/model/model200_response.py index 056f4c56ad3..41a8dee5fdf 100644 --- a/samples/client/petstore/python/petstore_api/model/model200_response.py +++ b/samples/client/petstore/python/petstore_api/model/model200_response.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Model200Response(ModelNormal): @@ -92,8 +95,86 @@ class Model200Response(ModelNormal): '_class': 'class', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Model200Response - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (int): [optional] # noqa: E501 + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +254,6 @@ class Model200Response(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/model_return.py b/samples/client/petstore/python/petstore_api/model/model_return.py index 5f34582cdb4..f3720b05246 100644 --- a/samples/client/petstore/python/petstore_api/model/model_return.py +++ b/samples/client/petstore/python/petstore_api/model/model_return.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ModelReturn(ModelNormal): @@ -90,8 +93,85 @@ class ModelReturn(ModelNormal): '_return': 'return', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ModelReturn - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _return (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ModelReturn(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/name.py b/samples/client/petstore/python/petstore_api/model/name.py index 06b387ce9bf..d46618c88a1 100644 --- a/samples/client/petstore/python/petstore_api/model/name.py +++ b/samples/client/petstore/python/petstore_api/model/name.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Name(ModelNormal): @@ -96,8 +99,93 @@ class Name(ModelNormal): '_123_number': '123Number', # noqa: E501 } + read_only_vars = { + 'snake_case', # noqa: E501 + '_123_number', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, *args, **kwargs): # noqa: E501 + """Name - a model defined in OpenAPI + + Args: + name (int): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + snake_case (int): [optional] # noqa: E501 + _property (str): [optional] # noqa: E501 + _123_number (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -182,3 +270,6 @@ class Name(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/number_only.py b/samples/client/petstore/python/petstore_api/model/number_only.py index cb2c9e2ad52..a96d9165056 100644 --- a/samples/client/petstore/python/petstore_api/model/number_only.py +++ b/samples/client/petstore/python/petstore_api/model/number_only.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class NumberOnly(ModelNormal): @@ -90,8 +93,85 @@ class NumberOnly(ModelNormal): 'just_number': 'JustNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_number (float): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class NumberOnly(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/number_with_validations.py b/samples/client/petstore/python/petstore_api/model/number_with_validations.py index fb47d885bfd..27bc46dbe44 100644 --- a/samples/client/petstore/python/petstore_api/model/number_with_validations.py +++ b/samples/client/petstore/python/petstore_api/model/number_with_validations.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class NumberWithValidations(ModelSimple): @@ -88,6 +91,8 @@ class NumberWithValidations(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -187,3 +192,97 @@ class NumberWithValidations(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """NumberWithValidations - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (float): # noqa: E501 + + Keyword Args: + value (float): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py b/samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py index 7256f67a8d6..2ef48316f43 100644 --- a/samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py +++ b/samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.number_with_validations import NumberWithValidations @@ -100,8 +103,87 @@ class ObjectModelWithRefProps(ModelNormal): 'my_boolean': 'my_boolean', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ObjectModelWithRefProps - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + my_number (NumberWithValidations): [optional] # noqa: E501 + my_string (str): [optional] # noqa: E501 + my_boolean (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -182,3 +264,6 @@ class ObjectModelWithRefProps(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/order.py b/samples/client/petstore/python/petstore_api/model/order.py index 48207e4560e..eeefff1513f 100644 --- a/samples/client/petstore/python/petstore_api/model/order.py +++ b/samples/client/petstore/python/petstore_api/model/order.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Order(ModelNormal): @@ -105,8 +108,90 @@ class Order(ModelNormal): 'complete': 'complete', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Order - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + pet_id (int): [optional] # noqa: E501 + quantity (int): [optional] # noqa: E501 + ship_date (datetime): [optional] # noqa: E501 + status (str): Order Status. [optional] # noqa: E501 + complete (bool): [optional] if omitted the server will use the default value of False # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -190,3 +275,6 @@ class Order(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/parent.py b/samples/client/petstore/python/petstore_api/model/parent.py index 063d5051747..e43f678253d 100644 --- a/samples/client/petstore/python/petstore_api/model/parent.py +++ b/samples/client/petstore/python/petstore_api/model/parent.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.grandparent import Grandparent @@ -100,6 +103,99 @@ class Parent(ModelComposed): 'tele_vision': 'teleVision', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Parent - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + tele_vision (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -196,6 +292,9 @@ class Parent(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/parent_all_of.py b/samples/client/petstore/python/petstore_api/model/parent_all_of.py index 2f7b8a791d2..602e3f610a0 100644 --- a/samples/client/petstore/python/petstore_api/model/parent_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/parent_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ParentAllOf(ModelNormal): @@ -90,8 +93,85 @@ class ParentAllOf(ModelNormal): 'tele_vision': 'teleVision', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ParentAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + tele_vision (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ParentAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/parent_pet.py b/samples/client/petstore/python/petstore_api/model/parent_pet.py index b012d1558a7..fd774033ee3 100644 --- a/samples/client/petstore/python/petstore_api/model/parent_pet.py +++ b/samples/client/petstore/python/petstore_api/model/parent_pet.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat import ChildCat @@ -109,6 +112,98 @@ class ParentPet(ModelComposed): 'pet_type': 'pet_type', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ParentPet - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -204,6 +299,9 @@ class ParentPet(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/pet.py b/samples/client/petstore/python/petstore_api/model/pet.py index b0c8b08607d..8946f6d4bea 100644 --- a/samples/client/petstore/python/petstore_api/model/pet.py +++ b/samples/client/petstore/python/petstore_api/model/pet.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.category import Category @@ -113,8 +116,94 @@ class Pet(ModelNormal): 'status': 'status', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, photo_urls, *args, **kwargs): # noqa: E501 + """Pet - a model defined in OpenAPI + + Args: + name (str): + photo_urls ([str]): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + category (Category): [optional] # noqa: E501 + tags ([Tag]): [optional] # noqa: E501 + status (str): pet status in the store. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + self.photo_urls = photo_urls + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -202,3 +291,6 @@ class Pet(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/player.py b/samples/client/petstore/python/petstore_api/model/player.py index 2c51f9b57af..50ab531029b 100644 --- a/samples/client/petstore/python/petstore_api/model/player.py +++ b/samples/client/petstore/python/petstore_api/model/player.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Player(ModelNormal): @@ -92,8 +95,89 @@ class Player(ModelNormal): 'enemy_player': 'enemyPlayer', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, *args, **kwargs): # noqa: E501 + """Player - a model defined in OpenAPI + + Args: + name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enemy_player (Player): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -176,3 +260,6 @@ class Player(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/read_only_first.py b/samples/client/petstore/python/petstore_api/model/read_only_first.py index 0302bf96a7e..38cb5e2634f 100644 --- a/samples/client/petstore/python/petstore_api/model/read_only_first.py +++ b/samples/client/petstore/python/petstore_api/model/read_only_first.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ReadOnlyFirst(ModelNormal): @@ -92,8 +95,87 @@ class ReadOnlyFirst(ModelNormal): 'baz': 'baz', # noqa: E501 } + read_only_vars = { + 'bar', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ReadOnlyFirst - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + baz (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +255,6 @@ class ReadOnlyFirst(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/special_model_name.py b/samples/client/petstore/python/petstore_api/model/special_model_name.py index cfaedbc7881..cc2e49f6bcb 100644 --- a/samples/client/petstore/python/petstore_api/model/special_model_name.py +++ b/samples/client/petstore/python/petstore_api/model/special_model_name.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class SpecialModelName(ModelNormal): @@ -90,8 +93,85 @@ class SpecialModelName(ModelNormal): 'special_property_name': '$special[property.name]', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SpecialModelName - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + special_property_name (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class SpecialModelName(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/string_boolean_map.py b/samples/client/petstore/python/petstore_api/model/string_boolean_map.py index 4ac52699183..05f8527fec1 100644 --- a/samples/client/petstore/python/petstore_api/model/string_boolean_map.py +++ b/samples/client/petstore/python/petstore_api/model/string_boolean_map.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class StringBooleanMap(ModelNormal): @@ -88,8 +91,84 @@ class StringBooleanMap(ModelNormal): attribute_map = { } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """StringBooleanMap - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +246,6 @@ class StringBooleanMap(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/string_enum.py b/samples/client/petstore/python/petstore_api/model/string_enum.py index 4c92316cb7e..5bd1e28942e 100644 --- a/samples/client/petstore/python/petstore_api/model/string_enum.py +++ b/samples/client/petstore/python/petstore_api/model/string_enum.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class StringEnum(ModelSimple): @@ -89,6 +92,8 @@ class StringEnum(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -188,3 +193,97 @@ class StringEnum(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """StringEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str):, must be one of ["placed", "approved", "delivered", ] # noqa: E501 + + Keyword Args: + value (str):, must be one of ["placed", "approved", "delivered", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python/petstore_api/model/tag.py b/samples/client/petstore/python/petstore_api/model/tag.py index 01c28233598..7db3cee0baa 100644 --- a/samples/client/petstore/python/petstore_api/model/tag.py +++ b/samples/client/petstore/python/petstore_api/model/tag.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Tag(ModelNormal): @@ -94,8 +97,87 @@ class Tag(ModelNormal): 'full_name': 'fullName', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Tag - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + name (str): [optional] # noqa: E501 + full_name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -176,3 +258,6 @@ class Tag(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/type_holder_default.py b/samples/client/petstore/python/petstore_api/model/type_holder_default.py index 04a96f7e906..be884db9d13 100644 --- a/samples/client/petstore/python/petstore_api/model/type_holder_default.py +++ b/samples/client/petstore/python/petstore_api/model/type_holder_default.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class TypeHolderDefault(ModelNormal): @@ -102,8 +105,102 @@ class TypeHolderDefault(ModelNormal): 'datetime_item': 'datetime_item', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, array_item, *args, **kwargs): # noqa: E501 + """TypeHolderDefault - a model defined in OpenAPI + + Args: + array_item ([int]): + + Keyword Args: + string_item (str): defaults to "what" # noqa: E501 + number_item (float): defaults to 1.234 # noqa: E501 + integer_item (int): defaults to -2 # noqa: E501 + bool_item (bool): defaults to True # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + date_item (date): [optional] # noqa: E501 + datetime_item (datetime): [optional] # noqa: E501 + """ + + string_item = kwargs.get('string_item', "what") + number_item = kwargs.get('number_item', 1.234) + integer_item = kwargs.get('integer_item', -2) + bool_item = kwargs.get('bool_item', True) + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.string_item = string_item + self.number_item = number_item + self.integer_item = integer_item + self.bool_item = bool_item + self.array_item = array_item + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -199,3 +296,6 @@ class TypeHolderDefault(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/type_holder_example.py b/samples/client/petstore/python/petstore_api/model/type_holder_example.py index f6e5f44c389..a0836e32d3f 100644 --- a/samples/client/petstore/python/petstore_api/model/type_holder_example.py +++ b/samples/client/petstore/python/petstore_api/model/type_holder_example.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class TypeHolderExample(ModelNormal): @@ -107,8 +110,99 @@ class TypeHolderExample(ModelNormal): 'array_item': 'array_item', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, bool_item, array_item, *args, **kwargs): # noqa: E501 + """TypeHolderExample - a model defined in OpenAPI + + Args: + bool_item (bool): + array_item ([int]): + + Keyword Args: + string_item (str): defaults to "what", must be one of ["what", ] # noqa: E501 + number_item (float): defaults to 1.234, must be one of [1.234, ] # noqa: E501 + integer_item (int): defaults to -2, must be one of [-2, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + string_item = kwargs.get('string_item', "what") + number_item = kwargs.get('number_item', 1.234) + integer_item = kwargs.get('integer_item', -2) + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.string_item = string_item + self.number_item = number_item + self.integer_item = integer_item + self.bool_item = bool_item + self.array_item = array_item + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -201,3 +295,6 @@ class TypeHolderExample(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/user.py b/samples/client/petstore/python/petstore_api/model/user.py index 64bd6984933..9c5bc4dfd41 100644 --- a/samples/client/petstore/python/petstore_api/model/user.py +++ b/samples/client/petstore/python/petstore_api/model/user.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class User(ModelNormal): @@ -104,8 +107,92 @@ class User(ModelNormal): 'user_status': 'userStatus', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """User - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + username (str): [optional] # noqa: E501 + first_name (str): [optional] # noqa: E501 + last_name (str): [optional] # noqa: E501 + email (str): [optional] # noqa: E501 + password (str): [optional] # noqa: E501 + phone (str): [optional] # noqa: E501 + user_status (int): User Status. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -191,3 +278,6 @@ class User(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/xml_item.py b/samples/client/petstore/python/petstore_api/model/xml_item.py index ba096779721..060ed03809c 100644 --- a/samples/client/petstore/python/petstore_api/model/xml_item.py +++ b/samples/client/petstore/python/petstore_api/model/xml_item.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class XmlItem(ModelNormal): @@ -146,8 +149,113 @@ class XmlItem(ModelNormal): 'prefix_ns_wrapped_array': 'prefix_ns_wrapped_array', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """XmlItem - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + attribute_string (str): [optional] # noqa: E501 + attribute_number (float): [optional] # noqa: E501 + attribute_integer (int): [optional] # noqa: E501 + attribute_boolean (bool): [optional] # noqa: E501 + wrapped_array ([int]): [optional] # noqa: E501 + name_string (str): [optional] # noqa: E501 + name_number (float): [optional] # noqa: E501 + name_integer (int): [optional] # noqa: E501 + name_boolean (bool): [optional] # noqa: E501 + name_array ([int]): [optional] # noqa: E501 + name_wrapped_array ([int]): [optional] # noqa: E501 + prefix_string (str): [optional] # noqa: E501 + prefix_number (float): [optional] # noqa: E501 + prefix_integer (int): [optional] # noqa: E501 + prefix_boolean (bool): [optional] # noqa: E501 + prefix_array ([int]): [optional] # noqa: E501 + prefix_wrapped_array ([int]): [optional] # noqa: E501 + namespace_string (str): [optional] # noqa: E501 + namespace_number (float): [optional] # noqa: E501 + namespace_integer (int): [optional] # noqa: E501 + namespace_boolean (bool): [optional] # noqa: E501 + namespace_array ([int]): [optional] # noqa: E501 + namespace_wrapped_array ([int]): [optional] # noqa: E501 + prefix_ns_string (str): [optional] # noqa: E501 + prefix_ns_number (float): [optional] # noqa: E501 + prefix_ns_integer (int): [optional] # noqa: E501 + prefix_ns_boolean (bool): [optional] # noqa: E501 + prefix_ns_array ([int]): [optional] # noqa: E501 + prefix_ns_wrapped_array ([int]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -254,3 +362,6 @@ class XmlItem(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model_utils.py b/samples/client/petstore/python/petstore_api/model_utils.py index 3a555f0a88c..3913228d6b8 100644 --- a/samples/client/petstore/python/petstore_api/model_utils.py +++ b/samples/client/petstore/python/petstore_api/model_utils.py @@ -29,6 +29,22 @@ none_type = type(None) file_type = io.IOBase +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + class cached_property(object): # this caches the result of the function call for fn with no inputs # use this as a decorator on fuction methods that you want converted @@ -284,6 +300,121 @@ class OpenApiModel(object): return new_inst + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + class ModelSimple(OpenApiModel): """the parent class of models whose type != object in their swagger/openapi""" @@ -1208,14 +1339,14 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, _spec_property_naming=spec_property_naming) if issubclass(model_class, ModelSimple): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) elif isinstance(model_data, list): - return model_class(*model_data, **kw_args) + return model_class._new_from_openapi_data(*model_data, **kw_args) if isinstance(model_data, dict): kw_args.update(model_data) - return model_class(**kw_args) + return model_class._new_from_openapi_data(**kw_args) elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) def deserialize_file(response_data, configuration, content_disposition=None): @@ -1577,22 +1708,6 @@ def get_valid_classes_phrase(input_classes): return "is one of [{0}]".format(", ".join(all_class_names)) -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python(kwargs, _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - def get_allof_instances(self, model_args, constant_args): """ Args: diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py index 7239795cf4a..34ae88833fb 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesAnyType(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesAnyType(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesAnyType - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesAnyType(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py index 7d9403758a0..55f44f411c2 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesArray(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesArray(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesArray - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesArray(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py index ca129b766ec..b9c5c258e3c 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesBoolean(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesBoolean(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesBoolean - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesBoolean(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py index 292f467aaa8..5a38128ad89 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesClass(ModelNormal): @@ -104,8 +107,95 @@ class AdditionalPropertiesClass(ModelNormal): 'anytype_3': 'anytype_3', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_string ({str: (str,)}): [optional] # noqa: E501 + map_number ({str: (float,)}): [optional] # noqa: E501 + map_integer ({str: (int,)}): [optional] # noqa: E501 + map_boolean ({str: (bool,)}): [optional] # noqa: E501 + map_array_integer ({str: ([int],)}): [optional] # noqa: E501 + map_array_anytype ({str: ([bool, date, datetime, dict, float, int, list, str, none_type],)}): [optional] # noqa: E501 + map_map_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_map_anytype ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type,)},)}): [optional] # noqa: E501 + anytype_1 (bool, date, datetime, dict, float, int, list, str, none_type): [optional] # noqa: E501 + anytype_2 (bool, date, datetime, dict, float, int, list, str, none_type): no type is set for this. [optional] # noqa: E501 + anytype_3 (bool, date, datetime, dict, float, int, list, str, none_type): because of a bug in swagger-parser, this should have values {str: (str, int, float...)} but instead we get any type. See https://github.com/swagger-api/swagger-parser/issues/1378. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -194,3 +284,6 @@ class AdditionalPropertiesClass(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py index 87d78bf3600..f6f80f89c7a 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesInteger(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesInteger(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesInteger - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesInteger(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py index b10bd036ff3..6c094699462 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesNumber(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesNumber(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesNumber - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesNumber(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py index 000653f13a7..1fa671aff9b 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesObject(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesObject(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesObject - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesObject(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py index 7f1f94aa6b6..0afa8a9e637 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesString(ModelNormal): @@ -90,8 +93,85 @@ class AdditionalPropertiesString(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesString - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class AdditionalPropertiesString(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py index a3d48b6ea97..d1a9e4afbb0 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.cat import Cat @@ -99,8 +102,89 @@ class Animal(ModelNormal): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """Animal - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -183,3 +267,6 @@ class Animal(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py index 838b18a1297..042a8274ee7 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -83,6 +86,8 @@ class AnimalFarm(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -182,3 +187,97 @@ class AnimalFarm(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """AnimalFarm - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([Animal]): # noqa: E501 + + Keyword Args: + value ([Animal]): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py index 01e2175b800..5abc32eafe2 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ApiResponse(ModelNormal): @@ -88,8 +91,87 @@ class ApiResponse(ModelNormal): 'message': 'message', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ApiResponse - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + code (int): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + message (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +252,6 @@ class ApiResponse(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py index 008b74dd42a..90586071915 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ArrayOfArrayOfNumberOnly(ModelNormal): @@ -84,8 +87,85 @@ class ArrayOfArrayOfNumberOnly(ModelNormal): 'array_array_number': 'ArrayArrayNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_array_number ([[float]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class ArrayOfArrayOfNumberOnly(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py index f2e080bc258..e343a727d6e 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ArrayOfNumberOnly(ModelNormal): @@ -84,8 +87,85 @@ class ArrayOfNumberOnly(ModelNormal): 'array_number': 'ArrayNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_number ([float]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class ArrayOfNumberOnly(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py index ac42b07b93c..13649acbe32 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.read_only_first import ReadOnlyFirst @@ -93,8 +96,87 @@ class ArrayTest(ModelNormal): 'array_array_of_model': 'array_array_of_model', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_of_string ([str]): [optional] # noqa: E501 + array_array_of_integer ([[int]]): [optional] # noqa: E501 + array_array_of_model ([[ReadOnlyFirst]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -175,3 +257,6 @@ class ArrayTest(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py index 710c17e51a5..75a354d2959 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Capitalization(ModelNormal): @@ -94,8 +97,90 @@ class Capitalization(ModelNormal): 'att_name': 'ATT_NAME', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Capitalization - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + small_camel (str): [optional] # noqa: E501 + capital_camel (str): [optional] # noqa: E501 + small_snake (str): [optional] # noqa: E501 + capital_snake (str): [optional] # noqa: E501 + sca_eth_flow_points (str): [optional] # noqa: E501 + att_name (str): Name of the pet . [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -179,3 +264,6 @@ class Capitalization(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py index fd8d4bc7179..c6714183384 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -98,6 +101,100 @@ class Cat(ModelComposed): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Cat - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -195,6 +292,9 @@ class Cat(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py index 50b046510df..5ed2c9cdf28 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class CatAllOf(ModelNormal): @@ -84,8 +87,85 @@ class CatAllOf(ModelNormal): 'declawed': 'declawed', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """CatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class CatAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py index ed167471d35..cf8a1384975 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Category(ModelNormal): @@ -86,8 +89,90 @@ class Category(ModelNormal): 'id': 'id', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Category - a model defined in OpenAPI + + Args: + + Keyword Args: + name (str): defaults to "default-name" # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + """ + + name = kwargs.get('name', "default-name") + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -171,3 +256,6 @@ class Category(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py index d36723dd625..02324cb640c 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_all_of import ChildAllOf @@ -95,6 +98,100 @@ class Child(ModelComposed): 'inter_net': 'interNet', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Child - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + tele_vision (bool): [optional] # noqa: E501 + inter_net (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -192,6 +289,9 @@ class Child(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py index 2339e520bd6..e3f8db2e199 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildAllOf(ModelNormal): @@ -84,8 +87,85 @@ class ChildAllOf(ModelNormal): 'inter_net': 'interNet', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + inter_net (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class ChildAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py index 70438f3441f..fe267715ade 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat_all_of import ChildCatAllOf @@ -96,6 +99,99 @@ class ChildCat(ModelComposed): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildCat - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -192,6 +288,9 @@ class ChildCat(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py index f0f1a1ae6bd..ceacfbcd7b1 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildCatAllOf(ModelNormal): @@ -84,8 +87,85 @@ class ChildCatAllOf(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildCatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class ChildCatAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py index df4956266ae..c1b0dc5e868 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_dog_all_of import ChildDogAllOf @@ -96,6 +99,99 @@ class ChildDog(ModelComposed): 'bark': 'bark', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildDog - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bark (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -192,6 +288,9 @@ class ChildDog(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py index d460b68b3d3..41c87c20618 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildDogAllOf(ModelNormal): @@ -84,8 +87,85 @@ class ChildDogAllOf(ModelNormal): 'bark': 'bark', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildDogAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bark (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class ChildDogAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py index 1f50ba403ed..ef95bd5b8ca 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_lizard_all_of import ChildLizardAllOf @@ -96,6 +99,99 @@ class ChildLizard(ModelComposed): 'loves_rocks': 'lovesRocks', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildLizard - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + loves_rocks (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -192,6 +288,9 @@ class ChildLizard(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py index 669b9338d79..f88016d0879 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildLizardAllOf(ModelNormal): @@ -84,8 +87,85 @@ class ChildLizardAllOf(ModelNormal): 'loves_rocks': 'lovesRocks', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildLizardAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + loves_rocks (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class ChildLizardAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py index 18c16f89f90..0ecc844f84c 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ClassModel(ModelNormal): @@ -84,8 +87,85 @@ class ClassModel(ModelNormal): '_class': '_class', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ClassModel - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class ClassModel(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py index da615c54773..2b4ac4b91a8 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Client(ModelNormal): @@ -84,8 +87,85 @@ class Client(ModelNormal): 'client': 'client', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Client - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + client (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class Client(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py index e29ffa33602..d01bdc6e34d 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -98,6 +101,100 @@ class Dog(ModelComposed): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Dog - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -195,6 +292,9 @@ class Dog(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py index b7b2e7db66d..cdc633dc66f 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class DogAllOf(ModelNormal): @@ -84,8 +87,85 @@ class DogAllOf(ModelNormal): 'breed': 'breed', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """DogAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class DogAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py index 43ebac57de3..39fe0ffb838 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class EnumArrays(ModelNormal): @@ -94,8 +97,86 @@ class EnumArrays(ModelNormal): 'array_enum': 'array_enum', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """EnumArrays - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_symbol (str): [optional] # noqa: E501 + array_enum ([str]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -175,3 +256,6 @@ class EnumArrays(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py index 14188ca31d2..b0ed3d8966d 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class EnumClass(ModelSimple): @@ -83,6 +86,8 @@ class EnumClass(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -178,3 +183,93 @@ class EnumClass(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """EnumClass - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + + Keyword Args: + value (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "-efg" + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py index 79ba0f6a747..a75f4774ae7 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.string_enum import StringEnum @@ -115,8 +118,92 @@ class EnumTest(ModelNormal): 'string_enum': 'stringEnum', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, enum_string_required, *args, **kwargs): # noqa: E501 + """EnumTest - a model defined in OpenAPI + + Args: + enum_string_required (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enum_string (str): [optional] # noqa: E501 + enum_integer (int): [optional] # noqa: E501 + enum_number (float): [optional] # noqa: E501 + string_enum (StringEnum): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.enum_string_required = enum_string_required + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -202,3 +289,6 @@ class EnumTest(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py index a38cccacc6a..a2beaf44a01 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class File(ModelNormal): @@ -84,8 +87,85 @@ class File(ModelNormal): 'source_uri': 'sourceURI', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """File - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + source_uri (str): Test capitalization. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class File(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py index b8c519ed9c7..e3f7608e95d 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.file import File @@ -91,8 +94,86 @@ class FileSchemaTestClass(ModelNormal): 'files': 'files', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """FileSchemaTestClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + file (File): [optional] # noqa: E501 + files ([File]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -172,3 +253,6 @@ class FileSchemaTestClass(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py index 494ce2646da..1588b1de053 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class FormatTest(ModelNormal): @@ -143,8 +146,103 @@ class FormatTest(ModelNormal): 'uuid': 'uuid', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, number, byte, date, password, *args, **kwargs): # noqa: E501 + """FormatTest - a model defined in OpenAPI + + Args: + number (float): + byte (str): + date (date): + password (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + integer (int): [optional] # noqa: E501 + int32 (int): [optional] # noqa: E501 + int64 (int): [optional] # noqa: E501 + float (float): [optional] # noqa: E501 + double (float): [optional] # noqa: E501 + string (str): [optional] # noqa: E501 + binary (file_type): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + uuid (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.number = number + self.byte = byte + self.date = date + self.password = password + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -241,3 +339,6 @@ class FormatTest(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py index a52744cc3e2..c25e0b3f843 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Grandparent(ModelNormal): @@ -84,8 +87,85 @@ class Grandparent(ModelNormal): 'radio_waves': 'radioWaves', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Grandparent - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class Grandparent(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py index 48d3f6d9f0b..e053af7d538 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat import ChildCat @@ -103,8 +106,88 @@ class GrandparentAnimal(ModelNormal): 'pet_type': 'pet_type', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, pet_type, *args, **kwargs): # noqa: E501 + """GrandparentAnimal - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.pet_type = pet_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -186,3 +269,6 @@ class GrandparentAnimal(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py index c94781ae2c4..294a16ddc46 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class HasOnlyReadOnly(ModelNormal): @@ -86,8 +89,88 @@ class HasOnlyReadOnly(ModelNormal): 'foo': 'foo', # noqa: E501 } + read_only_vars = { + 'bar', # noqa: E501 + 'foo', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """HasOnlyReadOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + foo (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +250,6 @@ class HasOnlyReadOnly(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py index 09c762d6a79..18863e57bc7 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class List(ModelNormal): @@ -84,8 +87,85 @@ class List(ModelNormal): '_123_list': '123-list', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """List - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _123_list (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class List(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py index 169fb9d88ee..61281080799 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.string_boolean_map import StringBooleanMap @@ -99,8 +102,88 @@ class MapTest(ModelNormal): 'indirect_map': 'indirect_map', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MapTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_map_of_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_of_enum_string ({str: (str,)}): [optional] # noqa: E501 + direct_map ({str: (bool,)}): [optional] # noqa: E501 + indirect_map (StringBooleanMap): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -182,3 +265,6 @@ class MapTest(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py index 01df80d9d62..95468963156 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -93,8 +96,87 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): 'map': 'map', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + uuid (str): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + map ({str: (Animal,)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -175,3 +257,6 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py index 46b155b6523..d094c7f84c6 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Model200Response(ModelNormal): @@ -86,8 +89,86 @@ class Model200Response(ModelNormal): '_class': 'class', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Model200Response - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (int): [optional] # noqa: E501 + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +248,6 @@ class Model200Response(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py index 377b3507a8b..51bcf6f1649 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ModelReturn(ModelNormal): @@ -84,8 +87,85 @@ class ModelReturn(ModelNormal): '_return': 'return', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ModelReturn - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _return (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class ModelReturn(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py index 1432e185ad6..4ee3e1ed2bf 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Name(ModelNormal): @@ -90,8 +93,93 @@ class Name(ModelNormal): '_123_number': '123Number', # noqa: E501 } + read_only_vars = { + 'snake_case', # noqa: E501 + '_123_number', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, *args, **kwargs): # noqa: E501 + """Name - a model defined in OpenAPI + + Args: + name (int): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + snake_case (int): [optional] # noqa: E501 + _property (str): [optional] # noqa: E501 + _123_number (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -176,3 +264,6 @@ class Name(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py index d4892dbede5..c4163787bc1 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class NumberOnly(ModelNormal): @@ -84,8 +87,85 @@ class NumberOnly(ModelNormal): 'just_number': 'JustNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_number (float): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class NumberOnly(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py index 458a7945975..5d66fec5ec6 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class NumberWithValidations(ModelSimple): @@ -82,6 +85,8 @@ class NumberWithValidations(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -181,3 +186,97 @@ class NumberWithValidations(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """NumberWithValidations - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (float): # noqa: E501 + + Keyword Args: + value (float): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py index b1dc4bf82e2..dfe5d05cf05 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.number_with_validations import NumberWithValidations @@ -93,8 +96,87 @@ class ObjectModelWithRefProps(ModelNormal): 'my_boolean': 'my_boolean', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ObjectModelWithRefProps - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + my_number (NumberWithValidations): [optional] # noqa: E501 + my_string (str): [optional] # noqa: E501 + my_boolean (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -175,3 +257,6 @@ class ObjectModelWithRefProps(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py index b42f066848a..b69e94ae36b 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Order(ModelNormal): @@ -99,8 +102,90 @@ class Order(ModelNormal): 'complete': 'complete', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Order - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + pet_id (int): [optional] # noqa: E501 + quantity (int): [optional] # noqa: E501 + ship_date (datetime): [optional] # noqa: E501 + status (str): Order Status. [optional] # noqa: E501 + complete (bool): [optional] if omitted the server will use the default value of False # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -184,3 +269,6 @@ class Order(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py index b07448d9e1f..13a722ff4b3 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.grandparent import Grandparent @@ -93,6 +96,99 @@ class Parent(ModelComposed): 'tele_vision': 'teleVision', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Parent - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + tele_vision (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -189,6 +285,9 @@ class Parent(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py index 0d109f25a4c..97916a1dd4e 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ParentAllOf(ModelNormal): @@ -84,8 +87,85 @@ class ParentAllOf(ModelNormal): 'tele_vision': 'teleVision', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ParentAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + tele_vision (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class ParentAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py index 597e30bb9c4..a20c0d1b867 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat import ChildCat @@ -102,6 +105,98 @@ class ParentPet(ModelComposed): 'pet_type': 'pet_type', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ParentPet - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -197,6 +292,9 @@ class ParentPet(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py index e9f1e30a319..a7b888a2aa3 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.category import Category @@ -106,8 +109,94 @@ class Pet(ModelNormal): 'status': 'status', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, photo_urls, *args, **kwargs): # noqa: E501 + """Pet - a model defined in OpenAPI + + Args: + name (str): + photo_urls ([str]): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + category (Category): [optional] # noqa: E501 + tags ([Tag]): [optional] # noqa: E501 + status (str): pet status in the store. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + self.photo_urls = photo_urls + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -195,3 +284,6 @@ class Pet(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py index 6e4485fb650..104c4d2900d 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Player(ModelNormal): @@ -86,8 +89,89 @@ class Player(ModelNormal): 'enemy_player': 'enemyPlayer', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, *args, **kwargs): # noqa: E501 + """Player - a model defined in OpenAPI + + Args: + name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enemy_player (Player): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +254,6 @@ class Player(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py index 5c68eab91ea..ad0bfbaac11 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ReadOnlyFirst(ModelNormal): @@ -86,8 +89,87 @@ class ReadOnlyFirst(ModelNormal): 'baz': 'baz', # noqa: E501 } + read_only_vars = { + 'bar', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ReadOnlyFirst - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + baz (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +249,6 @@ class ReadOnlyFirst(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py index 823e7759663..fa13828d6b9 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class SpecialModelName(ModelNormal): @@ -84,8 +87,85 @@ class SpecialModelName(ModelNormal): 'special_property_name': '$special[property.name]', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SpecialModelName - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + special_property_name (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +244,6 @@ class SpecialModelName(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py index 4ac52699183..05f8527fec1 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class StringBooleanMap(ModelNormal): @@ -88,8 +91,84 @@ class StringBooleanMap(ModelNormal): attribute_map = { } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """StringBooleanMap - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +246,6 @@ class StringBooleanMap(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py index 37dc04332ca..2397dd59fc9 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class StringEnum(ModelSimple): @@ -83,6 +86,8 @@ class StringEnum(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -182,3 +187,97 @@ class StringEnum(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """StringEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str):, must be one of ["placed", "approved", "delivered", ] # noqa: E501 + + Keyword Args: + value (str):, must be one of ["placed", "approved", "delivered", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py index d3dcb78b7ea..913976557b4 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Tag(ModelNormal): @@ -88,8 +91,87 @@ class Tag(ModelNormal): 'full_name': 'fullName', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Tag - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + name (str): [optional] # noqa: E501 + full_name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +252,6 @@ class Tag(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py index 324b131f3a2..b156cbac46e 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class TypeHolderDefault(ModelNormal): @@ -96,8 +99,102 @@ class TypeHolderDefault(ModelNormal): 'datetime_item': 'datetime_item', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, array_item, *args, **kwargs): # noqa: E501 + """TypeHolderDefault - a model defined in OpenAPI + + Args: + array_item ([int]): + + Keyword Args: + string_item (str): defaults to "what" # noqa: E501 + number_item (float): defaults to 1.234 # noqa: E501 + integer_item (int): defaults to -2 # noqa: E501 + bool_item (bool): defaults to True # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + date_item (date): [optional] # noqa: E501 + datetime_item (datetime): [optional] # noqa: E501 + """ + + string_item = kwargs.get('string_item', "what") + number_item = kwargs.get('number_item', 1.234) + integer_item = kwargs.get('integer_item', -2) + bool_item = kwargs.get('bool_item', True) + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.string_item = string_item + self.number_item = number_item + self.integer_item = integer_item + self.bool_item = bool_item + self.array_item = array_item + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -193,3 +290,6 @@ class TypeHolderDefault(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py index 30bbba178f4..c7a3f13b63c 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class TypeHolderExample(ModelNormal): @@ -101,8 +104,99 @@ class TypeHolderExample(ModelNormal): 'array_item': 'array_item', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, bool_item, array_item, *args, **kwargs): # noqa: E501 + """TypeHolderExample - a model defined in OpenAPI + + Args: + bool_item (bool): + array_item ([int]): + + Keyword Args: + string_item (str): defaults to "what", must be one of ["what", ] # noqa: E501 + number_item (float): defaults to 1.234, must be one of [1.234, ] # noqa: E501 + integer_item (int): defaults to -2, must be one of [-2, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + string_item = kwargs.get('string_item', "what") + number_item = kwargs.get('number_item', 1.234) + integer_item = kwargs.get('integer_item', -2) + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.string_item = string_item + self.number_item = number_item + self.integer_item = integer_item + self.bool_item = bool_item + self.array_item = array_item + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -195,3 +289,6 @@ class TypeHolderExample(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py index 9a3cd081411..a3a4019042b 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class User(ModelNormal): @@ -98,8 +101,92 @@ class User(ModelNormal): 'user_status': 'userStatus', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """User - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + username (str): [optional] # noqa: E501 + first_name (str): [optional] # noqa: E501 + last_name (str): [optional] # noqa: E501 + email (str): [optional] # noqa: E501 + password (str): [optional] # noqa: E501 + phone (str): [optional] # noqa: E501 + user_status (int): User Status. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -185,3 +272,6 @@ class User(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py index 8401b3f4007..18323416318 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class XmlItem(ModelNormal): @@ -140,8 +143,113 @@ class XmlItem(ModelNormal): 'prefix_ns_wrapped_array': 'prefix_ns_wrapped_array', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """XmlItem - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + attribute_string (str): [optional] # noqa: E501 + attribute_number (float): [optional] # noqa: E501 + attribute_integer (int): [optional] # noqa: E501 + attribute_boolean (bool): [optional] # noqa: E501 + wrapped_array ([int]): [optional] # noqa: E501 + name_string (str): [optional] # noqa: E501 + name_number (float): [optional] # noqa: E501 + name_integer (int): [optional] # noqa: E501 + name_boolean (bool): [optional] # noqa: E501 + name_array ([int]): [optional] # noqa: E501 + name_wrapped_array ([int]): [optional] # noqa: E501 + prefix_string (str): [optional] # noqa: E501 + prefix_number (float): [optional] # noqa: E501 + prefix_integer (int): [optional] # noqa: E501 + prefix_boolean (bool): [optional] # noqa: E501 + prefix_array ([int]): [optional] # noqa: E501 + prefix_wrapped_array ([int]): [optional] # noqa: E501 + namespace_string (str): [optional] # noqa: E501 + namespace_number (float): [optional] # noqa: E501 + namespace_integer (int): [optional] # noqa: E501 + namespace_boolean (bool): [optional] # noqa: E501 + namespace_array ([int]): [optional] # noqa: E501 + namespace_wrapped_array ([int]): [optional] # noqa: E501 + prefix_ns_string (str): [optional] # noqa: E501 + prefix_ns_number (float): [optional] # noqa: E501 + prefix_ns_integer (int): [optional] # noqa: E501 + prefix_ns_boolean (bool): [optional] # noqa: E501 + prefix_ns_array ([int]): [optional] # noqa: E501 + prefix_ns_wrapped_array ([int]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -248,3 +356,6 @@ class XmlItem(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py index 3a555f0a88c..3913228d6b8 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py @@ -29,6 +29,22 @@ none_type = type(None) file_type = io.IOBase +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + class cached_property(object): # this caches the result of the function call for fn with no inputs # use this as a decorator on fuction methods that you want converted @@ -284,6 +300,121 @@ class OpenApiModel(object): return new_inst + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + class ModelSimple(OpenApiModel): """the parent class of models whose type != object in their swagger/openapi""" @@ -1208,14 +1339,14 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, _spec_property_naming=spec_property_naming) if issubclass(model_class, ModelSimple): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) elif isinstance(model_data, list): - return model_class(*model_data, **kw_args) + return model_class._new_from_openapi_data(*model_data, **kw_args) if isinstance(model_data, dict): kw_args.update(model_data) - return model_class(**kw_args) + return model_class._new_from_openapi_data(**kw_args) elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) def deserialize_file(response_data, configuration, content_disposition=None): @@ -1577,22 +1708,6 @@ def get_valid_classes_phrase(input_classes): return "is one of [{0}]".format(", ".join(all_class_names)) -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python(kwargs, _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - def get_allof_instances(self, model_args, constant_args): """ Args: diff --git a/samples/client/petstore/scala-akka/.openapi-generator/FILES b/samples/client/petstore/scala-akka/.openapi-generator/FILES index 8d22043b5a9..2cd9737cf18 100644 --- a/samples/client/petstore/scala-akka/.openapi-generator/FILES +++ b/samples/client/petstore/scala-akka/.openapi-generator/FILES @@ -1,5 +1,6 @@ README.md build.sbt +project/build.properties src/main/resources/reference.conf src/main/scala/org/openapitools/client/api/EnumsSerializers.scala src/main/scala/org/openapitools/client/api/PetApi.scala diff --git a/samples/client/petstore/scala-akka/build.sbt b/samples/client/petstore/scala-akka/build.sbt index 038757790a5..e9915b07f85 100644 --- a/samples/client/petstore/scala-akka/build.sbt +++ b/samples/client/petstore/scala-akka/build.sbt @@ -1,19 +1,23 @@ version := "1.0.0" name := "scala-akka-petstore-client" organization := "org.openapitools" -scalaVersion := "2.12.8" + +scalaVersion := "2.12.13" +crossScalaVersions := Seq(scalaVersion.value, "2.13.4") + libraryDependencies ++= Seq( - "com.typesafe" % "config" % "1.3.3", - "com.typesafe.akka" %% "akka-actor" % "2.5.21", - "com.typesafe.akka" %% "akka-stream" % "2.5.21", - "com.typesafe.akka" %% "akka-http" % "10.1.7", - "org.json4s" %% "json4s-jackson" % "3.6.5", - "org.json4s" %% "json4s-ext" % "3.6.5", - "de.heikoseeberger" %% "akka-http-json4s" % "1.25.2", + "com.typesafe" % "config" % "1.4.1", + "com.typesafe.akka" %% "akka-actor" % "2.6.12", + "com.typesafe.akka" %% "akka-stream" % "2.6.12", + "com.typesafe.akka" %% "akka-http" % "10.2.3", + "org.json4s" %% "json4s-jackson" % "3.6.7", + "org.json4s" %% "json4s-ext" % "3.6.7", + "de.heikoseeberger" %% "akka-http-json4s" % "1.27.0", + "org.scala-lang.modules" %% "scala-collection-compat" % "2.4.1", // test dependencies - "org.scalatest" %% "scalatest" % "3.0.5" % "test", - "junit" % "junit" % "4.13.1" % "test" + "org.scalatest" %% "scalatest" % "3.2.3" % "test", + "org.scalatestplus" %% "junit-4-13" % "3.2.3.0" % "test" ) resolvers ++= Seq(Resolver.mavenLocal) diff --git a/samples/client/petstore/scala-akka/pom.xml b/samples/client/petstore/scala-akka/pom.xml index 42e08693b64..0f93bcb372b 100644 --- a/samples/client/petstore/scala-akka/pom.xml +++ b/samples/client/petstore/scala-akka/pom.xml @@ -15,15 +15,16 @@ UTF-8 1.8 - 2.12.8 - 3.5.3 - 3.2.11 - 2.5.21 - 10.1.7 - 1.3.3 - 1.25.2 - 4.13 - 3.0.5 + 2.12.13 + 3.6.7 + 3.6.7 + 2.6.12 + 10.2.3 + 1.4.1 + 1.27.0 + 2.4.1 + 3.2.3 + 3.2.3.0 3.3.1 @@ -70,6 +71,11 @@ akka-http-json4s_2.12 ${akka.http.json4s.version} + + org.scala-lang.modules + scala-collection-compat_2.12 + ${scala.compat.version} + @@ -79,9 +85,9 @@ test - junit - junit - ${junit.version} + org.scalatestplus + junit-4-13_2.12 + ${scala.test.plus.version} test diff --git a/samples/client/petstore/scala-akka/project/build.properties b/samples/client/petstore/scala-akka/project/build.properties new file mode 100644 index 00000000000..dc07aed85e0 --- /dev/null +++ b/samples/client/petstore/scala-akka/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.3.10 \ No newline at end of file diff --git a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala index d3ff4cadb8e..fe391096713 100644 --- a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala +++ b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala @@ -28,6 +28,7 @@ import de.heikoseeberger.akkahttpjson4s.Json4sSupport import org.json4s._ import org.json4s.jackson.JsonMethods._ import org.json4s.jackson.Serialization +import scala.collection.compat._ import scala.collection.immutable import scala.concurrent.{ ExecutionContext, ExecutionContextExecutor, Future } @@ -96,7 +97,7 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC private val http = Http() - val CompressionFilter: HttpMessage ⇒ Boolean = (msg: HttpMessage) => + val CompressionFilter: HttpMessage => Boolean = (msg: HttpMessage) => Seq( { _: HttpMessage => settings.compressionEnabled }, Encoder.DefaultFilter, @@ -125,7 +126,7 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC private def headers(headers: Map[String, Any]): immutable.Seq[HttpHeader] = headers.asFormattedParams .map { case (name, value) => RawHeader(name, value.toString) } - .to[immutable.Seq] + .to(immutable.Seq) private def bodyPart(name: String, value: Any): BodyPart = { @@ -157,9 +158,9 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC case MediaTypes.`multipart/form-data` => Multipart.FormData(Source(params.toList.map { case (name, value) => bodyPart(name, value) })) case MediaTypes.`application/x-www-form-urlencoded` => - FormData(params.mapValues(_.toString)) + FormData(params.view.mapValues(_.toString).toMap) case _: MediaType => // Default : application/x-www-form-urlencoded. - FormData(params.mapValues(_.toString)) + FormData(params.view.mapValues(_.toString).toMap) } ) } @@ -197,7 +198,9 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC params + (keyName -> key.value) case (params, _) => params }.asFormattedParams + .view .mapValues(_.toString) + .toMap .foldRight[Query](Uri.Query.Empty) { case ((name, value), acc) => acc.+:(name, value) } @@ -206,7 +209,9 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC def makeUri(r: ApiRequest[_]): Uri = { val opPath = r.operationPath.replaceAll("\\{format\\}", "json") val opPathWithParams = r.pathParams.asFormattedParams + .view .mapValues(_.toString) + .toMap .foldLeft(opPath) { case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value) } @@ -223,13 +228,13 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC http .singleRequest(request) .map { response => - val decoder: Coder with StreamDecoder = response.encoding match { - case HttpEncodings.gzip ⇒ - Gzip - case HttpEncodings.deflate ⇒ - Deflate - case HttpEncodings.identity ⇒ - NoCoding + val decoder: Decoder with Decoder = response.encoding match { + case HttpEncodings.gzip => + Coders.Gzip + case HttpEncodings.deflate => + Coders.Deflate + case HttpEncodings.identity => + Coders.NoCoding case HttpEncoding(encoding) => throw new IllegalArgumentException(s"Unsupported encoding: $encoding") } @@ -257,13 +262,13 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC request .responseForCode(response.status.intValue) match { case Some((Manifest.Unit, state: ResponseState)) => - Future(responseForState(state, Unit).asInstanceOf[ApiResponse[T]]) + Future(responseForState(state, ()).asInstanceOf[ApiResponse[T]]) case Some((manifest, state: ResponseState)) if manifest == mf => implicit val m: Unmarshaller[HttpEntity, T] = unmarshaller[T](mf, serialization, formats) Unmarshal(response.entity) .to[T] .recoverWith { - case e ⇒ throw ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), e) + case e => throw ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), e) } .map(value => responseForState(state, value)) case None | Some(_) => diff --git a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiSettings.scala b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiSettings.scala index 2553aeb3c87..2c02c47c7ba 100644 --- a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiSettings.scala +++ b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiSettings.scala @@ -13,12 +13,12 @@ package org.openapitools.client.core import java.util.concurrent.TimeUnit -import akka.actor.{ ExtendedActorSystem, Extension, ExtensionKey } +import akka.actor.{ActorSystem, ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider} import akka.http.scaladsl.model.StatusCodes.CustomStatusCode import akka.http.scaladsl.model.headers.RawHeader import com.typesafe.config.Config -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.concurrent.duration.FiniteDuration class ApiSettings(config: Config) extends Extension { @@ -42,4 +42,13 @@ class ApiSettings(config: Config) extends Extension { } } -object ApiSettings extends ExtensionKey[ApiSettings] +object ApiSettings extends ExtensionId[ApiSettings] with ExtensionIdProvider { + + override def lookup = ApiSettings + + override def createExtension(system: ExtendedActorSystem): ApiSettings = + new ApiSettings(system) + + // needed to get the type right when used from Java + override def get(system: ActorSystem): ApiSettings = super.get(system) +} diff --git a/samples/client/petstore/scala-akka/src/test/scala/PetApiTest.scala b/samples/client/petstore/scala-akka/src/test/scala/PetApiTest.scala index e6229fb05f3..48c8d4c644f 100644 --- a/samples/client/petstore/scala-akka/src/test/scala/PetApiTest.scala +++ b/samples/client/petstore/scala-akka/src/test/scala/PetApiTest.scala @@ -5,18 +5,19 @@ import org.openapitools.client.api._ import org.openapitools.client.core.{ApiInvoker, ApiKeyValue} import org.openapitools.client.model._ import org.scalatest.Inspectors._ -import org.scalatest._ -import org.scalatest.junit.JUnitRunner +import org.scalatest.flatspec.AsyncFlatSpec +import org.scalatest.matchers.should.Matchers +import org.scalatestplus.junit.JUnitRunner @RunWith(classOf[JUnitRunner]) class PetApiTest extends AsyncFlatSpec with Matchers { - private implicit val system: ActorSystem = ActorSystem() + implicit private val system: ActorSystem = ActorSystem() behavior of "PetApi" - val api: PetApi = PetApi() - val invoker: ApiInvoker = ApiInvoker(EnumsSerializers.all) - private implicit val apiKey: ApiKeyValue = ApiKeyValue("special-key") + val api: PetApi = PetApi() + val invoker: ApiInvoker = ApiInvoker(EnumsSerializers.all) + implicit private val apiKey: ApiKeyValue = ApiKeyValue("special-key") it should "add and fetch a pet" in { val petId = 1000 @@ -34,7 +35,7 @@ class PetApiTest extends AsyncFlatSpec with Matchers { for { addResponse <- invoker.execute(addPetRequest) - response <- invoker.execute(getPetRequest) + response <- invoker.execute(getPetRequest) } yield { addResponse.code should be(200) @@ -54,7 +55,7 @@ class PetApiTest extends AsyncFlatSpec with Matchers { } it should "update a pet" in { - val petId = (Math.random()*1000000000).toLong + val petId = (Math.random() * 1000000000).toLong val createdPet = Pet( Some(petId), Some(Category(Some(1), Some("sold"))), @@ -64,12 +65,12 @@ class PetApiTest extends AsyncFlatSpec with Matchers { Some(PetEnums.Status.Available) ) - for { - createdPet <- invoker.execute(api.addPet(createdPet)) + for { + createdPet <- invoker.execute(api.addPet(createdPet)) pet: core.ApiResponse[Pet] <- invoker.execute(api.getPetById(createdPet.content.id.get)) updatedPet = pet.content.copy(status = Some(PetEnums.Status.Sold), name = "developer") updatedPetResponse: core.ApiResponse[Pet] <- invoker.execute(api.updatePet(updatedPet)) - updatedRequested: core.ApiResponse[Pet] <- invoker.execute(api.getPetById(createdPet.content.id.get)) + updatedRequested: core.ApiResponse[Pet] <- invoker.execute(api.getPetById(createdPet.content.id.get)) } yield { pet.content.name should be("programmer") pet.content.status should be(Some(PetEnums.Status.Available)) @@ -120,4 +121,3 @@ class PetApiTest extends AsyncFlatSpec with Matchers { } */ } - diff --git a/samples/client/petstore/scala-sttp/build.sbt b/samples/client/petstore/scala-sttp/build.sbt index e7d77cdd2db..1b13385dba1 100644 --- a/samples/client/petstore/scala-sttp/build.sbt +++ b/samples/client/petstore/scala-sttp/build.sbt @@ -2,13 +2,13 @@ version := "1.0.0" name := "scala-sttp-petstore" organization := "org.openapitools" -scalaVersion := "2.13.2" -crossScalaVersions := Seq(scalaVersion.value, "2.12.10") +scalaVersion := "2.13.5" +crossScalaVersions := Seq(scalaVersion.value, "2.12.13") libraryDependencies ++= Seq( - "com.softwaremill.sttp.client" %% "core" % "2.2.0", - "com.softwaremill.sttp.client" %% "json4s" % "2.2.0", - "org.json4s" %% "json4s-jackson" % "3.6.8" + "com.softwaremill.sttp.client" %% "core" % "2.2.9", + "com.softwaremill.sttp.client" %% "json4s" % "2.2.9", + "org.json4s" %% "json4s-jackson" % "3.6.11" ) scalacOptions := Seq( diff --git a/samples/client/petstore/scala-sttp/project/build.properties b/samples/client/petstore/scala-sttp/project/build.properties index 654fe70c42c..e67343ae796 100644 --- a/samples/client/petstore/scala-sttp/project/build.properties +++ b/samples/client/petstore/scala-sttp/project/build.properties @@ -1 +1 @@ -sbt.version=1.3.12 +sbt.version=1.5.0 diff --git a/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala index 8f541ae7bfe..7bed7d54f33 100644 --- a/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala +++ b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala @@ -139,7 +139,7 @@ class PetApi(baseUrl: String) { .method(Method.POST, uri"$baseUrl/pet/${petId}") .contentType("application/x-www-form-urlencoded") .body(Map( - "name" -> name, + "name" -> name, "status" -> status )) .response(asJson[Unit]) diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py b/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py index 9345e736905..7993d12971b 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py @@ -29,6 +29,22 @@ none_type = type(None) file_type = io.IOBase +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + class cached_property(object): # this caches the result of the function call for fn with no inputs # use this as a decorator on fuction methods that you want converted @@ -284,6 +300,121 @@ class OpenApiModel(object): return new_inst + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + class ModelSimple(OpenApiModel): """the parent class of models whose type != object in their swagger/openapi""" @@ -1208,14 +1339,14 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, _spec_property_naming=spec_property_naming) if issubclass(model_class, ModelSimple): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) elif isinstance(model_data, list): - return model_class(*model_data, **kw_args) + return model_class._new_from_openapi_data(*model_data, **kw_args) if isinstance(model_data, dict): kw_args.update(model_data) - return model_class(**kw_args) + return model_class._new_from_openapi_data(**kw_args) elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) def deserialize_file(response_data, configuration, content_disposition=None): @@ -1577,22 +1708,6 @@ def get_valid_classes_phrase(input_classes): return "is one of [{0}]".format(", ".join(all_class_names)) -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python(kwargs, _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - def get_allof_instances(self, model_args, constant_args): """ Args: diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py index bb9ec1c821a..2fcf6b2de1e 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py @@ -29,6 +29,22 @@ none_type = type(None) file_type = io.IOBase +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + class cached_property(object): # this caches the result of the function call for fn with no inputs # use this as a decorator on fuction methods that you want converted @@ -284,6 +300,121 @@ class OpenApiModel(object): return new_inst + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + class ModelSimple(OpenApiModel): """the parent class of models whose type != object in their swagger/openapi""" @@ -1208,14 +1339,14 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, _spec_property_naming=spec_property_naming) if issubclass(model_class, ModelSimple): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) elif isinstance(model_data, list): - return model_class(*model_data, **kw_args) + return model_class._new_from_openapi_data(*model_data, **kw_args) if isinstance(model_data, dict): kw_args.update(model_data) - return model_class(**kw_args) + return model_class._new_from_openapi_data(**kw_args) elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) def deserialize_file(response_data, configuration, content_disposition=None): @@ -1577,22 +1708,6 @@ def get_valid_classes_phrase(input_classes): return "is one of [{0}]".format(", ".join(all_class_names)) -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python(kwargs, _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - def get_allof_instances(self, model_args, constant_args): """ Args: diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart index c847d27f60b..35b984b86a1 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart @@ -77,7 +77,7 @@ class ApiClient { ? '?${urlEncodedQueryParams.join('&')}' : ''; - final url = '$basePath$path$queryString'; + final Uri uri = Uri.parse('$basePath$path$queryString'); if (nullableContentType != null) { headerParams['Content-Type'] = nullableContentType; @@ -89,7 +89,7 @@ class ApiClient { body is MultipartFile && (nullableContentType == null || !nullableContentType.toLowerCase().startsWith('multipart/form-data')) ) { - final request = StreamedRequest(method, Uri.parse(url)); + final request = StreamedRequest(method, uri); request.headers.addAll(headerParams); request.contentLength = body.length; body.finalize().listen( @@ -103,7 +103,7 @@ class ApiClient { } if (body is MultipartRequest) { - final request = MultipartRequest(method, Uri.parse(url)); + final request = MultipartRequest(method, uri); request.fields.addAll(body.fields); request.files.addAll(body.files); request.headers.addAll(body.headers); @@ -118,12 +118,12 @@ class ApiClient { final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; switch(method) { - case 'POST': return await _client.post(url, headers: nullableHeaderParams, body: msgBody,); - case 'PUT': return await _client.put(url, headers: nullableHeaderParams, body: msgBody,); - case 'DELETE': return await _client.delete(url, headers: nullableHeaderParams,); - case 'PATCH': return await _client.patch(url, headers: nullableHeaderParams, body: msgBody,); - case 'HEAD': return await _client.head(url, headers: nullableHeaderParams,); - case 'GET': return await _client.get(url, headers: nullableHeaderParams,); + case 'POST': return await _client.post(uri, headers: nullableHeaderParams, body: msgBody,); + case 'PUT': return await _client.put(uri, headers: nullableHeaderParams, body: msgBody,); + case 'DELETE': return await _client.delete(uri, headers: nullableHeaderParams,); + case 'PATCH': return await _client.patch(uri, headers: nullableHeaderParams, body: msgBody,); + case 'HEAD': return await _client.head(uri, headers: nullableHeaderParams,); + case 'GET': return await _client.get(uri, headers: nullableHeaderParams,); } } on SocketException catch (e, trace) { throw ApiException.withInner(HttpStatus.badRequest, 'Socket operation failed: $method $path', e, trace,); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/pubspec.yaml b/samples/openapi3/client/petstore/dart2/petstore_client_lib/pubspec.yaml index 06e77263172..4d55880cd85 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/pubspec.yaml @@ -9,12 +9,12 @@ authors: - 'Author ' homepage: 'homepage' environment: - sdk: '>=2.0.0 <3.0.0' + sdk: '>=2.12.0 <3.0.0' dependencies: - http: '>=0.12.0 <0.13.0' - intl: '^0.16.1' + http: '>=0.13.0 <0.14.0' + intl: '^0.17.0' meta: '^1.1.8' dev_dependencies: - test: '>=1.3.0 <1.16.0' + test: '>=1.16.0 <1.18.0' diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart index 83cad2d3ded..0aa83cf0197 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart @@ -80,7 +80,7 @@ class ApiClient { ? '?${urlEncodedQueryParams.join('&')}' : ''; - final url = '$basePath$path$queryString'; + final Uri uri = Uri.parse('$basePath$path$queryString'); if (nullableContentType != null) { headerParams['Content-Type'] = nullableContentType; @@ -92,7 +92,7 @@ class ApiClient { body is MultipartFile && (nullableContentType == null || !nullableContentType.toLowerCase().startsWith('multipart/form-data')) ) { - final request = StreamedRequest(method, Uri.parse(url)); + final request = StreamedRequest(method, uri); request.headers.addAll(headerParams); request.contentLength = body.length; body.finalize().listen( @@ -106,7 +106,7 @@ class ApiClient { } if (body is MultipartRequest) { - final request = MultipartRequest(method, Uri.parse(url)); + final request = MultipartRequest(method, uri); request.fields.addAll(body.fields); request.files.addAll(body.files); request.headers.addAll(body.headers); @@ -121,12 +121,12 @@ class ApiClient { final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; switch(method) { - case 'POST': return await _client.post(url, headers: nullableHeaderParams, body: msgBody,); - case 'PUT': return await _client.put(url, headers: nullableHeaderParams, body: msgBody,); - case 'DELETE': return await _client.delete(url, headers: nullableHeaderParams,); - case 'PATCH': return await _client.patch(url, headers: nullableHeaderParams, body: msgBody,); - case 'HEAD': return await _client.head(url, headers: nullableHeaderParams,); - case 'GET': return await _client.get(url, headers: nullableHeaderParams,); + case 'POST': return await _client.post(uri, headers: nullableHeaderParams, body: msgBody,); + case 'PUT': return await _client.put(uri, headers: nullableHeaderParams, body: msgBody,); + case 'DELETE': return await _client.delete(uri, headers: nullableHeaderParams,); + case 'PATCH': return await _client.patch(uri, headers: nullableHeaderParams, body: msgBody,); + case 'HEAD': return await _client.head(uri, headers: nullableHeaderParams,); + case 'GET': return await _client.get(uri, headers: nullableHeaderParams,); } } on SocketException catch (e, trace) { throw ApiException.withInner(HttpStatus.badRequest, 'Socket operation failed: $method $path', e, trace,); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pubspec.yaml b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pubspec.yaml index 06e77263172..4d55880cd85 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pubspec.yaml @@ -9,12 +9,12 @@ authors: - 'Author ' homepage: 'homepage' environment: - sdk: '>=2.0.0 <3.0.0' + sdk: '>=2.12.0 <3.0.0' dependencies: - http: '>=0.12.0 <0.13.0' - intl: '^0.16.1' + http: '>=0.13.0 <0.14.0' + intl: '^0.17.0' meta: '^1.1.8' dev_dependencies: - test: '>=1.3.0 <1.16.0' + test: '>=1.16.0 <1.18.0' diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/build.yaml b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/build.yaml index b5399b955db..89a4dd6e1c2 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/build.yaml +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/build.yaml @@ -16,4 +16,3 @@ targets: field_rename: none ignore_unannotated: false include_if_null: false - nullable: true diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart index f54d8cad38d..65c9ec57844 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart @@ -80,7 +80,7 @@ class ApiClient { ? '?${urlEncodedQueryParams.join('&')}' : ''; - final url = '$basePath$path$queryString'; + final Uri uri = Uri.parse('$basePath$path$queryString'); if (nullableContentType != null) { headerParams['Content-Type'] = nullableContentType; @@ -92,7 +92,7 @@ class ApiClient { body is MultipartFile && (nullableContentType == null || !nullableContentType.toLowerCase().startsWith('multipart/form-data')) ) { - final request = StreamedRequest(method, Uri.parse(url)); + final request = StreamedRequest(method, uri); request.headers.addAll(headerParams); request.contentLength = body.length; body.finalize().listen( @@ -106,7 +106,7 @@ class ApiClient { } if (body is MultipartRequest) { - final request = MultipartRequest(method, Uri.parse(url)); + final request = MultipartRequest(method, uri); request.fields.addAll(body.fields); request.files.addAll(body.files); request.headers.addAll(body.headers); @@ -121,12 +121,12 @@ class ApiClient { final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; switch(method) { - case 'POST': return await _client.post(url, headers: nullableHeaderParams, body: msgBody,); - case 'PUT': return await _client.put(url, headers: nullableHeaderParams, body: msgBody,); - case 'DELETE': return await _client.delete(url, headers: nullableHeaderParams,); - case 'PATCH': return await _client.patch(url, headers: nullableHeaderParams, body: msgBody,); - case 'HEAD': return await _client.head(url, headers: nullableHeaderParams,); - case 'GET': return await _client.get(url, headers: nullableHeaderParams,); + case 'POST': return await _client.post(uri, headers: nullableHeaderParams, body: msgBody,); + case 'PUT': return await _client.put(uri, headers: nullableHeaderParams, body: msgBody,); + case 'DELETE': return await _client.delete(uri, headers: nullableHeaderParams,); + case 'PATCH': return await _client.patch(uri, headers: nullableHeaderParams, body: msgBody,); + case 'HEAD': return await _client.head(uri, headers: nullableHeaderParams,); + case 'GET': return await _client.get(uri, headers: nullableHeaderParams,); } } on SocketException catch (e, trace) { throw ApiException.withInner(HttpStatus.badRequest, 'Socket operation failed: $method $path', e, trace,); diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/pubspec.yaml b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/pubspec.yaml index a54b8ac2006..73931cb6b83 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/pubspec.yaml @@ -9,13 +9,13 @@ authors: - 'Author ' homepage: 'homepage' environment: - sdk: '>=2.0.0 <3.0.0' + sdk: '>=2.12.0 <3.0.0' dependencies: - http: '>=0.12.0 <0.13.0' - intl: '^0.16.1' + http: '>=0.13.0 <0.14.0' + intl: '^0.17.0' meta: '^1.1.8' json_annotation: '^3.1.1' dev_dependencies: - test: '>=1.3.0 <1.16.0' - build_runner: '^1.0.0' + test: '>=1.16.0 <1.18.0' + build_runner: '^1.10.9' json_serializable: '^3.5.1' diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py index a846775889f..f8303e680b2 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class AdditionalPropertiesClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/animal.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/animal.py index 2427f910a97..1a36f3398ff 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/animal.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/animal.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -117,7 +120,7 @@ class Animal(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/api_response.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/api_response.py index ab5e7999dd2..bddac1eb10a 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/api_response.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/api_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class ApiResponse(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py index c9b65c7e531..2975adc20e3 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ArrayOfArrayOfNumberOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py index 870286e0fc0..2a3400e7666 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ArrayOfNumberOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_test.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_test.py index 0e0c17ef190..5501a637f63 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_test.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -137,7 +140,7 @@ class ArrayTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/capitalization.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/capitalization.py index 064dc2eb2ff..cb8b0d98584 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/capitalization.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/capitalization.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -211,7 +214,7 @@ class Capitalization(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat.py index 3b6e6aa4c2e..0d9a0b20bf1 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class Cat(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat_all_of.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat_all_of.py index 7755fd65b0c..0633bbf58d0 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat_all_of.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class CatAllOf(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/category.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/category.py index c3dd5a4b9a1..ef52dcbf8c9 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/category.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/category.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -106,7 +109,7 @@ class Category(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/class_model.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/class_model.py index cd9439763d2..84c0de65b47 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/class_model.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/class_model.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ClassModel(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/client.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/client.py index f896b35240c..8d7c83ecfe6 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/client.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/client.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class Client(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog.py index 39514284d5f..61acd35cdfe 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class Dog(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog_all_of.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog_all_of.py index 207103a4874..3a052c3258a 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog_all_of.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class DogAllOf(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_arrays.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_arrays.py index b87cd37456e..eb4f3ea4ca3 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_arrays.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_arrays.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -119,7 +122,7 @@ class EnumArrays(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_class.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_class.py index 4b11877863a..79aac3570cb 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_class.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ class EnumClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_test.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_test.py index 09d7d1e3d80..93333df8878 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_test.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -285,7 +288,7 @@ class EnumTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file.py index e40cd04b014..2c1cccac0e1 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -81,7 +84,7 @@ class File(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py index d266755d260..c5a23842d4f 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class FileSchemaTestClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/foo.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/foo.py index 05abc6e9b9f..cab632f369c 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/foo.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/foo.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class Foo(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/format_test.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/format_test.py index a8323ade641..4e96a7b9175 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/format_test.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/format_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -522,7 +525,7 @@ class FormatTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py index dac8cfaff93..7175c2acc72 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class HasOnlyReadOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/health_check_result.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/health_check_result.py index cde33f5146a..64a3f4b2b90 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/health_check_result.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/health_check_result.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -78,7 +81,7 @@ class HealthCheckResult(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/inline_response_default.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/inline_response_default.py index d9da22a5fd3..a199122621f 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/inline_response_default.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/inline_response_default.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class InlineResponseDefault(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/list.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/list.py index b4425722474..6e1dea4e33b 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/list.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/list.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class List(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/map_test.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/map_test.py index 406f35db750..21bd2ccda98 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/map_test.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/map_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -165,7 +168,7 @@ class MapTest(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py index 14428a6536a..9e727b07d5c 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model200_response.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model200_response.py index 5c90147467b..db587fd24e2 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model200_response.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model200_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class Model200Response(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model_return.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model_return.py index 88174ef2308..5354fd56e2c 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model_return.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model_return.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class ModelReturn(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/name.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/name.py index 528988ebd43..0191a3a934a 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/name.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -158,7 +161,7 @@ class Name(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/nullable_class.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/nullable_class.py index 490eb2ba7d0..d36862f8526 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/nullable_class.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/nullable_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -355,7 +358,7 @@ class NullableClass(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/number_only.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/number_only.py index ebbcc8996d0..59a252e0bb6 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/number_only.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class NumberOnly(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/order.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/order.py index 6513d48a3a5..a267324d0d1 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/order.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/order.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -217,7 +220,7 @@ class Order(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_composite.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_composite.py index 44124e13c09..e26160ab430 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_composite.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_composite.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ class OuterComposite(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum.py index 77624ba1540..27cdfd1fb79 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ class OuterEnum(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_default_value.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_default_value.py index aae43db66e6..982e9599d0e 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_default_value.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_default_value.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ class OuterEnumDefaultValue(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer.py index d3d9ca3dbf9..3feec9c5a5a 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ class OuterEnumInteger(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer_default_value.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer_default_value.py index 9e0ed2c1a8b..6757a4d6367 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer_default_value.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer_default_value.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ class OuterEnumIntegerDefaultValue(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_object_with_enum_property.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_object_with_enum_property.py index 8a50b129a7f..b9572300b6f 100644 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_object_with_enum_property.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_object_with_enum_property.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -80,7 +83,7 @@ class OuterObjectWithEnumProperty(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/pet.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/pet.py index e71589429ca..22bb4a585e4 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/pet.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/pet.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -219,7 +222,7 @@ class Pet(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/read_only_first.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/read_only_first.py index 3a320fe64f0..c2888eba750 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/read_only_first.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/read_only_first.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class ReadOnlyFirst(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/special_model_name.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/special_model_name.py index 7669a508789..4c848e1887c 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/special_model_name.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/special_model_name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ class SpecialModelName(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/tag.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/tag.py index dbac885ad8e..a3e6789078d 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/tag.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/tag.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ class Tag(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/user.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/user.py index b70d84a6b40..7ae2898f6c5 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/user.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/user.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -263,7 +266,7 @@ class User(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python/.openapi-generator/FILES b/samples/openapi3/client/petstore/python/.openapi-generator/FILES index 175fdaa0919..9e23967bd9a 100644 --- a/samples/openapi3/client/petstore/python/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python/.openapi-generator/FILES @@ -64,6 +64,7 @@ docs/MapTest.md docs/MixedPropertiesAndAdditionalPropertiesClass.md docs/Model200Response.md docs/ModelReturn.md +docs/Mole.md docs/Name.md docs/NullableClass.md docs/NullableShape.md @@ -173,6 +174,7 @@ petstore_api/model/map_test.py petstore_api/model/mixed_properties_and_additional_properties_class.py petstore_api/model/model200_response.py petstore_api/model/model_return.py +petstore_api/model/mole.py petstore_api/model/name.py petstore_api/model/nullable_class.py petstore_api/model/nullable_shape.py diff --git a/samples/openapi3/client/petstore/python/README.md b/samples/openapi3/client/petstore/python/README.md index ce718fd4a46..bf7ae031db4 100644 --- a/samples/openapi3/client/petstore/python/README.md +++ b/samples/openapi3/client/petstore/python/README.md @@ -192,6 +192,7 @@ Class | Method | HTTP request | Description - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model200Response.md) - [ModelReturn](docs/ModelReturn.md) + - [Mole](docs/Mole.md) - [Name](docs/Name.md) - [NullableClass](docs/NullableClass.md) - [NullableShape](docs/NullableShape.md) diff --git a/samples/openapi3/client/petstore/python/docs/Mole.md b/samples/openapi3/client/petstore/python/docs/Mole.md new file mode 100644 index 00000000000..6c4f714963e --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/Mole.md @@ -0,0 +1,17 @@ +# Mole + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**blind** | **bool** | | [readonly] +**smell** | **str** | | +**hearing** | **bool** | | +**touch** | **bool** | | [optional] [readonly] +**taste** | **str** | | [optional] +**seeing_ghosts** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py index 82aca2a9ca8..6540576f957 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesClass(ModelNormal): @@ -104,8 +107,92 @@ class AdditionalPropertiesClass(ModelNormal): 'map_with_undeclared_properties_string': 'map_with_undeclared_properties_string', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_property ({str: (str,)}): [optional] # noqa: E501 + map_of_map_property ({str: ({str: (str,)},)}): [optional] # noqa: E501 + anytype_1 (bool, date, datetime, dict, float, int, list, str, none_type): [optional] # noqa: E501 + map_with_undeclared_properties_anytype_1 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + map_with_undeclared_properties_anytype_2 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + map_with_undeclared_properties_anytype_3 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + empty_map (dict): an object with no declared properties and no undeclared properties, hence it's an empty map.. [optional] # noqa: E501 + map_with_undeclared_properties_string ({str: (str,)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -191,3 +278,6 @@ class AdditionalPropertiesClass(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py index 67d43acfe53..f8e0b8529cc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.enum_class import EnumClass @@ -94,8 +97,84 @@ class AdditionalPropertiesWithArrayOfEnums(ModelNormal): attribute_map = { } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesWithArrayOfEnums - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +252,6 @@ class AdditionalPropertiesWithArrayOfEnums(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/address.py b/samples/openapi3/client/petstore/python/petstore_api/model/address.py index b1504407903..a7c88b8fec2 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/address.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/address.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Address(ModelNormal): @@ -88,8 +91,84 @@ class Address(ModelNormal): attribute_map = { } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Address - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +246,6 @@ class Address(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/animal.py b/samples/openapi3/client/petstore/python/petstore_api/model/animal.py index c53b1e1ad28..fda6c283ebd 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/animal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/animal.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.cat import Cat @@ -106,8 +109,89 @@ class Animal(ModelNormal): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """Animal - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -190,3 +274,6 @@ class Animal(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py b/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py index fb58224ebd4..59bde51a290 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -90,6 +93,8 @@ class AnimalFarm(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -189,3 +194,97 @@ class AnimalFarm(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """AnimalFarm - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([Animal]): # noqa: E501 + + Keyword Args: + value ([Animal]): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py b/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py index 53adb5aba12..d1f3b363bef 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ApiResponse(ModelNormal): @@ -94,8 +97,87 @@ class ApiResponse(ModelNormal): 'message': 'message', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ApiResponse - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + code (int): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + message (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -176,3 +258,6 @@ class ApiResponse(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/apple.py b/samples/openapi3/client/petstore/python/petstore_api/model/apple.py index 4068d2488e5..b5d3d62826d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/apple.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/apple.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Apple(ModelNormal): @@ -103,8 +106,89 @@ class Apple(ModelNormal): 'origin': 'origin', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, cultivar, *args, **kwargs): # noqa: E501 + """Apple - a model defined in OpenAPI + + Args: + cultivar (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + origin (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.cultivar = cultivar + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -187,3 +271,6 @@ class Apple(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py b/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py index fb161cd4c0f..469aa6e1f6e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AppleReq(ModelNormal): @@ -86,8 +89,89 @@ class AppleReq(ModelNormal): 'mealy': 'mealy', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, cultivar, *args, **kwargs): # noqa: E501 + """AppleReq - a model defined in OpenAPI + + Args: + cultivar (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + mealy (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.cultivar = cultivar + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +254,6 @@ class AppleReq(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py index 8b6a2c42d0e..16d9bda29f1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ArrayOfArrayOfNumberOnly(ModelNormal): @@ -90,8 +93,85 @@ class ArrayOfArrayOfNumberOnly(ModelNormal): 'array_array_number': 'ArrayArrayNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_array_number ([[float]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ArrayOfArrayOfNumberOnly(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py index 8d9962152ed..1a4166a6e67 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.string_enum import StringEnum @@ -90,6 +93,8 @@ class ArrayOfEnums(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -189,3 +194,97 @@ class ArrayOfEnums(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """ArrayOfEnums - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([StringEnum]): # noqa: E501 + + Keyword Args: + value ([StringEnum]): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py index 7b754dc283e..0e44ab61aff 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ArrayOfNumberOnly(ModelNormal): @@ -90,8 +93,85 @@ class ArrayOfNumberOnly(ModelNormal): 'array_number': 'ArrayNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_number ([float]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ArrayOfNumberOnly(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py index 9691a1e6037..64c180d11bc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.read_only_first import ReadOnlyFirst @@ -100,8 +103,87 @@ class ArrayTest(ModelNormal): 'array_array_of_model': 'array_array_of_model', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_of_string ([str]): [optional] # noqa: E501 + array_array_of_integer ([[int]]): [optional] # noqa: E501 + array_array_of_model ([[ReadOnlyFirst]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -182,3 +264,6 @@ class ArrayTest(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/banana.py b/samples/openapi3/client/petstore/python/petstore_api/model/banana.py index 24ad257e6d2..2e2249d2f5e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/banana.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/banana.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Banana(ModelNormal): @@ -90,8 +93,88 @@ class Banana(ModelNormal): 'length_cm': 'lengthCm', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, length_cm, *args, **kwargs): # noqa: E501 + """Banana - a model defined in OpenAPI + + Args: + length_cm (float): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.length_cm = length_cm + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +256,6 @@ class Banana(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py b/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py index 472678bd20e..ff367d1d550 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class BananaReq(ModelNormal): @@ -86,8 +89,89 @@ class BananaReq(ModelNormal): 'sweet': 'sweet', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, length_cm, *args, **kwargs): # noqa: E501 + """BananaReq - a model defined in OpenAPI + + Args: + length_cm (float): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + sweet (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.length_cm = length_cm + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +254,6 @@ class BananaReq(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py b/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py index 25b336460bc..bdf99390952 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class BasquePig(ModelNormal): @@ -90,8 +93,88 @@ class BasquePig(ModelNormal): 'class_name': 'className', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """BasquePig - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +256,6 @@ class BasquePig(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py b/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py index 6d939535cee..2f1323481dc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Capitalization(ModelNormal): @@ -100,8 +103,90 @@ class Capitalization(ModelNormal): 'att_name': 'ATT_NAME', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Capitalization - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + small_camel (str): [optional] # noqa: E501 + capital_camel (str): [optional] # noqa: E501 + small_snake (str): [optional] # noqa: E501 + capital_snake (str): [optional] # noqa: E501 + sca_eth_flow_points (str): [optional] # noqa: E501 + att_name (str): Name of the pet . [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -185,3 +270,6 @@ class Capitalization(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/cat.py b/samples/openapi3/client/petstore/python/petstore_api/model/cat.py index eeea79359fc..be46fe5abd8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/cat.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/cat.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -105,6 +108,100 @@ class Cat(ModelComposed): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Cat - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -202,6 +299,9 @@ class Cat(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py b/samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py index 7efba680b4d..a5bef948f72 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class CatAllOf(ModelNormal): @@ -90,8 +93,85 @@ class CatAllOf(ModelNormal): 'declawed': 'declawed', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """CatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class CatAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/category.py b/samples/openapi3/client/petstore/python/petstore_api/model/category.py index 4936b4f0e44..b40329c9424 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/category.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/category.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Category(ModelNormal): @@ -92,8 +95,90 @@ class Category(ModelNormal): 'id': 'id', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Category - a model defined in OpenAPI + + Args: + + Keyword Args: + name (str): defaults to "default-name" # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + """ + + name = kwargs.get('name', "default-name") + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -177,3 +262,6 @@ class Category(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py index d054cb7a97a..3644df82fc5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat_all_of import ChildCatAllOf @@ -103,6 +106,99 @@ class ChildCat(ModelComposed): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildCat - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -199,6 +295,9 @@ class ChildCat(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py index 3d732d085fb..48b725d7c3c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildCatAllOf(ModelNormal): @@ -90,8 +93,85 @@ class ChildCatAllOf(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildCatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ChildCatAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py b/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py index 9e65a937365..a3f2b58f87f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ClassModel(ModelNormal): @@ -90,8 +93,85 @@ class ClassModel(ModelNormal): '_class': '_class', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ClassModel - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ClassModel(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/client.py b/samples/openapi3/client/petstore/python/petstore_api/model/client.py index 6218de1e19e..3dca32f7926 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/client.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/client.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Client(ModelNormal): @@ -90,8 +93,85 @@ class Client(ModelNormal): 'client': 'client', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Client - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + client (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class Client(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py b/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py index e461673adbd..bd835d9a39a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.quadrilateral_interface import QuadrilateralInterface @@ -100,6 +103,99 @@ class ComplexQuadrilateral(ModelComposed): 'quadrilateral_type': 'quadrilateralType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ComplexQuadrilateral - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + quadrilateral_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -196,6 +292,9 @@ class ComplexQuadrilateral(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py index 299c866cf8f..68847c276ee 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -100,6 +103,99 @@ class ComposedOneOfNumberWithValidations(ModelComposed): 'class_name': 'className', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ComposedOneOfNumberWithValidations - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + class_name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -196,6 +292,9 @@ class ComposedOneOfNumberWithValidations(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_schema_with_props_and_no_add_props.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_schema_with_props_and_no_add_props.py index 518f4774b55..2cba94f6409 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/composed_schema_with_props_and_no_add_props.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_schema_with_props_and_no_add_props.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.tag import Tag @@ -93,6 +96,100 @@ class ComposedSchemaWithPropsAndNoAddProps(ModelComposed): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ComposedSchemaWithPropsAndNoAddProps - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] # noqa: E501 + id (int): [optional] # noqa: E501 + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -190,6 +287,9 @@ class ComposedSchemaWithPropsAndNoAddProps(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py b/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py index 82215915e84..c102f99cd28 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class DanishPig(ModelNormal): @@ -90,8 +93,88 @@ class DanishPig(ModelNormal): 'class_name': 'className', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """DanishPig - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +256,6 @@ class DanishPig(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/dog.py b/samples/openapi3/client/petstore/python/petstore_api/model/dog.py index 3452f0d040a..4a20dafa46c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/dog.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/dog.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -105,6 +108,100 @@ class Dog(ModelComposed): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Dog - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -202,6 +299,9 @@ class Dog(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py b/samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py index 962903d3a38..dbc36cb2c8f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class DogAllOf(ModelNormal): @@ -90,8 +93,85 @@ class DogAllOf(ModelNormal): 'breed': 'breed', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """DogAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class DogAllOf(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py b/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py index 24d402c3a82..41b4a5802c0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.fruit import Fruit @@ -108,8 +111,88 @@ class Drawing(ModelNormal): 'shapes': 'shapes', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Drawing - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + main_shape (Shape): [optional] # noqa: E501 + shape_or_null (ShapeOrNull): [optional] # noqa: E501 + nullable_shape (NullableShape): [optional] # noqa: E501 + shapes ([Shape]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -191,3 +274,6 @@ class Drawing(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py b/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py index db56838d7e4..da42763d9c3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class EnumArrays(ModelNormal): @@ -100,8 +103,86 @@ class EnumArrays(ModelNormal): 'array_enum': 'array_enum', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """EnumArrays - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_symbol (str): [optional] # noqa: E501 + array_enum ([str]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -181,3 +262,6 @@ class EnumArrays(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py index 63be703c38e..a9e7723b255 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class EnumClass(ModelSimple): @@ -89,6 +92,8 @@ class EnumClass(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -184,3 +189,93 @@ class EnumClass(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """EnumClass - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + + Keyword Args: + value (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "-efg" + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py index 23ddbcf9a2c..1587b332721 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.array_of_enums import ArrayOfEnums @@ -144,8 +147,98 @@ class EnumTest(ModelNormal): 'array_of_str_enum': 'ArrayOfStrEnum', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, enum_string_required, *args, **kwargs): # noqa: E501 + """EnumTest - a model defined in OpenAPI + + Args: + enum_string_required (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enum_string (str): [optional] # noqa: E501 + enum_integer (int): [optional] # noqa: E501 + enum_number (float): [optional] # noqa: E501 + string_enum (StringEnum): [optional] # noqa: E501 + integer_enum (IntegerEnum): [optional] # noqa: E501 + string_enum_with_default_value (StringEnumWithDefaultValue): [optional] # noqa: E501 + integer_enum_with_default_value (IntegerEnumWithDefaultValue): [optional] # noqa: E501 + integer_enum_one_value (IntegerEnumOneValue): [optional] # noqa: E501 + inline_array_of_str_enum ([StringEnum]): [optional] # noqa: E501 + array_of_str_enum (ArrayOfEnums): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.enum_string_required = enum_string_required + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -237,3 +330,6 @@ class EnumTest(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py index e5e4104bd02..54549b98213 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.shape_interface import ShapeInterface @@ -100,6 +103,99 @@ class EquilateralTriangle(ModelComposed): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """EquilateralTriangle - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -196,6 +292,9 @@ class EquilateralTriangle(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fake_get_inline_additional_properties_payload_array_data.py b/samples/openapi3/client/petstore/python/petstore_api/model/fake_get_inline_additional_properties_payload_array_data.py index 833bbdd8261..71b921c921f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/fake_get_inline_additional_properties_payload_array_data.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fake_get_inline_additional_properties_payload_array_data.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class FakeGetInlineAdditionalPropertiesPayloadArrayData(ModelNormal): @@ -90,8 +93,85 @@ class FakeGetInlineAdditionalPropertiesPayloadArrayData(ModelNormal): 'labels': 'labels', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """FakeGetInlineAdditionalPropertiesPayloadArrayData - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + labels ([str, none_type]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class FakeGetInlineAdditionalPropertiesPayloadArrayData(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/file.py b/samples/openapi3/client/petstore/python/petstore_api/model/file.py index 137d0026324..849f5727dc9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/file.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/file.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class File(ModelNormal): @@ -90,8 +93,85 @@ class File(ModelNormal): 'source_uri': 'sourceURI', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """File - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + source_uri (str): Test capitalization. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class File(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py index 3722125ae48..f7e154e47b7 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.file import File @@ -98,8 +101,86 @@ class FileSchemaTestClass(ModelNormal): 'files': 'files', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """FileSchemaTestClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + file (File): [optional] # noqa: E501 + files ([File]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -179,3 +260,6 @@ class FileSchemaTestClass(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/foo.py b/samples/openapi3/client/petstore/python/petstore_api/model/foo.py index 7c319dc9995..ad17251f73b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/foo.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/foo.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Foo(ModelNormal): @@ -90,8 +93,85 @@ class Foo(ModelNormal): 'bar': 'bar', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Foo - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] if omitted the server will use the default value of "bar" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class Foo(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py index cce7f7f0981..6d4b3b79d70 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class FormatTest(ModelNormal): @@ -163,8 +166,106 @@ class FormatTest(ModelNormal): 'pattern_with_digits_and_delimiter': 'pattern_with_digits_and_delimiter', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, number, byte, date, password, *args, **kwargs): # noqa: E501 + """FormatTest - a model defined in OpenAPI + + Args: + number (float): + byte (str): + date (date): + password (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + integer (int): [optional] # noqa: E501 + int32 (int): [optional] # noqa: E501 + int64 (int): [optional] # noqa: E501 + float (float): [optional] # noqa: E501 + double (float): [optional] # noqa: E501 + string (str): [optional] # noqa: E501 + binary (file_type): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + uuid (str): [optional] # noqa: E501 + uuid_no_example (str): [optional] # noqa: E501 + pattern_with_digits (str): A string that is a 10 digit number. Can have leading zeros.. [optional] # noqa: E501 + pattern_with_digits_and_delimiter (str): A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.number = number + self.byte = byte + self.date = date + self.password = password + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -264,3 +365,6 @@ class FormatTest(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py b/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py index c7283f99d0c..fedd13c38e4 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.apple import Apple @@ -115,6 +118,101 @@ class Fruit(ModelComposed): 'origin': 'origin', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Fruit - a model defined in OpenAPI + + Keyword Args: + cultivar (str): + length_cm (float): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] # noqa: E501 + origin (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -213,6 +311,9 @@ class Fruit(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py b/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py index 519aa6d20eb..01b907c5d8c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.apple_req import AppleReq @@ -104,6 +107,101 @@ class FruitReq(ModelComposed): 'length_cm': 'lengthCm', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """FruitReq - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + mealy (bool): [optional] # noqa: E501 + sweet (bool): [optional] # noqa: E501 + cultivar (str): [optional] # noqa: E501 + length_cm (float): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -202,6 +300,9 @@ class FruitReq(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py b/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py index dc9299c2a1b..99efd26f0d4 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.apple import Apple @@ -115,6 +118,101 @@ class GmFruit(ModelComposed): 'origin': 'origin', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """GmFruit - a model defined in OpenAPI + + Keyword Args: + cultivar (str): + length_cm (float): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] # noqa: E501 + origin (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -213,6 +311,9 @@ class GmFruit(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py b/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py index 70523affd89..1580c5a7b72 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat import ChildCat @@ -104,8 +107,88 @@ class GrandparentAnimal(ModelNormal): 'pet_type': 'pet_type', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, pet_type, *args, **kwargs): # noqa: E501 + """GrandparentAnimal - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.pet_type = pet_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -187,3 +270,6 @@ class GrandparentAnimal(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py index 4ea0bb08721..33d1c15b58d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class HasOnlyReadOnly(ModelNormal): @@ -92,8 +95,88 @@ class HasOnlyReadOnly(ModelNormal): 'foo': 'foo', # noqa: E501 } + read_only_vars = { + 'bar', # noqa: E501 + 'foo', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """HasOnlyReadOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + foo (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +256,6 @@ class HasOnlyReadOnly(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py b/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py index 356ddea3cb1..0b3818b7c50 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class HealthCheckResult(ModelNormal): @@ -90,8 +93,85 @@ class HealthCheckResult(ModelNormal): 'nullable_message': 'NullableMessage', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """HealthCheckResult - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + nullable_message (str, none_type): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class HealthCheckResult(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py b/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py index 9c78998902a..4ba519ea0af 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData @@ -96,8 +99,85 @@ class InlineAdditionalPropertiesRefPayload(ModelNormal): 'array_data': 'arrayData', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """InlineAdditionalPropertiesRefPayload - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_data ([FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -176,3 +256,6 @@ class InlineAdditionalPropertiesRefPayload(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py b/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py index ee93b74eac9..dbbd376e125 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData @@ -96,8 +99,85 @@ class InlineObject6(ModelNormal): 'array_data': 'arrayData', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """InlineObject6 - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_data ([FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -176,3 +256,6 @@ class InlineObject6(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py b/samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py index cb7b9985ea8..b755dbadd36 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.foo import Foo @@ -96,8 +99,85 @@ class InlineResponseDefault(ModelNormal): 'string': 'string', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """InlineResponseDefault - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + string (Foo): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -176,3 +256,6 @@ class InlineResponseDefault(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py index a31cd7c5695..2d3d1293cd3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class IntegerEnum(ModelSimple): @@ -89,6 +92,8 @@ class IntegerEnum(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -188,3 +193,97 @@ class IntegerEnum(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """IntegerEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int):, must be one of [0, 1, 2, ] # noqa: E501 + + Keyword Args: + value (int):, must be one of [0, 1, 2, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py index f8fc86bfba7..63c1a0b9a7b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class IntegerEnumOneValue(ModelSimple): @@ -87,6 +90,8 @@ class IntegerEnumOneValue(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -182,3 +187,93 @@ class IntegerEnumOneValue(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """IntegerEnumOneValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): if omitted defaults to 0, must be one of [0, ] # noqa: E501 + + Keyword Args: + value (int): if omitted defaults to 0, must be one of [0, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = 0 + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py index 3c56da865f6..008f954a0f1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class IntegerEnumWithDefaultValue(ModelSimple): @@ -89,6 +92,8 @@ class IntegerEnumWithDefaultValue(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -184,3 +189,93 @@ class IntegerEnumWithDefaultValue(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """IntegerEnumWithDefaultValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): if omitted defaults to 0, must be one of [0, 1, 2, ] # noqa: E501 + + Keyword Args: + value (int): if omitted defaults to 0, must be one of [0, 1, 2, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = 0 + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py index b1f64bcb0db..bcbc721c2b6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.shape_interface import ShapeInterface @@ -100,6 +103,99 @@ class IsoscelesTriangle(ModelComposed): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """IsoscelesTriangle - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -196,6 +292,9 @@ class IsoscelesTriangle(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/list.py b/samples/openapi3/client/petstore/python/petstore_api/model/list.py index 11b46f10b56..4b71d9deec0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/list.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/list.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class List(ModelNormal): @@ -90,8 +93,85 @@ class List(ModelNormal): '_123_list': '123-list', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """List - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _123_list (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class List(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py b/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py index 234933fe1a8..62037474b90 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.pig import Pig @@ -118,6 +121,101 @@ class Mammal(ModelComposed): 'type': 'type', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Mammal - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + has_baleen (bool): [optional] # noqa: E501 + has_teeth (bool): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -216,6 +314,9 @@ class Mammal(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py index a5418b39e73..39c3b180e88 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.string_boolean_map import StringBooleanMap @@ -106,8 +109,88 @@ class MapTest(ModelNormal): 'indirect_map': 'indirect_map', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MapTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_map_of_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_of_enum_string ({str: (str,)}): [optional] # noqa: E501 + direct_map ({str: (bool,)}): [optional] # noqa: E501 + indirect_map (StringBooleanMap): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -189,3 +272,6 @@ class MapTest(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py index 67b3f79d9e5..f46cd0b8972 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -100,8 +103,87 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): 'map': 'map', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + uuid (str): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + map ({str: (Animal,)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -182,3 +264,6 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py b/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py index 056f4c56ad3..41a8dee5fdf 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Model200Response(ModelNormal): @@ -92,8 +95,86 @@ class Model200Response(ModelNormal): '_class': 'class', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Model200Response - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (int): [optional] # noqa: E501 + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +254,6 @@ class Model200Response(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py b/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py index 5f34582cdb4..f3720b05246 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ModelReturn(ModelNormal): @@ -90,8 +93,85 @@ class ModelReturn(ModelNormal): '_return': 'return', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ModelReturn - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _return (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class ModelReturn(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mole.py b/samples/openapi3/client/petstore/python/petstore_api/model/mole.py new file mode 100644 index 00000000000..328168b2123 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/mole.py @@ -0,0 +1,284 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class Mole(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'blind': (bool,), # noqa: E501 + 'smell': (str,), # noqa: E501 + 'hearing': (bool,), # noqa: E501 + 'touch': (bool,), # noqa: E501 + 'taste': (str,), # noqa: E501 + 'seeing_ghosts': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'blind': 'blind', # noqa: E501 + 'smell': 'smell', # noqa: E501 + 'hearing': 'hearing', # noqa: E501 + 'touch': 'touch', # noqa: E501 + 'taste': 'taste', # noqa: E501 + 'seeing_ghosts': 'seeingGhosts', # noqa: E501 + } + + read_only_vars = { + 'blind', # noqa: E501 + 'touch', # noqa: E501 + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, blind, smell, hearing, *args, **kwargs): # noqa: E501 + """Mole - a model defined in OpenAPI + + Args: + blind (bool): + smell (str): + hearing (bool): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + touch (bool): [optional] # noqa: E501 + taste (str): [optional] # noqa: E501 + seeing_ghosts (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.blind = blind + self.smell = smell + self.hearing = hearing + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, smell, hearing, *args, **kwargs): # noqa: E501 + """Mole - a model defined in OpenAPI + + smell (str): + hearing (bool): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + touch (bool): [optional] # noqa: E501 + taste (str): [optional] # noqa: E501 + seeing_ghosts (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.smell = smell + self.hearing = hearing + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/name.py b/samples/openapi3/client/petstore/python/petstore_api/model/name.py index 06b387ce9bf..d46618c88a1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/name.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Name(ModelNormal): @@ -96,8 +99,93 @@ class Name(ModelNormal): '_123_number': '123Number', # noqa: E501 } + read_only_vars = { + 'snake_case', # noqa: E501 + '_123_number', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, *args, **kwargs): # noqa: E501 + """Name - a model defined in OpenAPI + + Args: + name (int): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + snake_case (int): [optional] # noqa: E501 + _property (str): [optional] # noqa: E501 + _123_number (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -182,3 +270,6 @@ class Name(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py index f2c2cb7642e..ad5e551dd0f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class NullableClass(ModelNormal): @@ -114,8 +117,97 @@ class NullableClass(ModelNormal): 'object_items_nullable': 'object_items_nullable', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NullableClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + integer_prop (int, none_type): [optional] # noqa: E501 + number_prop (float, none_type): [optional] # noqa: E501 + boolean_prop (bool, none_type): [optional] # noqa: E501 + string_prop (str, none_type): [optional] # noqa: E501 + date_prop (date, none_type): [optional] # noqa: E501 + datetime_prop (datetime, none_type): [optional] # noqa: E501 + array_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}], none_type): [optional] # noqa: E501 + array_and_items_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type], none_type): [optional] # noqa: E501 + array_items_nullable ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type]): [optional] # noqa: E501 + object_nullable ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): [optional] # noqa: E501 + object_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},)}, none_type): [optional] # noqa: E501 + object_and_items_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}, none_type): [optional] # noqa: E501 + object_items_nullable ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -206,3 +298,6 @@ class NullableClass(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py index a2cf17e3e7b..6b2a0573ade 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.quadrilateral import Quadrilateral @@ -108,6 +111,100 @@ class NullableShape(ModelComposed): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NullableShape - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + quadrilateral_type (str): [optional] # noqa: E501 + triangle_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -205,6 +302,9 @@ class NullableShape(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py index cb2c9e2ad52..a96d9165056 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class NumberOnly(ModelNormal): @@ -90,8 +93,85 @@ class NumberOnly(ModelNormal): 'just_number': 'JustNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_number (float): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class NumberOnly(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py index a3b2746c22b..afcbf8463ea 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class NumberWithValidations(ModelSimple): @@ -88,6 +91,8 @@ class NumberWithValidations(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -187,3 +192,97 @@ class NumberWithValidations(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """NumberWithValidations - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (float): # noqa: E501 + + Keyword Args: + value (float): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py index 7ba55b76eb2..23d16918fd6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ObjectInterface(ModelNormal): @@ -88,8 +91,84 @@ class ObjectInterface(ModelNormal): attribute_map = { } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ObjectInterface - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +246,6 @@ class ObjectInterface(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py index 11db10a6128..56a55a14c09 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.number_with_validations import NumberWithValidations @@ -104,8 +107,88 @@ class ObjectModelWithRefProps(ModelNormal): 'my_boolean': 'my_boolean', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ObjectModelWithRefProps - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + my_number (NumberWithValidations): [optional] # noqa: E501 + my_readonly (Readonly): [optional] # noqa: E501 + my_string (str): [optional] # noqa: E501 + my_boolean (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -187,3 +270,6 @@ class ObjectModelWithRefProps(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py index e03392b1154..dd38862e11b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ObjectWithValidations(ModelNormal): @@ -91,8 +94,84 @@ class ObjectWithValidations(ModelNormal): attribute_map = { } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ObjectWithValidations - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +249,6 @@ class ObjectWithValidations(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/order.py b/samples/openapi3/client/petstore/python/petstore_api/model/order.py index 48207e4560e..eeefff1513f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/order.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/order.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Order(ModelNormal): @@ -105,8 +108,90 @@ class Order(ModelNormal): 'complete': 'complete', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Order - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + pet_id (int): [optional] # noqa: E501 + quantity (int): [optional] # noqa: E501 + ship_date (datetime): [optional] # noqa: E501 + status (str): Order Status. [optional] # noqa: E501 + complete (bool): [optional] if omitted the server will use the default value of False # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -190,3 +275,6 @@ class Order(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py b/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py index bda9c277996..ff58abf3d79 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat import ChildCat @@ -103,6 +106,98 @@ class ParentPet(ModelComposed): 'pet_type': 'pet_type', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ParentPet - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -198,6 +293,9 @@ class ParentPet(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/pet.py b/samples/openapi3/client/petstore/python/petstore_api/model/pet.py index b0c8b08607d..8946f6d4bea 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/pet.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/pet.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.category import Category @@ -113,8 +116,94 @@ class Pet(ModelNormal): 'status': 'status', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, photo_urls, *args, **kwargs): # noqa: E501 + """Pet - a model defined in OpenAPI + + Args: + name (str): + photo_urls ([str]): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + category (Category): [optional] # noqa: E501 + tags ([Tag]): [optional] # noqa: E501 + status (str): pet status in the store. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + self.photo_urls = photo_urls + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -202,3 +291,6 @@ class Pet(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/pig.py b/samples/openapi3/client/petstore/python/petstore_api/model/pig.py index 21f61c65de0..07845be55eb 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/pig.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.basque_pig import BasquePig @@ -104,6 +107,98 @@ class Pig(ModelComposed): 'class_name': 'className', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Pig - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -199,6 +294,9 @@ class Pig(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py index d15d37cdbca..b3aefcd1bd5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral @@ -106,6 +109,99 @@ class Quadrilateral(ModelComposed): 'shape_type': 'shapeType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Quadrilateral - a model defined in OpenAPI + + Keyword Args: + quadrilateral_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + shape_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -202,6 +298,9 @@ class Quadrilateral(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py index 872608885ac..5ca8fae392a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class QuadrilateralInterface(ModelNormal): @@ -90,8 +93,88 @@ class QuadrilateralInterface(ModelNormal): 'quadrilateral_type': 'quadrilateralType', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, quadrilateral_type, *args, **kwargs): # noqa: E501 + """QuadrilateralInterface - a model defined in OpenAPI + + Args: + quadrilateral_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.quadrilateral_type = quadrilateral_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +256,6 @@ class QuadrilateralInterface(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py b/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py index 0302bf96a7e..38cb5e2634f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ReadOnlyFirst(ModelNormal): @@ -92,8 +95,87 @@ class ReadOnlyFirst(ModelNormal): 'baz': 'baz', # noqa: E501 } + read_only_vars = { + 'bar', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ReadOnlyFirst - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + baz (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +255,6 @@ class ReadOnlyFirst(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/readonly.py b/samples/openapi3/client/petstore/python/petstore_api/model/readonly.py index 7d038917bb4..9a98af452eb 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/readonly.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/readonly.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Readonly(ModelNormal): @@ -90,8 +93,85 @@ class Readonly(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Readonly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class Readonly(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py index 86fc0a4f495..a10ce28f172 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.shape_interface import ShapeInterface @@ -100,6 +103,99 @@ class ScaleneTriangle(ModelComposed): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ScaleneTriangle - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -196,6 +292,9 @@ class ScaleneTriangle(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape.py b/samples/openapi3/client/petstore/python/petstore_api/model/shape.py index 763a7aa362b..50e21b8c8d8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/shape.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/shape.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.quadrilateral import Quadrilateral @@ -108,6 +111,100 @@ class Shape(ModelComposed): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Shape - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + quadrilateral_type (str): [optional] # noqa: E501 + triangle_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -205,6 +302,9 @@ class Shape(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py index b8ab31fc31c..0f11d5a1446 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ShapeInterface(ModelNormal): @@ -90,8 +93,88 @@ class ShapeInterface(ModelNormal): 'shape_type': 'shapeType', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, shape_type, *args, **kwargs): # noqa: E501 + """ShapeInterface - a model defined in OpenAPI + + Args: + shape_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.shape_type = shape_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +256,6 @@ class ShapeInterface(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py b/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py index 403449e0c9c..00ae221f8a6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.quadrilateral import Quadrilateral @@ -108,6 +111,100 @@ class ShapeOrNull(ModelComposed): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ShapeOrNull - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + quadrilateral_type (str): [optional] # noqa: E501 + triangle_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -205,6 +302,9 @@ class ShapeOrNull(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py b/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py index d68f1d3b5cb..1a3bef4c26e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.quadrilateral_interface import QuadrilateralInterface @@ -100,6 +103,99 @@ class SimpleQuadrilateral(ModelComposed): 'quadrilateral_type': 'quadrilateralType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SimpleQuadrilateral - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + quadrilateral_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -196,6 +292,9 @@ class SimpleQuadrilateral(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py b/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py index 72687c02ab6..3c3215d357b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.object_interface import ObjectInterface @@ -94,6 +97,97 @@ class SomeObject(ModelComposed): attribute_map = { } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SomeObject - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -188,6 +282,9 @@ class SomeObject(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py b/samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py index 3fba94014b5..76e776ae67f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class SomeObjectWithSelfAttr(ModelNormal): @@ -90,8 +93,85 @@ class SomeObjectWithSelfAttr(ModelNormal): '_self': 'self', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SomeObjectWithSelfAttr - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _self (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class SomeObjectWithSelfAttr(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py b/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py index cfaedbc7881..cc2e49f6bcb 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class SpecialModelName(ModelNormal): @@ -90,8 +93,85 @@ class SpecialModelName(ModelNormal): 'special_property_name': '$special[property.name]', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SpecialModelName - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + special_property_name (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ class SpecialModelName(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py b/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py index 4ac52699183..05f8527fec1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class StringBooleanMap(ModelNormal): @@ -88,8 +91,84 @@ class StringBooleanMap(ModelNormal): attribute_map = { } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """StringBooleanMap - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +246,6 @@ class StringBooleanMap(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py index 1e48fdecbf4..890e25eeddc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class StringEnum(ModelSimple): @@ -95,6 +98,8 @@ lines''', attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -198,3 +203,101 @@ lines''', '''double quote path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """StringEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str):, must be one of ["placed", "approved", "delivered", "single quoted", '''multiple +lines''', '''double quote + with newline''', ] # noqa: E501 + + Keyword Args: + value (str):, must be one of ["placed", "approved", "delivered", "single quoted", '''multiple +lines''', '''double quote + with newline''', ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py index 1417d0ff0fc..3861e56a08c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class StringEnumWithDefaultValue(ModelSimple): @@ -89,6 +92,8 @@ class StringEnumWithDefaultValue(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -184,3 +189,93 @@ class StringEnumWithDefaultValue(ModelSimple): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """StringEnumWithDefaultValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): if omitted defaults to "placed", must be one of ["placed", "approved", "delivered", ] # noqa: E501 + + Keyword Args: + value (str): if omitted defaults to "placed", must be one of ["placed", "approved", "delivered", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "placed" + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/tag.py b/samples/openapi3/client/petstore/python/petstore_api/model/tag.py index 0e7427effa6..95a08c18073 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/tag.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/tag.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Tag(ModelNormal): @@ -92,8 +95,86 @@ class Tag(ModelNormal): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Tag - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +254,6 @@ class Tag(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py index b1112e24892..f9082e2098f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.equilateral_triangle import EquilateralTriangle @@ -109,6 +112,99 @@ class Triangle(ModelComposed): 'shape_type': 'shapeType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Triangle - a model defined in OpenAPI + + Keyword Args: + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + shape_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -205,6 +301,9 @@ class Triangle(ModelComposed): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py index f31e3dba135..783e5fe3bf8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class TriangleInterface(ModelNormal): @@ -90,8 +93,88 @@ class TriangleInterface(ModelNormal): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, triangle_type, *args, **kwargs): # noqa: E501 + """TriangleInterface - a model defined in OpenAPI + + Args: + triangle_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.triangle_type = triangle_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +256,6 @@ class TriangleInterface(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/user.py b/samples/openapi3/client/petstore/python/petstore_api/model/user.py index 2271e3e37e5..f77ab381d21 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/user.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/user.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class User(ModelNormal): @@ -112,8 +115,96 @@ class User(ModelNormal): 'any_type_prop_nullable': 'anyTypePropNullable', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """User - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + username (str): [optional] # noqa: E501 + first_name (str): [optional] # noqa: E501 + last_name (str): [optional] # noqa: E501 + email (str): [optional] # noqa: E501 + password (str): [optional] # noqa: E501 + phone (str): [optional] # noqa: E501 + user_status (int): User Status. [optional] # noqa: E501 + object_with_no_declared_props ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value.. [optional] # noqa: E501 + object_with_no_declared_props_nullable ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): test code generation for nullable objects. Value must be a map of strings to values or the 'null' value.. [optional] # noqa: E501 + any_type_prop (bool, date, datetime, dict, float, int, list, str, none_type): test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389. [optional] # noqa: E501 + any_type_prop_nullable (bool, date, datetime, dict, float, int, list, str, none_type): test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -203,3 +294,6 @@ class User(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/whale.py b/samples/openapi3/client/petstore/python/petstore_api/model/whale.py index c3e1c40b4e5..a8eb263b118 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/whale.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/whale.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Whale(ModelNormal): @@ -94,8 +97,90 @@ class Whale(ModelNormal): 'has_teeth': 'hasTeeth', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """Whale - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + has_baleen (bool): [optional] # noqa: E501 + has_teeth (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -179,3 +264,6 @@ class Whale(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py b/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py index bf5bbbefa9c..c348b331671 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py @@ -25,6 +25,9 @@ from petstore_api.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Zebra(ModelNormal): @@ -97,8 +100,89 @@ class Zebra(ModelNormal): 'type': 'type', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """Zebra - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -181,3 +265,6 @@ class Zebra(ModelNormal): # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model_utils.py b/samples/openapi3/client/petstore/python/petstore_api/model_utils.py index 3a555f0a88c..3913228d6b8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model_utils.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model_utils.py @@ -29,6 +29,22 @@ none_type = type(None) file_type = io.IOBase +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + class cached_property(object): # this caches the result of the function call for fn with no inputs # use this as a decorator on fuction methods that you want converted @@ -284,6 +300,121 @@ class OpenApiModel(object): return new_inst + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + class ModelSimple(OpenApiModel): """the parent class of models whose type != object in their swagger/openapi""" @@ -1208,14 +1339,14 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, _spec_property_naming=spec_property_naming) if issubclass(model_class, ModelSimple): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) elif isinstance(model_data, list): - return model_class(*model_data, **kw_args) + return model_class._new_from_openapi_data(*model_data, **kw_args) if isinstance(model_data, dict): kw_args.update(model_data) - return model_class(**kw_args) + return model_class._new_from_openapi_data(**kw_args) elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) def deserialize_file(response_data, configuration, content_disposition=None): @@ -1577,22 +1708,6 @@ def get_valid_classes_phrase(input_classes): return "is one of [{0}]".format(", ".join(all_class_names)) -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python(kwargs, _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - def get_allof_instances(self, model_args, constant_args): """ Args: diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py index ef47f62075b..f18e33defce 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py @@ -67,6 +67,7 @@ from petstore_api.model.map_test import MapTest from petstore_api.model.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass from petstore_api.model.model200_response import Model200Response from petstore_api.model.model_return import ModelReturn +from petstore_api.model.mole import Mole from petstore_api.model.name import Name from petstore_api.model.nullable_class import NullableClass from petstore_api.model.nullable_shape import NullableShape diff --git a/samples/openapi3/client/petstore/python/test/test_mole.py b/samples/openapi3/client/petstore/python/test/test_mole.py new file mode 100644 index 00000000000..176fdf03a31 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_mole.py @@ -0,0 +1,35 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.mole import Mole + + +class TestMole(unittest.TestCase): + """Mole unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testMole(self): + """Test Mole""" + # FIXME: construct object with mandatory attributes with example values + # mole = Mole() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_mole.py b/samples/openapi3/client/petstore/python/tests_manual/test_mole.py new file mode 100644 index 00000000000..fa8bf28c308 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_mole.py @@ -0,0 +1,78 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest +from petstore_api.exceptions import ApiAttributeError + +import petstore_api + +try: + from petstore_api.model import mole +except ImportError: + mole = sys.modules["petstore_api.model.mole"] + + +class TestMole(unittest.TestCase): + """Triangle unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testMole(self): + # includes required parameters that are `readOnly=False` and not defined `readOnly` + my_mole = mole.Mole(smell="dirt", hearing=False) + assert my_mole.smell == "dirt" + assert my_mole.hearing is False + + # includes required parameters that `readOnly=False`, an optional `readOnly=False` and not defined `readOnly` + my_mole = mole.Mole(smell="dirt", taste="kfc", hearing=True) + assert my_mole.smell == "dirt" + assert my_mole.taste == "kfc" + assert my_mole.hearing is True + + # includes required parameters that `readOnly=False`, and required not defined `readOnly`, and an optional not defined + my_mole = mole.Mole(smell="dirt", seeing_ghosts=True, hearing=False) + assert my_mole.smell == "dirt" + assert my_mole.seeing_ghosts is True + assert my_mole.hearing is False + + # passing in required readOnly parameters raises an exception + with self.assertRaises(ApiAttributeError): + mole.Mole(smell="dirt", hearing=False, blind=True) + + # passing in optional readOnly parameters raises an exception + with self.assertRaises(ApiAttributeError): + mole.Mole(smell="dirt", hearing=False, touch=True) + + # passing in required an optional parameters with readOnly true or false works with from_openapi_data + my_mole = mole.Mole._from_openapi_data( + smell="dirt", + taste="kfc", + blind=True, + touch=False, + hearing=True, + seeing_ghosts=False, + ) + assert my_mole.smell == "dirt" + assert my_mole.taste == "kfc" + assert my_mole.blind is True + assert my_mole.touch is False + assert my_mole.hearing is True + assert my_mole.seeing_ghosts is False + + +if __name__ == "__main__": + unittest.main() diff --git a/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts index 12d711bd5b7..547125db459 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts @@ -19,8 +19,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public async addPet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async addPet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -32,7 +32,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -57,7 +57,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -70,8 +70,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param petId Pet id to delete * @param apiKey */ - public async deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -85,7 +85,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -100,7 +100,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -113,8 +113,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'status' is not null or undefined if (status === null || status === undefined) { @@ -126,7 +126,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByStatus'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -143,7 +143,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -156,8 +156,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by tags * @param tags Tags to filter by */ - public async findPetsByTags(tags: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByTags(tags: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'tags' is not null or undefined if (tags === null || tags === undefined) { @@ -169,7 +169,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByTags'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -186,7 +186,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -199,8 +199,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Find pet by ID * @param petId ID of pet to return */ - public async getPetById(petId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getPetById(petId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -213,7 +213,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -227,7 +227,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -239,8 +239,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public async updatePet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -252,7 +252,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -277,7 +277,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -291,8 +291,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param name Updated name of the pet * @param status Updated status of the pet */ - public async updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -307,7 +307,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -331,7 +331,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -345,8 +345,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - let config = options || this.configuration; + public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -361,7 +361,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -385,7 +385,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/default/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/default/apis/StoreApi.ts index 12be0132697..7780dd52f48 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/apis/StoreApi.ts @@ -19,8 +19,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public async deleteOrder(orderId: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteOrder(orderId: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -33,7 +33,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -54,14 +54,14 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public async getInventory(options?: Configuration): Promise { - let config = options || this.configuration; + public async getInventory(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/store/inventory'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -75,7 +75,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -88,8 +88,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public async getOrderById(orderId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getOrderById(orderId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -102,7 +102,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -123,8 +123,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Place an order for a pet * @param order order placed for purchasing the pet */ - public async placeOrder(order: Order, options?: Configuration): Promise { - let config = options || this.configuration; + public async placeOrder(order: Order, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'order' is not null or undefined if (order === null || order === undefined) { @@ -136,7 +136,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/store/order'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params diff --git a/samples/openapi3/client/petstore/typescript/builds/default/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/default/apis/UserApi.ts index 0717cb75304..e12b26fd31d 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/apis/UserApi.ts @@ -19,8 +19,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Create user * @param user Created user object */ - public async createUser(user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUser(user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -32,7 +32,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -55,7 +55,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -67,8 +67,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -80,7 +80,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithArray'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -103,7 +103,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -115,8 +115,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithListInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithListInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -128,7 +128,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithList'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -151,7 +151,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -164,8 +164,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Delete user * @param username The name that needs to be deleted */ - public async deleteUser(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteUser(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -178,7 +178,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -192,7 +192,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -204,8 +204,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public async getUserByName(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async getUserByName(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -218,7 +218,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -240,8 +240,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username The user name for login * @param password The password for login in clear text */ - public async loginUser(username: string, password: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async loginUser(username: string, password: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -259,7 +259,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/login'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -285,14 +285,14 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { /** * Logs out current logged in user session */ - public async logoutUser(options?: Configuration): Promise { - let config = options || this.configuration; + public async logoutUser(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/user/logout'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -306,7 +306,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -320,8 +320,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username name that need to be deleted * @param user Updated user object */ - public async updateUser(username: string, user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async updateUser(username: string, user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -340,7 +340,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -363,7 +363,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/default/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/default/types/ObservableAPI.ts index 459fbc8e226..488915f871b 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/types/ObservableAPI.ts @@ -30,8 +30,8 @@ export class ObservablePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.addPet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -54,8 +54,8 @@ export class ObservablePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -78,8 +78,8 @@ export class ObservablePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByStatus(status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -102,8 +102,8 @@ export class ObservablePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByTags(tags, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -126,8 +126,8 @@ export class ObservablePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getPetById(petId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -149,8 +149,8 @@ export class ObservablePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -174,8 +174,8 @@ export class ObservablePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -199,8 +199,8 @@ export class ObservablePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -241,8 +241,8 @@ export class ObservableStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteOrder(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -264,8 +264,8 @@ export class ObservableStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Observable<{ [key: string]: number; }> { - const requestContextPromise = this.requestFactory.getInventory(options); + public getInventory(_options?: Configuration): Observable<{ [key: string]: number; }> { + const requestContextPromise = this.requestFactory.getInventory(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -288,8 +288,8 @@ export class ObservableStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getOrderById(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -311,8 +311,8 @@ export class ObservableStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.placeOrder(order, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -353,8 +353,8 @@ export class ObservableUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUser(user, options); + public createUser(user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUser(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -376,8 +376,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -399,8 +399,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithListInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -423,8 +423,8 @@ export class ObservableUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteUser(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -446,8 +446,8 @@ export class ObservableUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getUserByName(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -470,8 +470,8 @@ export class ObservableUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.loginUser(username, password, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -492,8 +492,8 @@ export class ObservableUserApi { /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.logoutUser(options); + public logoutUser(_options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.logoutUser(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -517,8 +517,8 @@ export class ObservableUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updateUser(username, user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); diff --git a/samples/openapi3/client/petstore/typescript/builds/default/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/default/types/PromiseAPI.ts index 2129b103e7e..ac44ba7a13b 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/types/PromiseAPI.ts @@ -26,8 +26,8 @@ export class PromisePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Promise { - const result = this.api.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.addPet(pet, _options); return result.toPromise(); } @@ -36,8 +36,8 @@ export class PromisePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - const result = this.api.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + const result = this.api.deletePet(petId, apiKey, _options); return result.toPromise(); } @@ -46,8 +46,8 @@ export class PromisePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise> { - const result = this.api.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise> { + const result = this.api.findPetsByStatus(status, _options); return result.toPromise(); } @@ -56,8 +56,8 @@ export class PromisePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Promise> { - const result = this.api.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Promise> { + const result = this.api.findPetsByTags(tags, _options); return result.toPromise(); } @@ -66,8 +66,8 @@ export class PromisePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Promise { - const result = this.api.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Promise { + const result = this.api.getPetById(petId, _options); return result.toPromise(); } @@ -75,8 +75,8 @@ export class PromisePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Promise { - const result = this.api.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.updatePet(pet, _options); return result.toPromise(); } @@ -86,8 +86,8 @@ export class PromisePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - const result = this.api.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + const result = this.api.updatePetWithForm(petId, name, status, _options); return result.toPromise(); } @@ -97,8 +97,8 @@ export class PromisePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - const result = this.api.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + const result = this.api.uploadFile(petId, additionalMetadata, file, _options); return result.toPromise(); } @@ -126,8 +126,8 @@ export class PromiseStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Promise { - const result = this.api.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Promise { + const result = this.api.deleteOrder(orderId, _options); return result.toPromise(); } @@ -135,8 +135,8 @@ export class PromiseStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Promise<{ [key: string]: number; }> { - const result = this.api.getInventory(options); + public getInventory(_options?: Configuration): Promise<{ [key: string]: number; }> { + const result = this.api.getInventory(_options); return result.toPromise(); } @@ -145,8 +145,8 @@ export class PromiseStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Promise { - const result = this.api.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Promise { + const result = this.api.getOrderById(orderId, _options); return result.toPromise(); } @@ -154,8 +154,8 @@ export class PromiseStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Promise { - const result = this.api.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Promise { + const result = this.api.placeOrder(order, _options); return result.toPromise(); } @@ -183,8 +183,8 @@ export class PromiseUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Promise { - const result = this.api.createUser(user, options); + public createUser(user: User, _options?: Configuration): Promise { + const result = this.api.createUser(user, _options); return result.toPromise(); } @@ -192,8 +192,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithArrayInput(user, _options); return result.toPromise(); } @@ -201,8 +201,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithListInput(user, _options); return result.toPromise(); } @@ -211,8 +211,8 @@ export class PromiseUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Promise { - const result = this.api.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Promise { + const result = this.api.deleteUser(username, _options); return result.toPromise(); } @@ -220,8 +220,8 @@ export class PromiseUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Promise { - const result = this.api.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Promise { + const result = this.api.getUserByName(username, _options); return result.toPromise(); } @@ -230,16 +230,16 @@ export class PromiseUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Promise { - const result = this.api.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Promise { + const result = this.api.loginUser(username, password, _options); return result.toPromise(); } /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Promise { - const result = this.api.logoutUser(options); + public logoutUser(_options?: Configuration): Promise { + const result = this.api.logoutUser(_options); return result.toPromise(); } @@ -249,8 +249,8 @@ export class PromiseUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Promise { - const result = this.api.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Promise { + const result = this.api.updateUser(username, user, _options); return result.toPromise(); } diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts index 552716b7cb3..cb9a2dfd3e6 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts @@ -18,8 +18,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public async addPet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async addPet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -31,7 +31,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -56,7 +56,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -69,8 +69,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param petId Pet id to delete * @param apiKey */ - public async deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -84,7 +84,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -99,7 +99,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -112,8 +112,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'status' is not null or undefined if (status === null || status === undefined) { @@ -125,7 +125,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByStatus'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -142,7 +142,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -155,8 +155,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by tags * @param tags Tags to filter by */ - public async findPetsByTags(tags: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByTags(tags: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'tags' is not null or undefined if (tags === null || tags === undefined) { @@ -168,7 +168,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByTags'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -185,7 +185,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -198,8 +198,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Find pet by ID * @param petId ID of pet to return */ - public async getPetById(petId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getPetById(petId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -212,7 +212,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -226,7 +226,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -238,8 +238,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public async updatePet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -251,7 +251,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -276,7 +276,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -290,8 +290,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param name Updated name of the pet * @param status Updated status of the pet */ - public async updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -306,7 +306,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -330,7 +330,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -344,8 +344,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - let config = options || this.configuration; + public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -360,7 +360,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -384,7 +384,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/deno/apis/StoreApi.ts index f677c988a10..2cedbd705a6 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/apis/StoreApi.ts @@ -18,8 +18,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public async deleteOrder(orderId: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteOrder(orderId: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -32,7 +32,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -53,14 +53,14 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public async getInventory(options?: Configuration): Promise { - let config = options || this.configuration; + public async getInventory(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/store/inventory'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -74,7 +74,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -87,8 +87,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public async getOrderById(orderId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getOrderById(orderId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -101,7 +101,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -122,8 +122,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Place an order for a pet * @param order order placed for purchasing the pet */ - public async placeOrder(order: Order, options?: Configuration): Promise { - let config = options || this.configuration; + public async placeOrder(order: Order, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'order' is not null or undefined if (order === null || order === undefined) { @@ -135,7 +135,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/store/order'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/deno/apis/UserApi.ts index 3757165b71a..7972e160583 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/apis/UserApi.ts @@ -18,8 +18,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Create user * @param user Created user object */ - public async createUser(user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUser(user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -31,7 +31,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -54,7 +54,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -66,8 +66,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -79,7 +79,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithArray'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -102,7 +102,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -114,8 +114,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithListInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithListInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -127,7 +127,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithList'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -150,7 +150,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -163,8 +163,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Delete user * @param username The name that needs to be deleted */ - public async deleteUser(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteUser(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -177,7 +177,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -191,7 +191,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -203,8 +203,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public async getUserByName(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async getUserByName(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -217,7 +217,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -239,8 +239,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username The user name for login * @param password The password for login in clear text */ - public async loginUser(username: string, password: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async loginUser(username: string, password: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -258,7 +258,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/login'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -284,14 +284,14 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { /** * Logs out current logged in user session */ - public async logoutUser(options?: Configuration): Promise { - let config = options || this.configuration; + public async logoutUser(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/user/logout'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -305,7 +305,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -319,8 +319,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username name that need to be deleted * @param user Updated user object */ - public async updateUser(username: string, user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async updateUser(username: string, user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -339,7 +339,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -362,7 +362,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/deno/types/ObservableAPI.ts index 318c8a3e1bf..cde73c04cc0 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/types/ObservableAPI.ts @@ -30,8 +30,8 @@ export class ObservablePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.addPet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -54,8 +54,8 @@ export class ObservablePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -78,8 +78,8 @@ export class ObservablePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByStatus(status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -102,8 +102,8 @@ export class ObservablePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByTags(tags, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -126,8 +126,8 @@ export class ObservablePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getPetById(petId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -149,8 +149,8 @@ export class ObservablePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -174,8 +174,8 @@ export class ObservablePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -199,8 +199,8 @@ export class ObservablePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -241,8 +241,8 @@ export class ObservableStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteOrder(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -264,8 +264,8 @@ export class ObservableStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Observable<{ [key: string]: number; }> { - const requestContextPromise = this.requestFactory.getInventory(options); + public getInventory(_options?: Configuration): Observable<{ [key: string]: number; }> { + const requestContextPromise = this.requestFactory.getInventory(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -288,8 +288,8 @@ export class ObservableStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getOrderById(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -311,8 +311,8 @@ export class ObservableStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.placeOrder(order, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -353,8 +353,8 @@ export class ObservableUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUser(user, options); + public createUser(user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUser(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -376,8 +376,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -399,8 +399,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithListInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -423,8 +423,8 @@ export class ObservableUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteUser(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -446,8 +446,8 @@ export class ObservableUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getUserByName(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -470,8 +470,8 @@ export class ObservableUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.loginUser(username, password, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -492,8 +492,8 @@ export class ObservableUserApi { /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.logoutUser(options); + public logoutUser(_options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.logoutUser(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -517,8 +517,8 @@ export class ObservableUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updateUser(username, user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/deno/types/PromiseAPI.ts index 5e2f7df9735..76db56cbc8b 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/types/PromiseAPI.ts @@ -26,8 +26,8 @@ export class PromisePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Promise { - const result = this.api.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.addPet(pet, _options); return result.toPromise(); } @@ -36,8 +36,8 @@ export class PromisePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - const result = this.api.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + const result = this.api.deletePet(petId, apiKey, _options); return result.toPromise(); } @@ -46,8 +46,8 @@ export class PromisePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise> { - const result = this.api.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise> { + const result = this.api.findPetsByStatus(status, _options); return result.toPromise(); } @@ -56,8 +56,8 @@ export class PromisePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Promise> { - const result = this.api.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Promise> { + const result = this.api.findPetsByTags(tags, _options); return result.toPromise(); } @@ -66,8 +66,8 @@ export class PromisePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Promise { - const result = this.api.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Promise { + const result = this.api.getPetById(petId, _options); return result.toPromise(); } @@ -75,8 +75,8 @@ export class PromisePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Promise { - const result = this.api.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.updatePet(pet, _options); return result.toPromise(); } @@ -86,8 +86,8 @@ export class PromisePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - const result = this.api.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + const result = this.api.updatePetWithForm(petId, name, status, _options); return result.toPromise(); } @@ -97,8 +97,8 @@ export class PromisePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - const result = this.api.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + const result = this.api.uploadFile(petId, additionalMetadata, file, _options); return result.toPromise(); } @@ -126,8 +126,8 @@ export class PromiseStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Promise { - const result = this.api.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Promise { + const result = this.api.deleteOrder(orderId, _options); return result.toPromise(); } @@ -135,8 +135,8 @@ export class PromiseStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Promise<{ [key: string]: number; }> { - const result = this.api.getInventory(options); + public getInventory(_options?: Configuration): Promise<{ [key: string]: number; }> { + const result = this.api.getInventory(_options); return result.toPromise(); } @@ -145,8 +145,8 @@ export class PromiseStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Promise { - const result = this.api.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Promise { + const result = this.api.getOrderById(orderId, _options); return result.toPromise(); } @@ -154,8 +154,8 @@ export class PromiseStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Promise { - const result = this.api.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Promise { + const result = this.api.placeOrder(order, _options); return result.toPromise(); } @@ -183,8 +183,8 @@ export class PromiseUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Promise { - const result = this.api.createUser(user, options); + public createUser(user: User, _options?: Configuration): Promise { + const result = this.api.createUser(user, _options); return result.toPromise(); } @@ -192,8 +192,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithArrayInput(user, _options); return result.toPromise(); } @@ -201,8 +201,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithListInput(user, _options); return result.toPromise(); } @@ -211,8 +211,8 @@ export class PromiseUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Promise { - const result = this.api.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Promise { + const result = this.api.deleteUser(username, _options); return result.toPromise(); } @@ -220,8 +220,8 @@ export class PromiseUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Promise { - const result = this.api.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Promise { + const result = this.api.getUserByName(username, _options); return result.toPromise(); } @@ -230,16 +230,16 @@ export class PromiseUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Promise { - const result = this.api.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Promise { + const result = this.api.loginUser(username, password, _options); return result.toPromise(); } /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Promise { - const result = this.api.logoutUser(options); + public logoutUser(_options?: Configuration): Promise { + const result = this.api.logoutUser(_options); return result.toPromise(); } @@ -249,8 +249,8 @@ export class PromiseUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Promise { - const result = this.api.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Promise { + const result = this.api.updateUser(username, user, _options); return result.toPromise(); } diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts index 2225d19dbb9..a127fccfbc2 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts @@ -21,8 +21,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public async addPet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async addPet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -34,7 +34,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -59,7 +59,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -72,8 +72,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param petId Pet id to delete * @param apiKey */ - public async deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -87,7 +87,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -102,7 +102,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -115,8 +115,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'status' is not null or undefined if (status === null || status === undefined) { @@ -128,7 +128,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByStatus'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -145,7 +145,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -158,8 +158,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by tags * @param tags Tags to filter by */ - public async findPetsByTags(tags: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByTags(tags: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'tags' is not null or undefined if (tags === null || tags === undefined) { @@ -171,7 +171,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByTags'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -188,7 +188,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -201,8 +201,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Find pet by ID * @param petId ID of pet to return */ - public async getPetById(petId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getPetById(petId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -215,7 +215,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -229,7 +229,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -241,8 +241,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public async updatePet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -254,7 +254,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -279,7 +279,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -293,8 +293,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param name Updated name of the pet * @param status Updated status of the pet */ - public async updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -309,7 +309,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -333,7 +333,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -347,8 +347,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - let config = options || this.configuration; + public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -363,7 +363,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -387,7 +387,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/StoreApi.ts index 836e9ba0261..3607b8dee6e 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/StoreApi.ts @@ -21,8 +21,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public async deleteOrder(orderId: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteOrder(orderId: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -35,7 +35,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -56,14 +56,14 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public async getInventory(options?: Configuration): Promise { - let config = options || this.configuration; + public async getInventory(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/store/inventory'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -77,7 +77,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -90,8 +90,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public async getOrderById(orderId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getOrderById(orderId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -104,7 +104,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -125,8 +125,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Place an order for a pet * @param order order placed for purchasing the pet */ - public async placeOrder(order: Order, options?: Configuration): Promise { - let config = options || this.configuration; + public async placeOrder(order: Order, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'order' is not null or undefined if (order === null || order === undefined) { @@ -138,7 +138,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/store/order'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/UserApi.ts index 5c68288c381..cc4580ef34c 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/UserApi.ts @@ -21,8 +21,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Create user * @param user Created user object */ - public async createUser(user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUser(user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -34,7 +34,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -57,7 +57,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -69,8 +69,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -82,7 +82,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithArray'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -105,7 +105,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -117,8 +117,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithListInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithListInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -130,7 +130,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithList'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -153,7 +153,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -166,8 +166,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Delete user * @param username The name that needs to be deleted */ - public async deleteUser(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteUser(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -180,7 +180,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -194,7 +194,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -206,8 +206,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public async getUserByName(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async getUserByName(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -220,7 +220,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -242,8 +242,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username The user name for login * @param password The password for login in clear text */ - public async loginUser(username: string, password: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async loginUser(username: string, password: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -261,7 +261,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/login'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -287,14 +287,14 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { /** * Logs out current logged in user session */ - public async logoutUser(options?: Configuration): Promise { - let config = options || this.configuration; + public async logoutUser(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/user/logout'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -308,7 +308,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -322,8 +322,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username name that need to be deleted * @param user Updated user object */ - public async updateUser(username: string, user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async updateUser(username: string, user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -342,7 +342,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -365,7 +365,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObservableAPI.ts index 555e2ce7273..6ed7a67b5cb 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObservableAPI.ts @@ -35,8 +35,8 @@ export class ObservablePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.addPet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -59,8 +59,8 @@ export class ObservablePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -83,8 +83,8 @@ export class ObservablePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByStatus(status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -107,8 +107,8 @@ export class ObservablePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByTags(tags, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -131,8 +131,8 @@ export class ObservablePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getPetById(petId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -154,8 +154,8 @@ export class ObservablePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -179,8 +179,8 @@ export class ObservablePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -204,8 +204,8 @@ export class ObservablePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -249,8 +249,8 @@ export class ObservableStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteOrder(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -272,8 +272,8 @@ export class ObservableStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Observable<{ [key: string]: number; }> { - const requestContextPromise = this.requestFactory.getInventory(options); + public getInventory(_options?: Configuration): Observable<{ [key: string]: number; }> { + const requestContextPromise = this.requestFactory.getInventory(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -296,8 +296,8 @@ export class ObservableStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getOrderById(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -319,8 +319,8 @@ export class ObservableStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.placeOrder(order, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -364,8 +364,8 @@ export class ObservableUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUser(user, options); + public createUser(user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUser(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -387,8 +387,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -410,8 +410,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithListInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -434,8 +434,8 @@ export class ObservableUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteUser(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -457,8 +457,8 @@ export class ObservableUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getUserByName(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -481,8 +481,8 @@ export class ObservableUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.loginUser(username, password, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -503,8 +503,8 @@ export class ObservableUserApi { /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.logoutUser(options); + public logoutUser(_options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.logoutUser(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -528,8 +528,8 @@ export class ObservableUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updateUser(username, user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/types/PromiseAPI.ts index f58fad865e1..a6135ddbd24 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/types/PromiseAPI.ts @@ -31,8 +31,8 @@ export class PromisePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Promise { - const result = this.api.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.addPet(pet, _options); return result.toPromise(); } @@ -41,8 +41,8 @@ export class PromisePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - const result = this.api.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + const result = this.api.deletePet(petId, apiKey, _options); return result.toPromise(); } @@ -51,8 +51,8 @@ export class PromisePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise> { - const result = this.api.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise> { + const result = this.api.findPetsByStatus(status, _options); return result.toPromise(); } @@ -61,8 +61,8 @@ export class PromisePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Promise> { - const result = this.api.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Promise> { + const result = this.api.findPetsByTags(tags, _options); return result.toPromise(); } @@ -71,8 +71,8 @@ export class PromisePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Promise { - const result = this.api.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Promise { + const result = this.api.getPetById(petId, _options); return result.toPromise(); } @@ -80,8 +80,8 @@ export class PromisePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Promise { - const result = this.api.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.updatePet(pet, _options); return result.toPromise(); } @@ -91,8 +91,8 @@ export class PromisePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - const result = this.api.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + const result = this.api.updatePetWithForm(petId, name, status, _options); return result.toPromise(); } @@ -102,8 +102,8 @@ export class PromisePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - const result = this.api.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + const result = this.api.uploadFile(petId, additionalMetadata, file, _options); return result.toPromise(); } @@ -134,8 +134,8 @@ export class PromiseStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Promise { - const result = this.api.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Promise { + const result = this.api.deleteOrder(orderId, _options); return result.toPromise(); } @@ -143,8 +143,8 @@ export class PromiseStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Promise<{ [key: string]: number; }> { - const result = this.api.getInventory(options); + public getInventory(_options?: Configuration): Promise<{ [key: string]: number; }> { + const result = this.api.getInventory(_options); return result.toPromise(); } @@ -153,8 +153,8 @@ export class PromiseStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Promise { - const result = this.api.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Promise { + const result = this.api.getOrderById(orderId, _options); return result.toPromise(); } @@ -162,8 +162,8 @@ export class PromiseStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Promise { - const result = this.api.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Promise { + const result = this.api.placeOrder(order, _options); return result.toPromise(); } @@ -194,8 +194,8 @@ export class PromiseUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Promise { - const result = this.api.createUser(user, options); + public createUser(user: User, _options?: Configuration): Promise { + const result = this.api.createUser(user, _options); return result.toPromise(); } @@ -203,8 +203,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithArrayInput(user, _options); return result.toPromise(); } @@ -212,8 +212,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithListInput(user, _options); return result.toPromise(); } @@ -222,8 +222,8 @@ export class PromiseUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Promise { - const result = this.api.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Promise { + const result = this.api.deleteUser(username, _options); return result.toPromise(); } @@ -231,8 +231,8 @@ export class PromiseUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Promise { - const result = this.api.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Promise { + const result = this.api.getUserByName(username, _options); return result.toPromise(); } @@ -241,16 +241,16 @@ export class PromiseUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Promise { - const result = this.api.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Promise { + const result = this.api.loginUser(username, password, _options); return result.toPromise(); } /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Promise { - const result = this.api.logoutUser(options); + public logoutUser(_options?: Configuration): Promise { + const result = this.api.logoutUser(_options); return result.toPromise(); } @@ -260,8 +260,8 @@ export class PromiseUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Promise { - const result = this.api.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Promise { + const result = this.api.updateUser(username, user, _options); return result.toPromise(); } diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts index 0e0db9ad8ee..8cf33634c31 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts @@ -18,8 +18,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public async addPet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async addPet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -31,7 +31,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -56,7 +56,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -69,8 +69,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param petId Pet id to delete * @param apiKey */ - public async deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -84,7 +84,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -99,7 +99,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -112,8 +112,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'status' is not null or undefined if (status === null || status === undefined) { @@ -125,7 +125,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByStatus'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -142,7 +142,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -155,8 +155,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by tags * @param tags Tags to filter by */ - public async findPetsByTags(tags: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByTags(tags: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'tags' is not null or undefined if (tags === null || tags === undefined) { @@ -168,7 +168,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByTags'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -185,7 +185,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -198,8 +198,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Find pet by ID * @param petId ID of pet to return */ - public async getPetById(petId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getPetById(petId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -212,7 +212,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -226,7 +226,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -238,8 +238,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public async updatePet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -251,7 +251,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -276,7 +276,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -290,8 +290,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param name Updated name of the pet * @param status Updated status of the pet */ - public async updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -306,7 +306,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -330,7 +330,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -344,8 +344,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - let config = options || this.configuration; + public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -360,7 +360,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -384,7 +384,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/StoreApi.ts index 9ada7b0fee1..5ca1dd79b3d 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/StoreApi.ts @@ -18,8 +18,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public async deleteOrder(orderId: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteOrder(orderId: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -32,7 +32,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -53,14 +53,14 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public async getInventory(options?: Configuration): Promise { - let config = options || this.configuration; + public async getInventory(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/store/inventory'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -74,7 +74,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -87,8 +87,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public async getOrderById(orderId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getOrderById(orderId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -101,7 +101,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -122,8 +122,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Place an order for a pet * @param order order placed for purchasing the pet */ - public async placeOrder(order: Order, options?: Configuration): Promise { - let config = options || this.configuration; + public async placeOrder(order: Order, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'order' is not null or undefined if (order === null || order === undefined) { @@ -135,7 +135,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/store/order'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/UserApi.ts index f705cc52a12..79bed0455ca 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/UserApi.ts @@ -18,8 +18,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Create user * @param user Created user object */ - public async createUser(user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUser(user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -31,7 +31,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -54,7 +54,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -66,8 +66,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -79,7 +79,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithArray'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -102,7 +102,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -114,8 +114,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithListInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithListInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -127,7 +127,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithList'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -150,7 +150,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -163,8 +163,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Delete user * @param username The name that needs to be deleted */ - public async deleteUser(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteUser(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -177,7 +177,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -191,7 +191,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -203,8 +203,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public async getUserByName(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async getUserByName(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -217,7 +217,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -239,8 +239,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username The user name for login * @param password The password for login in clear text */ - public async loginUser(username: string, password: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async loginUser(username: string, password: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -258,7 +258,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/login'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -284,14 +284,14 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { /** * Logs out current logged in user session */ - public async logoutUser(options?: Configuration): Promise { - let config = options || this.configuration; + public async logoutUser(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/user/logout'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -305,7 +305,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -319,8 +319,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username name that need to be deleted * @param user Updated user object */ - public async updateUser(username: string, user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async updateUser(username: string, user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -339,7 +339,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -362,7 +362,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObservableAPI.ts index 459fbc8e226..488915f871b 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObservableAPI.ts @@ -30,8 +30,8 @@ export class ObservablePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.addPet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -54,8 +54,8 @@ export class ObservablePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -78,8 +78,8 @@ export class ObservablePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByStatus(status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -102,8 +102,8 @@ export class ObservablePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByTags(tags, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -126,8 +126,8 @@ export class ObservablePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getPetById(petId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -149,8 +149,8 @@ export class ObservablePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -174,8 +174,8 @@ export class ObservablePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -199,8 +199,8 @@ export class ObservablePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -241,8 +241,8 @@ export class ObservableStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteOrder(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -264,8 +264,8 @@ export class ObservableStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Observable<{ [key: string]: number; }> { - const requestContextPromise = this.requestFactory.getInventory(options); + public getInventory(_options?: Configuration): Observable<{ [key: string]: number; }> { + const requestContextPromise = this.requestFactory.getInventory(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -288,8 +288,8 @@ export class ObservableStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getOrderById(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -311,8 +311,8 @@ export class ObservableStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.placeOrder(order, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -353,8 +353,8 @@ export class ObservableUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUser(user, options); + public createUser(user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUser(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -376,8 +376,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -399,8 +399,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithListInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -423,8 +423,8 @@ export class ObservableUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteUser(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -446,8 +446,8 @@ export class ObservableUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getUserByName(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -470,8 +470,8 @@ export class ObservableUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.loginUser(username, password, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -492,8 +492,8 @@ export class ObservableUserApi { /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.logoutUser(options); + public logoutUser(_options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.logoutUser(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -517,8 +517,8 @@ export class ObservableUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updateUser(username, user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/types/PromiseAPI.ts index 2129b103e7e..ac44ba7a13b 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/types/PromiseAPI.ts @@ -26,8 +26,8 @@ export class PromisePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Promise { - const result = this.api.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.addPet(pet, _options); return result.toPromise(); } @@ -36,8 +36,8 @@ export class PromisePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - const result = this.api.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + const result = this.api.deletePet(petId, apiKey, _options); return result.toPromise(); } @@ -46,8 +46,8 @@ export class PromisePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise> { - const result = this.api.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise> { + const result = this.api.findPetsByStatus(status, _options); return result.toPromise(); } @@ -56,8 +56,8 @@ export class PromisePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Promise> { - const result = this.api.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Promise> { + const result = this.api.findPetsByTags(tags, _options); return result.toPromise(); } @@ -66,8 +66,8 @@ export class PromisePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Promise { - const result = this.api.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Promise { + const result = this.api.getPetById(petId, _options); return result.toPromise(); } @@ -75,8 +75,8 @@ export class PromisePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Promise { - const result = this.api.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.updatePet(pet, _options); return result.toPromise(); } @@ -86,8 +86,8 @@ export class PromisePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - const result = this.api.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + const result = this.api.updatePetWithForm(petId, name, status, _options); return result.toPromise(); } @@ -97,8 +97,8 @@ export class PromisePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - const result = this.api.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + const result = this.api.uploadFile(petId, additionalMetadata, file, _options); return result.toPromise(); } @@ -126,8 +126,8 @@ export class PromiseStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Promise { - const result = this.api.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Promise { + const result = this.api.deleteOrder(orderId, _options); return result.toPromise(); } @@ -135,8 +135,8 @@ export class PromiseStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Promise<{ [key: string]: number; }> { - const result = this.api.getInventory(options); + public getInventory(_options?: Configuration): Promise<{ [key: string]: number; }> { + const result = this.api.getInventory(_options); return result.toPromise(); } @@ -145,8 +145,8 @@ export class PromiseStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Promise { - const result = this.api.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Promise { + const result = this.api.getOrderById(orderId, _options); return result.toPromise(); } @@ -154,8 +154,8 @@ export class PromiseStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Promise { - const result = this.api.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Promise { + const result = this.api.placeOrder(order, _options); return result.toPromise(); } @@ -183,8 +183,8 @@ export class PromiseUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Promise { - const result = this.api.createUser(user, options); + public createUser(user: User, _options?: Configuration): Promise { + const result = this.api.createUser(user, _options); return result.toPromise(); } @@ -192,8 +192,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithArrayInput(user, _options); return result.toPromise(); } @@ -201,8 +201,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithListInput(user, _options); return result.toPromise(); } @@ -211,8 +211,8 @@ export class PromiseUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Promise { - const result = this.api.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Promise { + const result = this.api.deleteUser(username, _options); return result.toPromise(); } @@ -220,8 +220,8 @@ export class PromiseUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Promise { - const result = this.api.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Promise { + const result = this.api.getUserByName(username, _options); return result.toPromise(); } @@ -230,16 +230,16 @@ export class PromiseUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Promise { - const result = this.api.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Promise { + const result = this.api.loginUser(username, password, _options); return result.toPromise(); } /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Promise { - const result = this.api.logoutUser(options); + public logoutUser(_options?: Configuration): Promise { + const result = this.api.logoutUser(_options); return result.toPromise(); } @@ -249,8 +249,8 @@ export class PromiseUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Promise { - const result = this.api.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Promise { + const result = this.api.updateUser(username, user, _options); return result.toPromise(); } diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/PetApi.ts index 12d711bd5b7..547125db459 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/PetApi.ts @@ -19,8 +19,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public async addPet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async addPet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -32,7 +32,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -57,7 +57,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -70,8 +70,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param petId Pet id to delete * @param apiKey */ - public async deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -85,7 +85,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -100,7 +100,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -113,8 +113,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'status' is not null or undefined if (status === null || status === undefined) { @@ -126,7 +126,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByStatus'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -143,7 +143,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -156,8 +156,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by tags * @param tags Tags to filter by */ - public async findPetsByTags(tags: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByTags(tags: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'tags' is not null or undefined if (tags === null || tags === undefined) { @@ -169,7 +169,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByTags'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -186,7 +186,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -199,8 +199,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Find pet by ID * @param petId ID of pet to return */ - public async getPetById(petId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getPetById(petId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -213,7 +213,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -227,7 +227,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -239,8 +239,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public async updatePet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -252,7 +252,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -277,7 +277,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -291,8 +291,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param name Updated name of the pet * @param status Updated status of the pet */ - public async updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -307,7 +307,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -331,7 +331,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -345,8 +345,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - let config = options || this.configuration; + public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -361,7 +361,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -385,7 +385,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/StoreApi.ts index 12be0132697..7780dd52f48 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/StoreApi.ts @@ -19,8 +19,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public async deleteOrder(orderId: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteOrder(orderId: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -33,7 +33,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -54,14 +54,14 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public async getInventory(options?: Configuration): Promise { - let config = options || this.configuration; + public async getInventory(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/store/inventory'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -75,7 +75,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -88,8 +88,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public async getOrderById(orderId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getOrderById(orderId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -102,7 +102,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -123,8 +123,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Place an order for a pet * @param order order placed for purchasing the pet */ - public async placeOrder(order: Order, options?: Configuration): Promise { - let config = options || this.configuration; + public async placeOrder(order: Order, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'order' is not null or undefined if (order === null || order === undefined) { @@ -136,7 +136,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/store/order'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/UserApi.ts index 0717cb75304..e12b26fd31d 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/UserApi.ts @@ -19,8 +19,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Create user * @param user Created user object */ - public async createUser(user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUser(user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -32,7 +32,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -55,7 +55,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -67,8 +67,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -80,7 +80,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithArray'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -103,7 +103,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -115,8 +115,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithListInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithListInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -128,7 +128,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithList'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -151,7 +151,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -164,8 +164,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Delete user * @param username The name that needs to be deleted */ - public async deleteUser(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteUser(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -178,7 +178,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -192,7 +192,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -204,8 +204,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public async getUserByName(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async getUserByName(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -218,7 +218,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -240,8 +240,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username The user name for login * @param password The password for login in clear text */ - public async loginUser(username: string, password: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async loginUser(username: string, password: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -259,7 +259,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/login'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -285,14 +285,14 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { /** * Logs out current logged in user session */ - public async logoutUser(options?: Configuration): Promise { - let config = options || this.configuration; + public async logoutUser(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/user/logout'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -306,7 +306,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -320,8 +320,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username name that need to be deleted * @param user Updated user object */ - public async updateUser(username: string, user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async updateUser(username: string, user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -340,7 +340,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -363,7 +363,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObservableAPI.ts index 459fbc8e226..488915f871b 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObservableAPI.ts @@ -30,8 +30,8 @@ export class ObservablePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.addPet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -54,8 +54,8 @@ export class ObservablePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -78,8 +78,8 @@ export class ObservablePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByStatus(status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -102,8 +102,8 @@ export class ObservablePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByTags(tags, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -126,8 +126,8 @@ export class ObservablePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getPetById(petId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -149,8 +149,8 @@ export class ObservablePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -174,8 +174,8 @@ export class ObservablePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -199,8 +199,8 @@ export class ObservablePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -241,8 +241,8 @@ export class ObservableStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteOrder(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -264,8 +264,8 @@ export class ObservableStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Observable<{ [key: string]: number; }> { - const requestContextPromise = this.requestFactory.getInventory(options); + public getInventory(_options?: Configuration): Observable<{ [key: string]: number; }> { + const requestContextPromise = this.requestFactory.getInventory(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -288,8 +288,8 @@ export class ObservableStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getOrderById(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -311,8 +311,8 @@ export class ObservableStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.placeOrder(order, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -353,8 +353,8 @@ export class ObservableUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUser(user, options); + public createUser(user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUser(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -376,8 +376,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -399,8 +399,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithListInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -423,8 +423,8 @@ export class ObservableUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteUser(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -446,8 +446,8 @@ export class ObservableUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getUserByName(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -470,8 +470,8 @@ export class ObservableUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.loginUser(username, password, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -492,8 +492,8 @@ export class ObservableUserApi { /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.logoutUser(options); + public logoutUser(_options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.logoutUser(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -517,8 +517,8 @@ export class ObservableUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updateUser(username, user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/types/PromiseAPI.ts index 2129b103e7e..ac44ba7a13b 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/types/PromiseAPI.ts @@ -26,8 +26,8 @@ export class PromisePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Promise { - const result = this.api.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.addPet(pet, _options); return result.toPromise(); } @@ -36,8 +36,8 @@ export class PromisePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - const result = this.api.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + const result = this.api.deletePet(petId, apiKey, _options); return result.toPromise(); } @@ -46,8 +46,8 @@ export class PromisePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise> { - const result = this.api.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise> { + const result = this.api.findPetsByStatus(status, _options); return result.toPromise(); } @@ -56,8 +56,8 @@ export class PromisePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Promise> { - const result = this.api.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Promise> { + const result = this.api.findPetsByTags(tags, _options); return result.toPromise(); } @@ -66,8 +66,8 @@ export class PromisePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Promise { - const result = this.api.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Promise { + const result = this.api.getPetById(petId, _options); return result.toPromise(); } @@ -75,8 +75,8 @@ export class PromisePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Promise { - const result = this.api.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.updatePet(pet, _options); return result.toPromise(); } @@ -86,8 +86,8 @@ export class PromisePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - const result = this.api.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + const result = this.api.updatePetWithForm(petId, name, status, _options); return result.toPromise(); } @@ -97,8 +97,8 @@ export class PromisePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - const result = this.api.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + const result = this.api.uploadFile(petId, additionalMetadata, file, _options); return result.toPromise(); } @@ -126,8 +126,8 @@ export class PromiseStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Promise { - const result = this.api.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Promise { + const result = this.api.deleteOrder(orderId, _options); return result.toPromise(); } @@ -135,8 +135,8 @@ export class PromiseStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Promise<{ [key: string]: number; }> { - const result = this.api.getInventory(options); + public getInventory(_options?: Configuration): Promise<{ [key: string]: number; }> { + const result = this.api.getInventory(_options); return result.toPromise(); } @@ -145,8 +145,8 @@ export class PromiseStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Promise { - const result = this.api.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Promise { + const result = this.api.getOrderById(orderId, _options); return result.toPromise(); } @@ -154,8 +154,8 @@ export class PromiseStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Promise { - const result = this.api.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Promise { + const result = this.api.placeOrder(order, _options); return result.toPromise(); } @@ -183,8 +183,8 @@ export class PromiseUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Promise { - const result = this.api.createUser(user, options); + public createUser(user: User, _options?: Configuration): Promise { + const result = this.api.createUser(user, _options); return result.toPromise(); } @@ -192,8 +192,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithArrayInput(user, _options); return result.toPromise(); } @@ -201,8 +201,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithListInput(user, _options); return result.toPromise(); } @@ -211,8 +211,8 @@ export class PromiseUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Promise { - const result = this.api.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Promise { + const result = this.api.deleteUser(username, _options); return result.toPromise(); } @@ -220,8 +220,8 @@ export class PromiseUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Promise { - const result = this.api.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Promise { + const result = this.api.getUserByName(username, _options); return result.toPromise(); } @@ -230,16 +230,16 @@ export class PromiseUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Promise { - const result = this.api.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Promise { + const result = this.api.loginUser(username, password, _options); return result.toPromise(); } /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Promise { - const result = this.api.logoutUser(options); + public logoutUser(_options?: Configuration): Promise { + const result = this.api.logoutUser(_options); return result.toPromise(); } @@ -249,8 +249,8 @@ export class PromiseUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Promise { - const result = this.api.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Promise { + const result = this.api.updateUser(username, user, _options); return result.toPromise(); } diff --git a/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION b/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION index c30f0ec2be7..6555596f931 100644 --- a/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION +++ b/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.0-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/cpp-pistache/api/PetApi.cpp b/samples/server/petstore/cpp-pistache/api/PetApi.cpp index 80e15bd6862..7b3641599ee 100644 --- a/samples/server/petstore/cpp-pistache/api/PetApi.cpp +++ b/samples/server/petstore/cpp-pistache/api/PetApi.cpp @@ -13,16 +13,17 @@ #include "PetApi.h" #include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace api { +namespace org::openapitools::server::api +{ using namespace org::openapitools::server::helpers; using namespace org::openapitools::server::model; -PetApi::PetApi(std::shared_ptr rtr) { - router = rtr; +const std::string PetApi::base = "/v2"; + +PetApi::PetApi(const std::shared_ptr& rtr) + : router(rtr) +{ } void PetApi::init() { @@ -45,30 +46,58 @@ void PetApi::setupRoutes() { router->addCustomHandler(Routes::bind(&PetApi::pet_api_default_handler, this)); } +std::pair PetApi::handleParsingException(const std::exception& ex) const noexcept +{ + try { + throw ex; + } catch (nlohmann::detail::exception &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch (org::openapitools::server::helpers::ValidationException &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } +} + +std::pair PetApi::handleOperationException(const std::exception& ex) const noexcept +{ + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, ex.what()); +} + void PetApi::add_pet_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the body param Pet body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->add_pet(body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->add_pet(body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::delete_pet_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto petId = request.param(":petId").as(); @@ -76,22 +105,24 @@ void PetApi::delete_pet_handler(const Pistache::Rest::Request &request, Pistache auto apiKey = request.headers().tryGetRaw("api_key"); try { - this->delete_pet(petId, apiKey, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->delete_pet(petId, apiKey, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::find_pets_by_status_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the query params auto statusQuery = request.query().get("status"); @@ -104,22 +135,24 @@ void PetApi::find_pets_by_status_handler(const Pistache::Rest::Request &request, } try { - this->find_pets_by_status(status, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->find_pets_by_status(status, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::find_pets_by_tags_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the query params auto tagsQuery = request.query().get("tags"); @@ -132,105 +165,118 @@ void PetApi::find_pets_by_tags_handler(const Pistache::Rest::Request &request, P } try { - this->find_pets_by_tags(tags, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->find_pets_by_tags(tags, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::get_pet_by_id_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto petId = request.param(":petId").as(); try { - this->get_pet_by_id(petId, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->get_pet_by_id(petId, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::update_pet_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the body param Pet body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->update_pet(body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->update_pet(body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::update_pet_with_form_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + try { this->update_pet_with_form(request, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::upload_file_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + try { this->upload_file(request, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::pet_api_default_handler(const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) { response.send(Pistache::Http::Code::Not_Found, "The requested method does not exist"); } -} -} -} -} +} // namespace org::openapitools::server::api diff --git a/samples/server/petstore/cpp-pistache/api/PetApi.h b/samples/server/petstore/cpp-pistache/api/PetApi.h index d991d13abae..f689a0675e1 100644 --- a/samples/server/petstore/cpp-pistache/api/PetApi.h +++ b/samples/server/petstore/cpp-pistache/api/PetApi.h @@ -24,25 +24,22 @@ #include #include +#include #include "ApiResponse.h" #include "Pet.h" #include -namespace org { -namespace openapitools { -namespace server { -namespace api { - -using namespace org::openapitools::server::model; +namespace org::openapitools::server::api +{ class PetApi { public: - PetApi(std::shared_ptr); - virtual ~PetApi() {} + explicit PetApi(const std::shared_ptr& rtr); + virtual ~PetApi() = default; void init(); - const std::string base = "/v2"; + static const std::string base; private: void setupRoutes(); @@ -57,7 +54,19 @@ private: void upload_file_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); void pet_api_default_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); - std::shared_ptr router; + const std::shared_ptr router; + + /// + /// Helper function to handle unexpected Exceptions during Parameter parsing and validation. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleParsingException(const std::exception& ex) const noexcept; + + /// + /// Helper function to handle unexpected Exceptions during processing of the request in handler functions. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleOperationException(const std::exception& ex) const noexcept; /// /// Add a new pet to the store @@ -66,8 +75,7 @@ private: /// /// /// Pet object that needs to be added to the store - virtual void add_pet(const Pet &body, Pistache::Http::ResponseWriter &response) = 0; - + virtual void add_pet(const org::openapitools::server::model::Pet &body, Pistache::Http::ResponseWriter &response) = 0; /// /// Deletes a pet /// @@ -77,7 +85,6 @@ private: /// Pet id to delete /// (optional, default to "") virtual void delete_pet(const int64_t &petId, const Pistache::Optional &apiKey, Pistache::Http::ResponseWriter &response) = 0; - /// /// Finds Pets by status /// @@ -86,7 +93,6 @@ private: /// /// Status values that need to be considered for filter virtual void find_pets_by_status(const Pistache::Optional> &status, Pistache::Http::ResponseWriter &response) = 0; - /// /// Finds Pets by tags /// @@ -95,7 +101,6 @@ private: /// /// Tags to filter by virtual void find_pets_by_tags(const Pistache::Optional> &tags, Pistache::Http::ResponseWriter &response) = 0; - /// /// Find pet by ID /// @@ -104,7 +109,6 @@ private: /// /// ID of pet to return virtual void get_pet_by_id(const int64_t &petId, Pistache::Http::ResponseWriter &response) = 0; - /// /// Update an existing pet /// @@ -112,8 +116,7 @@ private: /// /// /// Pet object that needs to be added to the store - virtual void update_pet(const Pet &body, Pistache::Http::ResponseWriter &response) = 0; - + virtual void update_pet(const org::openapitools::server::model::Pet &body, Pistache::Http::ResponseWriter &response) = 0; /// /// Updates a pet in the store with form data /// @@ -121,7 +124,6 @@ private: /// /// virtual void update_pet_with_form(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter &response) = 0; - /// /// uploads an image /// @@ -132,10 +134,7 @@ private: }; -} -} -} -} +} // namespace org::openapitools::server::api #endif /* PetApi_H_ */ diff --git a/samples/server/petstore/cpp-pistache/api/StoreApi.cpp b/samples/server/petstore/cpp-pistache/api/StoreApi.cpp index e3f1038f80a..ea0c0e1793b 100644 --- a/samples/server/petstore/cpp-pistache/api/StoreApi.cpp +++ b/samples/server/petstore/cpp-pistache/api/StoreApi.cpp @@ -13,16 +13,17 @@ #include "StoreApi.h" #include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace api { +namespace org::openapitools::server::api +{ using namespace org::openapitools::server::helpers; using namespace org::openapitools::server::model; -StoreApi::StoreApi(std::shared_ptr rtr) { - router = rtr; +const std::string StoreApi::base = "/v2"; + +StoreApi::StoreApi(const std::shared_ptr& rtr) + : router(rtr) +{ } void StoreApi::init() { @@ -41,94 +42,123 @@ void StoreApi::setupRoutes() { router->addCustomHandler(Routes::bind(&StoreApi::store_api_default_handler, this)); } +std::pair StoreApi::handleParsingException(const std::exception& ex) const noexcept +{ + try { + throw ex; + } catch (nlohmann::detail::exception &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch (org::openapitools::server::helpers::ValidationException &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } +} + +std::pair StoreApi::handleOperationException(const std::exception& ex) const noexcept +{ + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, ex.what()); +} + void StoreApi::delete_order_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto orderId = request.param(":orderId").as(); try { - this->delete_order(orderId, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->delete_order(orderId, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void StoreApi::get_inventory_handler(const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) { + try { + try { - this->get_inventory(response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->get_inventory(response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void StoreApi::get_order_by_id_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto orderId = request.param(":orderId").as(); try { - this->get_order_by_id(orderId, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->get_order_by_id(orderId, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void StoreApi::place_order_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the body param Order body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->place_order(body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->place_order(body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void StoreApi::store_api_default_handler(const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) { response.send(Pistache::Http::Code::Not_Found, "The requested method does not exist"); } -} -} -} -} +} // namespace org::openapitools::server::api diff --git a/samples/server/petstore/cpp-pistache/api/StoreApi.h b/samples/server/petstore/cpp-pistache/api/StoreApi.h index f69875c4678..6eb22438747 100644 --- a/samples/server/petstore/cpp-pistache/api/StoreApi.h +++ b/samples/server/petstore/cpp-pistache/api/StoreApi.h @@ -24,25 +24,22 @@ #include #include +#include #include "Order.h" #include #include -namespace org { -namespace openapitools { -namespace server { -namespace api { - -using namespace org::openapitools::server::model; +namespace org::openapitools::server::api +{ class StoreApi { public: - StoreApi(std::shared_ptr); - virtual ~StoreApi() {} + explicit StoreApi(const std::shared_ptr& rtr); + virtual ~StoreApi() = default; void init(); - const std::string base = "/v2"; + static const std::string base; private: void setupRoutes(); @@ -53,7 +50,19 @@ private: void place_order_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); void store_api_default_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); - std::shared_ptr router; + const std::shared_ptr router; + + /// + /// Helper function to handle unexpected Exceptions during Parameter parsing and validation. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleParsingException(const std::exception& ex) const noexcept; + + /// + /// Helper function to handle unexpected Exceptions during processing of the request in handler functions. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleOperationException(const std::exception& ex) const noexcept; /// /// Delete purchase order by ID @@ -63,7 +72,6 @@ private: /// /// ID of the order that needs to be deleted virtual void delete_order(const std::string &orderId, Pistache::Http::ResponseWriter &response) = 0; - /// /// Returns pet inventories by status /// @@ -71,7 +79,6 @@ private: /// Returns a map of status codes to quantities /// virtual void get_inventory(Pistache::Http::ResponseWriter &response) = 0; - /// /// Find purchase order by ID /// @@ -80,7 +87,6 @@ private: /// /// ID of pet that needs to be fetched virtual void get_order_by_id(const int64_t &orderId, Pistache::Http::ResponseWriter &response) = 0; - /// /// Place an order for a pet /// @@ -88,14 +94,11 @@ private: /// /// /// order placed for purchasing the pet - virtual void place_order(const Order &body, Pistache::Http::ResponseWriter &response) = 0; + virtual void place_order(const org::openapitools::server::model::Order &body, Pistache::Http::ResponseWriter &response) = 0; }; -} -} -} -} +} // namespace org::openapitools::server::api #endif /* StoreApi_H_ */ diff --git a/samples/server/petstore/cpp-pistache/api/UserApi.cpp b/samples/server/petstore/cpp-pistache/api/UserApi.cpp index 93d275611d7..94903581dc4 100644 --- a/samples/server/petstore/cpp-pistache/api/UserApi.cpp +++ b/samples/server/petstore/cpp-pistache/api/UserApi.cpp @@ -13,16 +13,17 @@ #include "UserApi.h" #include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace api { +namespace org::openapitools::server::api +{ using namespace org::openapitools::server::helpers; using namespace org::openapitools::server::model; -UserApi::UserApi(std::shared_ptr rtr) { - router = rtr; +const std::string UserApi::base = "/v2"; + +UserApi::UserApi(const std::shared_ptr& rtr) + : router(rtr) +{ } void UserApi::init() { @@ -45,114 +46,166 @@ void UserApi::setupRoutes() { router->addCustomHandler(Routes::bind(&UserApi::user_api_default_handler, this)); } +std::pair UserApi::handleParsingException(const std::exception& ex) const noexcept +{ + try { + throw ex; + } catch (nlohmann::detail::exception &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch (org::openapitools::server::helpers::ValidationException &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } +} + +std::pair UserApi::handleOperationException(const std::exception& ex) const noexcept +{ + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, ex.what()); +} + void UserApi::create_user_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the body param User body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->create_user(body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->create_user(body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::create_users_with_array_input_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the body param std::vector body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->create_users_with_array_input(body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->create_users_with_array_input(body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::create_users_with_list_input_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the body param std::vector body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->create_users_with_list_input(body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->create_users_with_list_input(body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::delete_user_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto username = request.param(":username").as(); try { - this->delete_user(username, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->delete_user(username, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::get_user_by_name_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto username = request.param(":username").as(); try { - this->get_user_by_name(username, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->get_user_by_name(username, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::login_user_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the query params auto usernameQuery = request.query().get("username"); @@ -173,40 +226,44 @@ void UserApi::login_user_handler(const Pistache::Rest::Request &request, Pistach } try { - this->login_user(username, password, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->login_user(username, password, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::logout_user_handler(const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) { + try { + try { - this->logout_user(response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->logout_user(response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::update_user_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto username = request.param(":username").as(); @@ -215,29 +272,34 @@ void UserApi::update_user_handler(const Pistache::Rest::Request &request, Pistac User body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->update_user(username, body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->update_user(username, body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::user_api_default_handler(const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) { response.send(Pistache::Http::Code::Not_Found, "The requested method does not exist"); } -} -} -} -} +} // namespace org::openapitools::server::api diff --git a/samples/server/petstore/cpp-pistache/api/UserApi.h b/samples/server/petstore/cpp-pistache/api/UserApi.h index 6c589979dbc..003b6db4df4 100644 --- a/samples/server/petstore/cpp-pistache/api/UserApi.h +++ b/samples/server/petstore/cpp-pistache/api/UserApi.h @@ -24,25 +24,22 @@ #include #include +#include #include "User.h" #include #include -namespace org { -namespace openapitools { -namespace server { -namespace api { - -using namespace org::openapitools::server::model; +namespace org::openapitools::server::api +{ class UserApi { public: - UserApi(std::shared_ptr); - virtual ~UserApi() {} + explicit UserApi(const std::shared_ptr& rtr); + virtual ~UserApi() = default; void init(); - const std::string base = "/v2"; + static const std::string base; private: void setupRoutes(); @@ -57,7 +54,19 @@ private: void update_user_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); void user_api_default_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); - std::shared_ptr router; + const std::shared_ptr router; + + /// + /// Helper function to handle unexpected Exceptions during Parameter parsing and validation. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleParsingException(const std::exception& ex) const noexcept; + + /// + /// Helper function to handle unexpected Exceptions during processing of the request in handler functions. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleOperationException(const std::exception& ex) const noexcept; /// /// Create user @@ -66,8 +75,7 @@ private: /// This can only be done by the logged in user. /// /// Created user object - virtual void create_user(const User &body, Pistache::Http::ResponseWriter &response) = 0; - + virtual void create_user(const org::openapitools::server::model::User &body, Pistache::Http::ResponseWriter &response) = 0; /// /// Creates list of users with given input array /// @@ -76,7 +84,6 @@ private: /// /// List of user object virtual void create_users_with_array_input(const std::vector &body, Pistache::Http::ResponseWriter &response) = 0; - /// /// Creates list of users with given input array /// @@ -85,7 +92,6 @@ private: /// /// List of user object virtual void create_users_with_list_input(const std::vector &body, Pistache::Http::ResponseWriter &response) = 0; - /// /// Delete user /// @@ -94,7 +100,6 @@ private: /// /// The name that needs to be deleted virtual void delete_user(const std::string &username, Pistache::Http::ResponseWriter &response) = 0; - /// /// Get user by user name /// @@ -103,7 +108,6 @@ private: /// /// The name that needs to be fetched. Use user1 for testing. virtual void get_user_by_name(const std::string &username, Pistache::Http::ResponseWriter &response) = 0; - /// /// Logs user into the system /// @@ -113,7 +117,6 @@ private: /// The user name for login /// The password for login in clear text virtual void login_user(const Pistache::Optional &username, const Pistache::Optional &password, Pistache::Http::ResponseWriter &response) = 0; - /// /// Logs out current logged in user session /// @@ -121,7 +124,6 @@ private: /// /// virtual void logout_user(Pistache::Http::ResponseWriter &response) = 0; - /// /// Updated user /// @@ -130,14 +132,11 @@ private: /// /// name that need to be deleted /// Updated user object - virtual void update_user(const std::string &username, const User &body, Pistache::Http::ResponseWriter &response) = 0; + virtual void update_user(const std::string &username, const org::openapitools::server::model::User &body, Pistache::Http::ResponseWriter &response) = 0; }; -} -} -} -} +} // namespace org::openapitools::server::api #endif /* UserApi_H_ */ diff --git a/samples/server/petstore/cpp-pistache/impl/PetApiImpl.cpp b/samples/server/petstore/cpp-pistache/impl/PetApiImpl.cpp index 778117a18bb..94b49b151e4 100644 --- a/samples/server/petstore/cpp-pistache/impl/PetApiImpl.cpp +++ b/samples/server/petstore/cpp-pistache/impl/PetApiImpl.cpp @@ -19,9 +19,10 @@ namespace api { using namespace org::openapitools::server::model; -PetApiImpl::PetApiImpl(std::shared_ptr rtr) +PetApiImpl::PetApiImpl(const std::shared_ptr& rtr) : PetApi(rtr) - { } +{ +} void PetApiImpl::add_pet(const Pet &body, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); diff --git a/samples/server/petstore/cpp-pistache/impl/PetApiImpl.h b/samples/server/petstore/cpp-pistache/impl/PetApiImpl.h index 9e9f3d145ba..82c10b0a410 100644 --- a/samples/server/petstore/cpp-pistache/impl/PetApiImpl.h +++ b/samples/server/petstore/cpp-pistache/impl/PetApiImpl.h @@ -33,17 +33,15 @@ #include "Pet.h" #include -namespace org { -namespace openapitools { -namespace server { -namespace api { +namespace org::openapitools::server::api +{ using namespace org::openapitools::server::model; class PetApiImpl : public org::openapitools::server::api::PetApi { public: - PetApiImpl(std::shared_ptr); - ~PetApiImpl() {} + explicit PetApiImpl(const std::shared_ptr& rtr); + ~PetApiImpl() override = default; void add_pet(const Pet &body, Pistache::Http::ResponseWriter &response); void delete_pet(const int64_t &petId, const Pistache::Optional &apiKey, Pistache::Http::ResponseWriter &response); @@ -56,11 +54,8 @@ public: }; -} -} -} -} +} // namespace org::openapitools::server::api -#endif \ No newline at end of file +#endif diff --git a/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.cpp b/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.cpp index ef164eb0543..a746316b803 100644 --- a/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.cpp +++ b/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.cpp @@ -19,9 +19,10 @@ namespace api { using namespace org::openapitools::server::model; -StoreApiImpl::StoreApiImpl(std::shared_ptr rtr) +StoreApiImpl::StoreApiImpl(const std::shared_ptr& rtr) : StoreApi(rtr) - { } +{ +} void StoreApiImpl::delete_order(const std::string &orderId, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); diff --git a/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.h b/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.h index c9937246318..c5dda64490f 100644 --- a/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.h +++ b/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.h @@ -33,17 +33,15 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace api { +namespace org::openapitools::server::api +{ using namespace org::openapitools::server::model; class StoreApiImpl : public org::openapitools::server::api::StoreApi { public: - StoreApiImpl(std::shared_ptr); - ~StoreApiImpl() {} + explicit StoreApiImpl(const std::shared_ptr& rtr); + ~StoreApiImpl() override = default; void delete_order(const std::string &orderId, Pistache::Http::ResponseWriter &response); void get_inventory(Pistache::Http::ResponseWriter &response); @@ -52,11 +50,8 @@ public: }; -} -} -} -} +} // namespace org::openapitools::server::api -#endif \ No newline at end of file +#endif diff --git a/samples/server/petstore/cpp-pistache/impl/UserApiImpl.cpp b/samples/server/petstore/cpp-pistache/impl/UserApiImpl.cpp index 7163a560bd7..b477f053c5c 100644 --- a/samples/server/petstore/cpp-pistache/impl/UserApiImpl.cpp +++ b/samples/server/petstore/cpp-pistache/impl/UserApiImpl.cpp @@ -19,9 +19,10 @@ namespace api { using namespace org::openapitools::server::model; -UserApiImpl::UserApiImpl(std::shared_ptr rtr) +UserApiImpl::UserApiImpl(const std::shared_ptr& rtr) : UserApi(rtr) - { } +{ +} void UserApiImpl::create_user(const User &body, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); diff --git a/samples/server/petstore/cpp-pistache/impl/UserApiImpl.h b/samples/server/petstore/cpp-pistache/impl/UserApiImpl.h index 8f22c499889..856a30db5bb 100644 --- a/samples/server/petstore/cpp-pistache/impl/UserApiImpl.h +++ b/samples/server/petstore/cpp-pistache/impl/UserApiImpl.h @@ -33,17 +33,15 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace api { +namespace org::openapitools::server::api +{ using namespace org::openapitools::server::model; class UserApiImpl : public org::openapitools::server::api::UserApi { public: - UserApiImpl(std::shared_ptr); - ~UserApiImpl() {} + explicit UserApiImpl(const std::shared_ptr& rtr); + ~UserApiImpl() override = default; void create_user(const User &body, Pistache::Http::ResponseWriter &response); void create_users_with_array_input(const std::vector &body, Pistache::Http::ResponseWriter &response); @@ -56,11 +54,8 @@ public: }; -} -} -} -} +} // namespace org::openapitools::server::api -#endif \ No newline at end of file +#endif diff --git a/samples/server/petstore/cpp-pistache/model/ApiResponse.cpp b/samples/server/petstore/cpp-pistache/model/ApiResponse.cpp index 4b9ca741920..049f6c19d6d 100644 --- a/samples/server/petstore/cpp-pistache/model/ApiResponse.cpp +++ b/samples/server/petstore/cpp-pistache/model/ApiResponse.cpp @@ -12,11 +12,12 @@ #include "ApiResponse.h" +#include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace model { +#include + +namespace org::openapitools::server::model +{ ApiResponse::ApiResponse() { @@ -29,13 +30,52 @@ ApiResponse::ApiResponse() } -ApiResponse::~ApiResponse() +void ApiResponse::validate() const { + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } } -void ApiResponse::validate() +bool ApiResponse::validate(std::stringstream& msg) const { - // TODO: implement validation + return validate(msg, ""); +} + +bool ApiResponse::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "ApiResponse" : pathPrefix; + + + + + + return success; +} + +bool ApiResponse::operator==(const ApiResponse& rhs) const +{ + return + + + + ((!codeIsSet() && !rhs.codeIsSet()) || (codeIsSet() && rhs.codeIsSet() && getCode() == rhs.getCode())) && + + + ((!typeIsSet() && !rhs.typeIsSet()) || (typeIsSet() && rhs.typeIsSet() && getType() == rhs.getType())) && + + + ((!messageIsSet() && !rhs.messageIsSet()) || (messageIsSet() && rhs.messageIsSet() && getMessage() == rhs.getMessage())) + + ; +} + +bool ApiResponse::operator!=(const ApiResponse& rhs) const +{ + return !(*this == rhs); } void to_json(nlohmann::json& j, const ApiResponse& o) @@ -123,8 +163,5 @@ void ApiResponse::unsetMessage() } -} -} -} -} +} // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/ApiResponse.h b/samples/server/petstore/cpp-pistache/model/ApiResponse.h index 7ecb6c9a82e..d963b76650b 100644 --- a/samples/server/petstore/cpp-pistache/model/ApiResponse.h +++ b/samples/server/petstore/cpp-pistache/model/ApiResponse.h @@ -22,10 +22,8 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace model { +namespace org::openapitools::server::model +{ /// /// Describes the result of uploading an image resource @@ -34,9 +32,22 @@ class ApiResponse { public: ApiResponse(); - virtual ~ApiResponse(); + virtual ~ApiResponse() = default; - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const ApiResponse& rhs) const; + bool operator!=(const ApiResponse& rhs) const; ///////////////////////////////////////////// /// ApiResponse members @@ -72,11 +83,11 @@ protected: bool m_TypeIsSet; std::string m_Message; bool m_MessageIsSet; + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -} -} -} -} +} // namespace org::openapitools::server::model #endif /* ApiResponse_H_ */ diff --git a/samples/server/petstore/cpp-pistache/model/Category.cpp b/samples/server/petstore/cpp-pistache/model/Category.cpp index 3b08114f61d..deb18ff9bb7 100644 --- a/samples/server/petstore/cpp-pistache/model/Category.cpp +++ b/samples/server/petstore/cpp-pistache/model/Category.cpp @@ -12,11 +12,12 @@ #include "Category.h" +#include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace model { +#include + +namespace org::openapitools::server::model +{ Category::Category() { @@ -27,13 +28,48 @@ Category::Category() } -Category::~Category() +void Category::validate() const { + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } } -void Category::validate() +bool Category::validate(std::stringstream& msg) const { - // TODO: implement validation + return validate(msg, ""); +} + +bool Category::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "Category" : pathPrefix; + + + + + return success; +} + +bool Category::operator==(const Category& rhs) const +{ + return + + + + ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && + + + ((!nameIsSet() && !rhs.nameIsSet()) || (nameIsSet() && rhs.nameIsSet() && getName() == rhs.getName())) + + ; +} + +bool Category::operator!=(const Category& rhs) const +{ + return !(*this == rhs); } void to_json(nlohmann::json& j, const Category& o) @@ -97,8 +133,5 @@ void Category::unsetName() } -} -} -} -} +} // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/Category.h b/samples/server/petstore/cpp-pistache/model/Category.h index fa12fdc0de8..1929ce33e92 100644 --- a/samples/server/petstore/cpp-pistache/model/Category.h +++ b/samples/server/petstore/cpp-pistache/model/Category.h @@ -22,10 +22,8 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace model { +namespace org::openapitools::server::model +{ /// /// A category for a pet @@ -34,9 +32,22 @@ class Category { public: Category(); - virtual ~Category(); + virtual ~Category() = default; - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const Category& rhs) const; + bool operator!=(const Category& rhs) const; ///////////////////////////////////////////// /// Category members @@ -63,11 +74,11 @@ protected: bool m_IdIsSet; std::string m_Name; bool m_NameIsSet; + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -} -} -} -} +} // namespace org::openapitools::server::model #endif /* Category_H_ */ diff --git a/samples/server/petstore/cpp-pistache/model/Helpers.cpp b/samples/server/petstore/cpp-pistache/model/Helpers.cpp index a7774194c82..cfac2d78986 100644 --- a/samples/server/petstore/cpp-pistache/model/Helpers.cpp +++ b/samples/server/petstore/cpp-pistache/model/Helpers.cpp @@ -10,34 +10,75 @@ * Do not edit the class manually. */ #include "Helpers.h" +#include -namespace org { -namespace openapitools { -namespace server { -namespace helpers { +namespace org::openapitools::server::helpers +{ +const std::regex regexRfc3339_date(R"(^(\d{4})\-(\d{2})\-(\d{2})$)"); +const std::regex regexRfc3339_date_time( + R"(^(\d{4})\-(\d{2})\-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|([\+\-])(\d{2}):(\d{2}))$)" +); + + +namespace +{ + // Determine if given year is a leap year + // See RFC 3339, Appendix C https://tools.ietf.org/html/rfc3339#appendix-C + bool isLeapYear(const uint16_t year) { + return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)); + } + + bool validateDateValues(const uint16_t year, const uint16_t month, const uint16_t day) { + return !( + (month == 0 || month > 12) + || (day == 0) + || (month == 2 && day > (28 + (isLeapYear(year) ? 1 : 0))) + || (month <= 7 && day > (30 + month % 2)) + || (month >= 8 && day > (31 - month % 2)) + ); + } + + bool validateTimeValues(const uint16_t hours, const uint16_t minutes, const uint16_t seconds) { + return (hours <= 23) && (minutes <= 59) && (seconds <= 60); + } +} + +bool validateRfc3339_date(const std::string& str) { + std::smatch match; + const bool found = std::regex_search(str, match, regexRfc3339_date); + return found && validateDateValues(std::stoi(match[1]), std::stoi(match[2]), std::stoi(match[3])); +} + +bool validateRfc3339_date_time(const std::string& str) { + std::smatch match; + const bool found = std::regex_search(str, match, regexRfc3339_date_time); + return found + && validateDateValues(std::stoi(match[1]), std::stoi(match[2]), std::stoi(match[3])) + && validateTimeValues(std::stoi(match[4]), std::stoi(match[5]), std::stoi(match[6])); +} std::string toStringValue(const std::string &value){ return std::string(value); } -std::string toStringValue(const int32_t &value){ +std::string toStringValue(const int32_t value){ return std::to_string(value); } -std::string toStringValue(const int64_t &value){ +std::string toStringValue(const int64_t value){ return std::to_string(value); } -std::string toStringValue(const bool &value){ - return value?std::string("true"):std::string("false"); +std::string toStringValue(const bool value){ + return value ? std::string("true") : std::string("false"); } -std::string toStringValue(const float &value){ +std::string toStringValue(const float value){ return std::to_string(value); } -std::string toStringValue(const double &value){ +std::string toStringValue(const double value){ return std::to_string(value); } @@ -67,9 +108,15 @@ bool fromStringValue(const std::string &inStr, int64_t &value){ } bool fromStringValue(const std::string &inStr, bool &value){ - bool result = true; - inStr == "true"?value = true: inStr == "false"?value = false: result = false; - return result; + if (inStr == "true") { + value = true; + return true; + } + if (inStr == "false") { + value = false; + return true; + } + return false; } bool fromStringValue(const std::string &inStr, float &value){ @@ -92,7 +139,4 @@ bool fromStringValue(const std::string &inStr, double &value){ return true; } -} -} -} -} +} // namespace org::openapitools::server::helpers diff --git a/samples/server/petstore/cpp-pistache/model/Helpers.h b/samples/server/petstore/cpp-pistache/model/Helpers.h index 9c8c02c4ae6..176b817de1e 100644 --- a/samples/server/petstore/cpp-pistache/model/Helpers.h +++ b/samples/server/petstore/cpp-pistache/model/Helpers.h @@ -24,17 +24,80 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace helpers { +namespace org::openapitools::server::helpers +{ + + class ValidationException : public std::runtime_error + { + public: + explicit ValidationException(const std::string& what) + : std::runtime_error(what) + { } + ~ValidationException() override = default; + }; + + /// + /// Validate a string against the full-date definition of RFC 3339, section 5.6. + /// + bool validateRfc3339_date(const std::string& str); + + /// + /// Validate a string against the date-time definition of RFC 3339, section 5.6. + /// + bool validateRfc3339_date_time(const std::string& str); + + namespace sfinae_helpers + { + struct NoType {}; + template NoType operator==(const T1&, const T2&); + + template class EqualsOperatorAvailable + { + public: + enum + { + value = !std::is_same< decltype(std::declval() == std::declval()), NoType >::value + }; + }; + } // namespace sfinae_helpers + + + /// + /// Determine if the given vector only has unique elements. T must provide the == operator. + /// + template + bool hasOnlyUniqueItems(const std::vector& vec) + { + static_assert(sfinae_helpers::EqualsOperatorAvailable::value, + "hasOnlyUniqueItems cannot be called, passed template type does not provide == operator."); + if (vec.size() <= 1) + { + return true; + } + // Compare every element of vec to every other element of vec. + // This isn't an elegant way to do this, since it's O(n^2), + // but it's the best solution working only with the == operator. + // This could be greatly improved if our models provided a valid hash + // and/or the < operator + for (size_t i = 0; i < vec.size() - 1; i++) + { + for (size_t j = i + 1; j < vec.size(); j++) + { + if (vec[i] == vec[j]) + { + return false; + } + } + } + return true; + } std::string toStringValue(const std::string &value); - std::string toStringValue(const int32_t &value); - std::string toStringValue(const int64_t &value); - std::string toStringValue(const bool &value); - std::string toStringValue(const float &value); - std::string toStringValue(const double &value); + std::string toStringValue(const int32_t value); + std::string toStringValue(const int64_t value); + std::string toStringValue(const bool value); + std::string toStringValue(const float value); + std::string toStringValue(const double value); bool fromStringValue(const std::string &inStr, std::string &value); bool fromStringValue(const std::string &inStr, int32_t &value); @@ -68,9 +131,6 @@ namespace helpers { return fromStringValue(inStrings, value); } -} -} -} -} +} // namespace org::openapitools::server::helpers -#endif // Helpers_H_ \ No newline at end of file +#endif // Helpers_H_ diff --git a/samples/server/petstore/cpp-pistache/model/Order.cpp b/samples/server/petstore/cpp-pistache/model/Order.cpp index 986cf6b24fa..2d04f0ac637 100644 --- a/samples/server/petstore/cpp-pistache/model/Order.cpp +++ b/samples/server/petstore/cpp-pistache/model/Order.cpp @@ -12,11 +12,12 @@ #include "Order.h" +#include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace model { +#include + +namespace org::openapitools::server::model +{ Order::Order() { @@ -35,13 +36,64 @@ Order::Order() } -Order::~Order() +void Order::validate() const { + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } } -void Order::validate() +bool Order::validate(std::stringstream& msg) const { - // TODO: implement validation + return validate(msg, ""); +} + +bool Order::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "Order" : pathPrefix; + + + + + + + + + return success; +} + +bool Order::operator==(const Order& rhs) const +{ + return + + + + ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && + + + ((!petIdIsSet() && !rhs.petIdIsSet()) || (petIdIsSet() && rhs.petIdIsSet() && getPetId() == rhs.getPetId())) && + + + ((!quantityIsSet() && !rhs.quantityIsSet()) || (quantityIsSet() && rhs.quantityIsSet() && getQuantity() == rhs.getQuantity())) && + + + ((!shipDateIsSet() && !rhs.shipDateIsSet()) || (shipDateIsSet() && rhs.shipDateIsSet() && getShipDate() == rhs.getShipDate())) && + + + ((!statusIsSet() && !rhs.statusIsSet()) || (statusIsSet() && rhs.statusIsSet() && getStatus() == rhs.getStatus())) && + + + ((!completeIsSet() && !rhs.completeIsSet()) || (completeIsSet() && rhs.completeIsSet() && isComplete() == rhs.isComplete())) + + ; +} + +bool Order::operator!=(const Order& rhs) const +{ + return !(*this == rhs); } void to_json(nlohmann::json& j, const Order& o) @@ -201,8 +253,5 @@ void Order::unsetComplete() } -} -} -} -} +} // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/Order.h b/samples/server/petstore/cpp-pistache/model/Order.h index d900b633f32..3d28e1eef6b 100644 --- a/samples/server/petstore/cpp-pistache/model/Order.h +++ b/samples/server/petstore/cpp-pistache/model/Order.h @@ -22,10 +22,8 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace model { +namespace org::openapitools::server::model +{ /// /// An order for a pets from the pet store @@ -34,9 +32,22 @@ class Order { public: Order(); - virtual ~Order(); + virtual ~Order() = default; - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const Order& rhs) const; + bool operator!=(const Order& rhs) const; ///////////////////////////////////////////// /// Order members @@ -99,11 +110,11 @@ protected: bool m_StatusIsSet; bool m_Complete; bool m_CompleteIsSet; + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -} -} -} -} +} // namespace org::openapitools::server::model #endif /* Order_H_ */ diff --git a/samples/server/petstore/cpp-pistache/model/Pet.cpp b/samples/server/petstore/cpp-pistache/model/Pet.cpp index 434b1339cd0..9c7ba886a44 100644 --- a/samples/server/petstore/cpp-pistache/model/Pet.cpp +++ b/samples/server/petstore/cpp-pistache/model/Pet.cpp @@ -12,11 +12,12 @@ #include "Pet.h" +#include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace model { +#include + +namespace org::openapitools::server::model +{ Pet::Pet() { @@ -30,13 +31,106 @@ Pet::Pet() } -Pet::~Pet() +void Pet::validate() const { + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } } -void Pet::validate() +bool Pet::validate(std::stringstream& msg) const { - // TODO: implement validation + return validate(msg, ""); +} + +bool Pet::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "Pet" : pathPrefix; + + + + + + + /* PhotoUrls */ { + const std::vector& value = m_PhotoUrls; + const std::string currentValuePath = _pathPrefix + ".photoUrls"; + + + { // Recursive validation of array elements + const std::string oldValuePath = currentValuePath; + int i = 0; + for (const std::string& value : value) + { + const std::string currentValuePath = oldValuePath + "[" + std::to_string(i) + "]"; + + + + i++; + } + } + + } + + + if (tagsIsSet()) + { + const std::vector& value = m_Tags; + const std::string currentValuePath = _pathPrefix + ".tags"; + + + { // Recursive validation of array elements + const std::string oldValuePath = currentValuePath; + int i = 0; + for (const Tag& value : value) + { + const std::string currentValuePath = oldValuePath + "[" + std::to_string(i) + "]"; + + success = value.validate(msg, currentValuePath + ".tags") && success; + + i++; + } + } + + } + + + + return success; +} + +bool Pet::operator==(const Pet& rhs) const +{ + return + + + + ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && + + + ((!categoryIsSet() && !rhs.categoryIsSet()) || (categoryIsSet() && rhs.categoryIsSet() && getCategory() == rhs.getCategory())) && + + (getName() == rhs.getName()) + && + + (getPhotoUrls() == rhs.getPhotoUrls()) + && + + + ((!tagsIsSet() && !rhs.tagsIsSet()) || (tagsIsSet() && rhs.tagsIsSet() && getTags() == rhs.getTags())) && + + + ((!statusIsSet() && !rhs.statusIsSet()) || (statusIsSet() && rhs.statusIsSet() && getStatus() == rhs.getStatus())) + + ; +} + +bool Pet::operator!=(const Pet& rhs) const +{ + return !(*this == rhs); } void to_json(nlohmann::json& j, const Pet& o) @@ -124,7 +218,7 @@ void Pet::setName(std::string const& value) { m_Name = value; } -std::vector& Pet::getPhotoUrls() +std::vector Pet::getPhotoUrls() const { return m_PhotoUrls; } @@ -132,7 +226,7 @@ void Pet::setPhotoUrls(std::vector const& value) { m_PhotoUrls = value; } -std::vector& Pet::getTags() +std::vector Pet::getTags() const { return m_Tags; } @@ -168,8 +262,5 @@ void Pet::unsetStatus() } -} -} -} -} +} // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/Pet.h b/samples/server/petstore/cpp-pistache/model/Pet.h index eddf475f6ee..1cd841a08fa 100644 --- a/samples/server/petstore/cpp-pistache/model/Pet.h +++ b/samples/server/petstore/cpp-pistache/model/Pet.h @@ -25,10 +25,8 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace model { +namespace org::openapitools::server::model +{ /// /// A pet for sale in the pet store @@ -37,9 +35,22 @@ class Pet { public: Pet(); - virtual ~Pet(); + virtual ~Pet() = default; - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const Pet& rhs) const; + bool operator!=(const Pet& rhs) const; ///////////////////////////////////////////// /// Pet members @@ -66,12 +77,12 @@ public: /// /// /// - std::vector& getPhotoUrls(); + std::vector getPhotoUrls() const; void setPhotoUrls(std::vector const& value); /// /// /// - std::vector& getTags(); + std::vector getTags() const; void setTags(std::vector const& value); bool tagsIsSet() const; void unsetTags(); @@ -98,11 +109,11 @@ protected: bool m_TagsIsSet; std::string m_Status; bool m_StatusIsSet; + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -} -} -} -} +} // namespace org::openapitools::server::model #endif /* Pet_H_ */ diff --git a/samples/server/petstore/cpp-pistache/model/Tag.cpp b/samples/server/petstore/cpp-pistache/model/Tag.cpp index cba759bad1d..659565e4034 100644 --- a/samples/server/petstore/cpp-pistache/model/Tag.cpp +++ b/samples/server/petstore/cpp-pistache/model/Tag.cpp @@ -12,11 +12,12 @@ #include "Tag.h" +#include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace model { +#include + +namespace org::openapitools::server::model +{ Tag::Tag() { @@ -27,13 +28,48 @@ Tag::Tag() } -Tag::~Tag() +void Tag::validate() const { + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } } -void Tag::validate() +bool Tag::validate(std::stringstream& msg) const { - // TODO: implement validation + return validate(msg, ""); +} + +bool Tag::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "Tag" : pathPrefix; + + + + + return success; +} + +bool Tag::operator==(const Tag& rhs) const +{ + return + + + + ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && + + + ((!nameIsSet() && !rhs.nameIsSet()) || (nameIsSet() && rhs.nameIsSet() && getName() == rhs.getName())) + + ; +} + +bool Tag::operator!=(const Tag& rhs) const +{ + return !(*this == rhs); } void to_json(nlohmann::json& j, const Tag& o) @@ -97,8 +133,5 @@ void Tag::unsetName() } -} -} -} -} +} // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/Tag.h b/samples/server/petstore/cpp-pistache/model/Tag.h index 4b422931d77..ddebeadae43 100644 --- a/samples/server/petstore/cpp-pistache/model/Tag.h +++ b/samples/server/petstore/cpp-pistache/model/Tag.h @@ -22,10 +22,8 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace model { +namespace org::openapitools::server::model +{ /// /// A tag for a pet @@ -34,9 +32,22 @@ class Tag { public: Tag(); - virtual ~Tag(); + virtual ~Tag() = default; - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const Tag& rhs) const; + bool operator!=(const Tag& rhs) const; ///////////////////////////////////////////// /// Tag members @@ -63,11 +74,11 @@ protected: bool m_IdIsSet; std::string m_Name; bool m_NameIsSet; + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -} -} -} -} +} // namespace org::openapitools::server::model #endif /* Tag_H_ */ diff --git a/samples/server/petstore/cpp-pistache/model/User.cpp b/samples/server/petstore/cpp-pistache/model/User.cpp index 2db9316b75d..c997bf9734d 100644 --- a/samples/server/petstore/cpp-pistache/model/User.cpp +++ b/samples/server/petstore/cpp-pistache/model/User.cpp @@ -12,11 +12,12 @@ #include "User.h" +#include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace model { +#include + +namespace org::openapitools::server::model +{ User::User() { @@ -39,13 +40,72 @@ User::User() } -User::~User() +void User::validate() const { + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } } -void User::validate() +bool User::validate(std::stringstream& msg) const { - // TODO: implement validation + return validate(msg, ""); +} + +bool User::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "User" : pathPrefix; + + + + + + + + + + + return success; +} + +bool User::operator==(const User& rhs) const +{ + return + + + + ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && + + + ((!usernameIsSet() && !rhs.usernameIsSet()) || (usernameIsSet() && rhs.usernameIsSet() && getUsername() == rhs.getUsername())) && + + + ((!firstNameIsSet() && !rhs.firstNameIsSet()) || (firstNameIsSet() && rhs.firstNameIsSet() && getFirstName() == rhs.getFirstName())) && + + + ((!lastNameIsSet() && !rhs.lastNameIsSet()) || (lastNameIsSet() && rhs.lastNameIsSet() && getLastName() == rhs.getLastName())) && + + + ((!emailIsSet() && !rhs.emailIsSet()) || (emailIsSet() && rhs.emailIsSet() && getEmail() == rhs.getEmail())) && + + + ((!passwordIsSet() && !rhs.passwordIsSet()) || (passwordIsSet() && rhs.passwordIsSet() && getPassword() == rhs.getPassword())) && + + + ((!phoneIsSet() && !rhs.phoneIsSet()) || (phoneIsSet() && rhs.phoneIsSet() && getPhone() == rhs.getPhone())) && + + + ((!userStatusIsSet() && !rhs.userStatusIsSet()) || (userStatusIsSet() && rhs.userStatusIsSet() && getUserStatus() == rhs.getUserStatus())) + + ; +} + +bool User::operator!=(const User& rhs) const +{ + return !(*this == rhs); } void to_json(nlohmann::json& j, const User& o) @@ -253,8 +313,5 @@ void User::unsetUserStatus() } -} -} -} -} +} // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/User.h b/samples/server/petstore/cpp-pistache/model/User.h index 1f4c17ce6a8..02bd5f4230a 100644 --- a/samples/server/petstore/cpp-pistache/model/User.h +++ b/samples/server/petstore/cpp-pistache/model/User.h @@ -22,10 +22,8 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace model { +namespace org::openapitools::server::model +{ /// /// A User who is purchasing from the pet store @@ -34,9 +32,22 @@ class User { public: User(); - virtual ~User(); + virtual ~User() = default; - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const User& rhs) const; + bool operator!=(const User& rhs) const; ///////////////////////////////////////////// /// User members @@ -117,11 +128,11 @@ protected: bool m_PhoneIsSet; int32_t m_UserStatus; bool m_UserStatusIsSet; + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -} -} -} -} +} // namespace org::openapitools::server::model #endif /* User_H_ */ diff --git a/samples/server/petstore/erlang-server/.openapi-generator/FILES b/samples/server/petstore/erlang-server/.openapi-generator/FILES new file mode 100644 index 00000000000..9c50202b935 --- /dev/null +++ b/samples/server/petstore/erlang-server/.openapi-generator/FILES @@ -0,0 +1,14 @@ +README.md +priv/openapi.json +rebar.config +src/openapi.app.src +src/openapi_api.erl +src/openapi_auth.erl +src/openapi_default_logic_handler.erl +src/openapi_logic_handler.erl +src/openapi_pet_handler.erl +src/openapi_router.erl +src/openapi_server.erl +src/openapi_store_handler.erl +src/openapi_user_handler.erl +src/openapi_utils.erl diff --git a/samples/server/petstore/erlang-server/.openapi-generator/VERSION b/samples/server/petstore/erlang-server/.openapi-generator/VERSION index d99e7162d01..d509cc92aa8 100644 --- a/samples/server/petstore/erlang-server/.openapi-generator/VERSION +++ b/samples/server/petstore/erlang-server/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.1.1-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/erlang-server/rebar.config b/samples/server/petstore/erlang-server/rebar.config index 7ddca0f3027..743b108f384 100644 --- a/samples/server/petstore/erlang-server/rebar.config +++ b/samples/server/petstore/erlang-server/rebar.config @@ -1,6 +1,6 @@ {deps, [ - {cowboy, {git, "https://github.com/ninenines/cowboy.git", {tag, "2.5.0"}}}, + {cowboy, {git, "https://github.com/ninenines/cowboy.git", {tag, "2.8.0"}}}, {rfc3339, {git, "https://github.com/talentdeficit/rfc3339.git", {tag, "master"}}}, - {jsx, {git, "https://github.com/talentdeficit/jsx.git", {tag, "2.9.0"}}}, - {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.5.2"}}} + {jsx, {git, "https://github.com/talentdeficit/jsx.git", {tag, "v3.1.0"}}}, + {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.5.6"}}} ]}. diff --git a/samples/server/petstore/kotlin-server/ktor/README.md b/samples/server/petstore/kotlin-server/ktor/README.md index 91f55b2101f..69886a32d5a 100644 --- a/samples/server/petstore/kotlin-server/ktor/README.md +++ b/samples/server/petstore/kotlin-server/ktor/README.md @@ -6,8 +6,8 @@ Generated by OpenAPI Generator 6.0.0-SNAPSHOT. ## Requires -* Kotlin 1.3.21 -* Gradle 4.9 +* Kotlin 1.4.31 +* Gradle 6.8.2 ## Build diff --git a/samples/server/petstore/kotlin-server/ktor/build.gradle b/samples/server/petstore/kotlin-server/ktor/build.gradle index 25536d4e531..c69f129160f 100644 --- a/samples/server/petstore/kotlin-server/ktor/build.gradle +++ b/samples/server/petstore/kotlin-server/ktor/build.gradle @@ -2,13 +2,13 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '4.9' + gradleVersion = '6.8.2' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.3.21' - ext.ktor_version = '1.1.3' + ext.kotlin_version = '1.4.31' + ext.ktor_version = '1.5.2' ext.shadow_version = '2.0.3' repositories { @@ -29,7 +29,7 @@ apply plugin: 'application' mainClassName = "io.ktor.server.netty.DevelopmentEngine" -// Initialization order with shadow 2.0.1 and Gradle 4.3 is weird. +// Initialization order with shadow 2.0.1 and Gradle 6.8.2 is weird. // See https://github.com/johnrengelman/shadow/issues/336#issuecomment-355402508 apply plugin: 'com.github.johnrengelman.shadow' @@ -59,6 +59,7 @@ dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" compile "io.ktor:ktor-server-netty:$ktor_version" compile "io.ktor:ktor-metrics:$ktor_version" + compile "io.ktor:ktor-auth:$ktor_version" compile "io.ktor:ktor-locations:$ktor_version" compile "io.ktor:ktor-gson:$ktor_version" compile "io.ktor:ktor-client-core:$ktor_version" diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt index 2b0cd5cdb5f..54658d6ba5d 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt @@ -18,12 +18,11 @@ import io.ktor.gson.GsonConverter import io.ktor.http.ContentType import io.ktor.locations.KtorExperimentalLocationsAPI import io.ktor.locations.Locations -import io.ktor.metrics.Metrics import io.ktor.routing.Routing import java.util.concurrent.TimeUnit -import io.ktor.util.KtorExperimentalAPI import io.ktor.auth.Authentication import io.ktor.auth.oauth +import io.ktor.metrics.dropwizard.DropwizardMetrics import org.openapitools.server.infrastructure.ApiKeyCredential import org.openapitools.server.infrastructure.ApiPrincipal import org.openapitools.server.infrastructure.apiKeyAuth @@ -32,23 +31,21 @@ import org.openapitools.server.apis.StoreApi import org.openapitools.server.apis.UserApi -@KtorExperimentalAPI internal val settings = HoconApplicationConfig(ConfigFactory.defaultApplication(HTTP::class.java.classLoader)) object HTTP { val client = HttpClient(Apache) } -@KtorExperimentalAPI @KtorExperimentalLocationsAPI fun Application.main() { install(DefaultHeaders) - install(Metrics) { + install(DropwizardMetrics) { val reporter = Slf4jReporter.forRegistry(registry) - .outputTo(log) - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .build() + .outputTo(log) + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .build() reporter.start(10, TimeUnit.SECONDS) } install(ContentNegotiation) { @@ -72,8 +69,8 @@ fun Application.main() { client = HttpClient(Apache) providerLookup = { ApplicationAuthProviders["petstore_auth"] } urlProvider = { _ -> - // TODO: define a callback url here. - "/" + // TODO: define a callback url here. + "/" } } } @@ -84,8 +81,7 @@ fun Application.main() { } - environment.monitor.subscribe(ApplicationStopping) - { + environment.monitor.subscribe(ApplicationStopping) { HTTP.client.close() } } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt index c16a32ef70f..8483e64319d 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt @@ -8,11 +8,7 @@ import io.ktor.features.deflate import io.ktor.features.gzip import io.ktor.features.minimumSize import io.ktor.http.HttpMethod -import io.ktor.util.KtorExperimentalAPI -import java.time.Duration -import java.util.concurrent.Executors - -import org.openapitools.server.settings +import java.util.concurrent.TimeUnit /** @@ -25,7 +21,7 @@ import org.openapitools.server.settings */ internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit { return { - maxAge = Duration.ofDays(365) + maxAgeInSeconds = TimeUnit.DAYS.toSeconds(365) includeSubDomains = true preload = false @@ -55,7 +51,6 @@ internal fun ApplicationCompressionConfiguration(): Compression.Configuration.() } // Defines authentication mechanisms used throughout the application. -@KtorExperimentalAPI val ApplicationAuthProviders: Map = listOf( OAuthServerSettings.OAuth2ServerSettings( name = "petstore_auth", @@ -77,6 +72,3 @@ val ApplicationAuthProviders: Map = listOf) + @Location("/pet/findByStatus") class findPetsByStatus(val status: kotlin.collections.List) /** * Finds Pets by tags @@ -38,7 +47,7 @@ object Paths { * @param tags Tags to filter by */ @KtorExperimentalLocationsAPI - @Location("/pet/findByTags") class findPetsByTags(val tags: kotlin.Array) + @Location("/pet/findByTags") class findPetsByTags(val tags: kotlin.collections.List) /** * Find pet by ID @@ -48,6 +57,34 @@ object Paths { @KtorExperimentalLocationsAPI @Location("/pet/{petId}") class getPetById(val petId: kotlin.Long) + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + @KtorExperimentalLocationsAPI + @Location("/pet") class updatePet(val body: Pet) + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + */ + @KtorExperimentalLocationsAPI + @Location("/pet/{petId}") class updatePetWithForm(val petId: kotlin.Long, val name: kotlin.String? = null, val status: kotlin.String? = null) + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + */ + @KtorExperimentalLocationsAPI + @Location("/pet/{petId}/uploadImage") class uploadFile(val petId: kotlin.Long, val additionalMetadata: kotlin.String? = null, val file: java.io.File? = null) + /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -71,6 +108,38 @@ object Paths { @KtorExperimentalLocationsAPI @Location("/store/order/{orderId}") class getOrderById(val orderId: kotlin.Long) + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + @KtorExperimentalLocationsAPI + @Location("/store/order") class placeOrder(val body: Order) + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + @KtorExperimentalLocationsAPI + @Location("/user") class createUser(val body: User) + + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + @KtorExperimentalLocationsAPI + @Location("/user/createWithArray") class createUsersWithArrayInput(val body: kotlin.collections.List) + + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + @KtorExperimentalLocationsAPI + @Location("/user/createWithList") class createUsersWithListInput(val body: kotlin.collections.List) + /** * Delete user * This can only be done by the logged in user. @@ -103,4 +172,13 @@ object Paths { @KtorExperimentalLocationsAPI @Location("/user/logout") class logoutUser() + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + @KtorExperimentalLocationsAPI + @Location("/user/{username}") class updateUser(val username: kotlin.String, val body: User) + } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt index 3ac3578638d..9226541eb34 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt @@ -20,17 +20,18 @@ import io.ktor.auth.OAuthAccessTokenResponse import io.ktor.auth.OAuthServerSettings import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.delete -import io.ktor.locations.get import io.ktor.response.respond import io.ktor.response.respondText import io.ktor.routing.Route -import io.ktor.routing.post -import io.ktor.routing.put -import io.ktor.routing.route - import org.openapitools.server.Paths +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.delete +import io.ktor.locations.get +import io.ktor.locations.post +import io.ktor.locations.put +import io.ktor.locations.options +import io.ktor.locations.head + import org.openapitools.server.infrastructure.ApiPrincipal @@ -41,40 +42,27 @@ import org.openapitools.server.models.Pet fun Route.PetApi() { val gson = Gson() val empty = mutableMapOf() - - route("/pet") { - authenticate("petstore_auth") { - post { - val principal = call.authentication.principal() - - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - call.respond(HttpStatusCode.NotImplemented) - } - } - } + authenticate("petstore_auth") { + post { + val principal = call.authentication.principal()!! + + call.respond(HttpStatusCode.NotImplemented) + } } - - delete { _: Paths.deletePet -> - val principal = call.authentication.principal() + authenticate("petstore_auth") { + delete { + val principal = call.authentication.principal()!! - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - call.respond(HttpStatusCode.NotImplemented) - } + call.respond(HttpStatusCode.NotImplemented) + } } - - get { _: Paths.findPetsByStatus -> - val principal = call.authentication.principal() + authenticate("petstore_auth") { + get { + val principal = call.authentication.principal()!! - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - val exampleContentType = "application/json" + val exampleContentType = "application/json" val exampleContentString = """{ "photoUrls" : [ "photoUrls", "photoUrls" ], "name" : "doggie", @@ -93,22 +81,19 @@ fun Route.PetApi() { "status" : "available" }""" - when(exampleContentType) { + when (exampleContentType) { "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } - } + } } - - get { _: Paths.findPetsByTags -> - val principal = call.authentication.principal() + authenticate("petstore_auth") { + get { + val principal = call.authentication.principal()!! - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - val exampleContentType = "application/json" + val exampleContentType = "application/json" val exampleContentString = """{ "photoUrls" : [ "photoUrls", "photoUrls" ], "name" : "doggie", @@ -127,22 +112,19 @@ fun Route.PetApi() { "status" : "available" }""" - when(exampleContentType) { + when (exampleContentType) { "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } - } + } } - - get { _: Paths.getPetById -> - val principal = call.authentication.principal() + authenticate("api_key") { + get { + val principal = call.authentication.principal()!! - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - val exampleContentType = "application/json" + val exampleContentType = "application/json" val exampleContentString = """{ "photoUrls" : [ "photoUrls", "photoUrls" ], "name" : "doggie", @@ -161,68 +143,47 @@ fun Route.PetApi() { "status" : "available" }""" - when(exampleContentType) { + when (exampleContentType) { "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } - } + } } - - route("/pet") { - authenticate("petstore_auth") { - put { - val principal = call.authentication.principal() - - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - call.respond(HttpStatusCode.NotImplemented) - } - } - } + authenticate("petstore_auth") { + put { + val principal = call.authentication.principal()!! + + call.respond(HttpStatusCode.NotImplemented) + } } - - route("/pet/{petId}") { - authenticate("petstore_auth") { - post { - val principal = call.authentication.principal() - - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - call.respond(HttpStatusCode.NotImplemented) - } - } - } + authenticate("petstore_auth") { + post { + val principal = call.authentication.principal()!! + + call.respond(HttpStatusCode.NotImplemented) + } } - - route("/pet/{petId}/uploadImage") { - authenticate("petstore_auth") { - post { - val principal = call.authentication.principal() + authenticate("petstore_auth") { + post { + val principal = call.authentication.principal()!! + + val exampleContentType = "application/json" + val exampleContentString = """{ + "code" : 0, + "type" : "type", + "message" : "message" + }""" - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - val exampleContentType = "application/json" - val exampleContentString = """{ - "code" : 0, - "type" : "type", - "message" : "message" - }""" - - when(exampleContentType) { - "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) - "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) - else -> call.respondText(exampleContentString) - } - } - } + when (exampleContentType) { + "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) + "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) + else -> call.respondText(exampleContentString) } } + } } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt index 17b2c526bd9..2e5f4ab8b96 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt @@ -20,17 +20,18 @@ import io.ktor.auth.OAuthAccessTokenResponse import io.ktor.auth.OAuthServerSettings import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.delete -import io.ktor.locations.get import io.ktor.response.respond import io.ktor.response.respondText import io.ktor.routing.Route -import io.ktor.routing.post -import io.ktor.routing.put -import io.ktor.routing.route - import org.openapitools.server.Paths +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.delete +import io.ktor.locations.get +import io.ktor.locations.post +import io.ktor.locations.put +import io.ktor.locations.options +import io.ktor.locations.head + import org.openapitools.server.infrastructure.ApiPrincipal @@ -40,24 +41,19 @@ import org.openapitools.server.models.Order fun Route.StoreApi() { val gson = Gson() val empty = mutableMapOf() - - delete { _: Paths.deleteOrder -> + delete { call.respond(HttpStatusCode.NotImplemented) } - - get { _: Paths.getInventory -> - val principal = call.authentication.principal() + authenticate("api_key") { + get { + val principal = call.authentication.principal()!! - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - call.respond(HttpStatusCode.NotImplemented) - } + call.respond(HttpStatusCode.NotImplemented) + } } - - get { _: Paths.getOrderById -> + get { val exampleContentType = "application/json" val exampleContentString = """{ "petId" : 6, @@ -68,31 +64,28 @@ fun Route.StoreApi() { "status" : "placed" }""" - when(exampleContentType) { + when (exampleContentType) { "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } } - - route("/store/order") { - post { - val exampleContentType = "application/json" - val exampleContentString = """{ - "petId" : 6, - "quantity" : 1, - "id" : 0, - "shipDate" : "2000-01-23T04:56:07.000+00:00", - "complete" : false, - "status" : "placed" - }""" - - when(exampleContentType) { - "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) - "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) - else -> call.respondText(exampleContentString) - } + post { + val exampleContentType = "application/json" + val exampleContentString = """{ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" + }""" + + when (exampleContentType) { + "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) + "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) + else -> call.respondText(exampleContentString) } } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt index 7fc0b78fa99..e248d75ae0c 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt @@ -20,17 +20,18 @@ import io.ktor.auth.OAuthAccessTokenResponse import io.ktor.auth.OAuthServerSettings import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.delete -import io.ktor.locations.get import io.ktor.response.respond import io.ktor.response.respondText import io.ktor.routing.Route -import io.ktor.routing.post -import io.ktor.routing.put -import io.ktor.routing.route - import org.openapitools.server.Paths +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.delete +import io.ktor.locations.get +import io.ktor.locations.post +import io.ktor.locations.put +import io.ktor.locations.options +import io.ktor.locations.head + import org.openapitools.server.infrastructure.ApiPrincipal @@ -40,34 +41,23 @@ import org.openapitools.server.models.User fun Route.UserApi() { val gson = Gson() val empty = mutableMapOf() - - route("/user") { - post { - call.respond(HttpStatusCode.NotImplemented) - } - } - - - route("/user/createWithArray") { - post { - call.respond(HttpStatusCode.NotImplemented) - } - } - - - route("/user/createWithList") { - post { - call.respond(HttpStatusCode.NotImplemented) - } - } - - - delete { _: Paths.deleteUser -> + post { call.respond(HttpStatusCode.NotImplemented) } + post { + call.respond(HttpStatusCode.NotImplemented) + } - get { _: Paths.getUserByName -> + post { + call.respond(HttpStatusCode.NotImplemented) + } + + delete { + call.respond(HttpStatusCode.NotImplemented) + } + + get { val exampleContentType = "application/json" val exampleContentString = """{ "firstName" : "firstName", @@ -80,28 +70,23 @@ fun Route.UserApi() { "username" : "username" }""" - when(exampleContentType) { + when (exampleContentType) { "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } } - - get { _: Paths.loginUser -> + get { call.respond(HttpStatusCode.NotImplemented) } - - get { _: Paths.logoutUser -> + get { call.respond(HttpStatusCode.NotImplemented) } - - route("/user/{username}") { - put { - call.respond(HttpStatusCode.NotImplemented) - } + put { + call.respond(HttpStatusCode.NotImplemented) } } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt index 8de972967ef..de09ba8b6b6 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt @@ -1,85 +1,105 @@ package org.openapitools.server.infrastructure -import io.ktor.application.ApplicationCall -import io.ktor.application.call -import io.ktor.auth.Authentication -import io.ktor.auth.AuthenticationFailedCause -import io.ktor.auth.AuthenticationPipeline -import io.ktor.auth.AuthenticationProvider -import io.ktor.auth.Credential -import io.ktor.auth.Principal -import io.ktor.auth.UnauthorizedResponse -import io.ktor.http.auth.HeaderValueEncoding -import io.ktor.http.auth.HttpAuthHeader -import io.ktor.request.ApplicationRequest -import io.ktor.response.respond +import io.ktor.application.* +import io.ktor.auth.* +import io.ktor.http.auth.* +import io.ktor.request.* +import io.ktor.response.* enum class ApiKeyLocation(val location: String) { QUERY("query"), HEADER("header") } -data class ApiKeyCredential(val value: String): Credential + +data class ApiKeyCredential(val value: String) : Credential data class ApiPrincipal(val apiKeyCredential: ApiKeyCredential?) : Principal - - /** * Represents a Api Key authentication provider * @param name is the name of the provider, or `null` for a default provider */ -class ApiKeyAuthenticationProvider(name: String?) : AuthenticationProvider(name) { - internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = { null } +class ApiKeyAuthenticationProvider(configuration: Configuration) : AuthenticationProvider(configuration) { - var apiKeyName: String = ""; + private val authenticationFunction = configuration.authenticationFunction - var apiKeyLocation: ApiKeyLocation = ApiKeyLocation.QUERY; + private val apiKeyName: String = configuration.apiKeyName - /** - * Sets a validation function that will check given [ApiKeyCredential] instance and return [Principal], - * or null if credential does not correspond to an authenticated principal - */ - fun validate(body: suspend ApplicationCall.(ApiKeyCredential) -> Principal?) { - authenticationFunction = body - } -} + private val apiKeyLocation: ApiKeyLocation = configuration.apiKeyLocation -fun Authentication.Configuration.apiKeyAuth(name: String? = null, configure: ApiKeyAuthenticationProvider.() -> Unit) { - val provider = ApiKeyAuthenticationProvider(name).apply(configure) - val apiKeyName = provider.apiKeyName - val apiKeyLocation = provider.apiKeyLocation - val authenticate = provider.authenticationFunction + internal fun install() { + pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> + val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) + val principal = credentials?.let { authenticationFunction(call, it) } - provider.pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> - val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) - val principal = credentials?.let { authenticate(call, it) } + val cause = when { + credentials == null -> AuthenticationFailedCause.NoCredentials + principal == null -> AuthenticationFailedCause.InvalidCredentials + else -> null + } - val cause = when { - credentials == null -> AuthenticationFailedCause.NoCredentials - principal == null -> AuthenticationFailedCause.InvalidCredentials - else -> null - } + if (cause != null) { + context.challenge(apiKeyName, cause) { + call.respond( + UnauthorizedResponse( + HttpAuthHeader.Parameterized( + "API_KEY", + mapOf("key" to apiKeyName), + HeaderValueEncoding.QUOTED_ALWAYS + ) + ) + ) + it.complete() + } + } - if (cause != null) { - context.challenge(apiKeyName, cause) { - // TODO: Verify correct response structure here. - call.respond(UnauthorizedResponse(HttpAuthHeader.Parameterized("API_KEY", mapOf("key" to apiKeyName), HeaderValueEncoding.QUOTED_ALWAYS))) - it.complete() + if (principal != null) { + context.principal(principal) } } + } - if (principal != null) { - context.principal(principal) + class Configuration internal constructor(name: String?) : AuthenticationProvider.Configuration(name) { + + internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = { + throw NotImplementedError( + "Api Key auth validate function is not specified. Use apiKeyAuth { validate { ... } } to fix." + ) + } + + var apiKeyName: String = "" + + var apiKeyLocation: ApiKeyLocation = ApiKeyLocation.QUERY + + /** + * Sets a validation function that will check given [ApiKeyCredential] instance and return [Principal], + * or null if credential does not correspond to an authenticated principal + */ + fun validate(body: suspend ApplicationCall.(ApiKeyCredential) -> Principal?) { + authenticationFunction = body } } } -fun ApplicationRequest.apiKeyAuthenticationCredentials(apiKeyName: String, apiKeyLocation: ApiKeyLocation): ApiKeyCredential? { - val value: String? = when(apiKeyLocation) { +fun Authentication.Configuration.apiKeyAuth( + name: String? = null, + configure: ApiKeyAuthenticationProvider.Configuration.() -> Unit +) { + val configuration = ApiKeyAuthenticationProvider.Configuration(name).apply(configure) + val provider = ApiKeyAuthenticationProvider(configuration) + provider.install() + register(provider) +} + +fun ApplicationRequest.apiKeyAuthenticationCredentials( + apiKeyName: String, + apiKeyLocation: ApiKeyLocation +): ApiKeyCredential? { + val value: String? = when (apiKeyLocation) { ApiKeyLocation.QUERY -> this.queryParameters[apiKeyName] ApiKeyLocation.HEADER -> this.headers[apiKeyName] } - when (value) { - null -> return null - else -> return ApiKeyCredential(value) + return when (value) { + null -> null + else -> ApiKeyCredential(value) } } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/ApiResponse.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/ApiResponse.kt index 45760790990..14f50dbb9ad 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/ApiResponse.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/ApiResponse.kt @@ -19,7 +19,7 @@ import java.io.Serializable * @param type * @param message */ -data class ApiResponse ( +data class ApiResponse( val code: kotlin.Int? = null, val type: kotlin.String? = null, val message: kotlin.String? = null diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Category.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Category.kt index ee26d4c76e5..9d857192138 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Category.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Category.kt @@ -18,7 +18,7 @@ import java.io.Serializable * @param id * @param name */ -data class Category ( +data class Category( val id: kotlin.Long? = null, val name: kotlin.String? = null ) : Serializable diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Order.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Order.kt index 7889abe12ee..5e9e18b0328 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Order.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Order.kt @@ -22,7 +22,7 @@ import java.io.Serializable * @param status Order Status * @param complete */ -data class Order ( +data class Order( val id: kotlin.Long? = null, val petId: kotlin.Long? = null, val quantity: kotlin.Int? = null, diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Pet.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Pet.kt index 8dc13b7ea6e..8b98ce0469c 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Pet.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Pet.kt @@ -24,12 +24,12 @@ import java.io.Serializable * @param tags * @param status pet status in the store */ -data class Pet ( +data class Pet( val name: kotlin.String, - val photoUrls: kotlin.Array, + val photoUrls: kotlin.collections.List, val id: kotlin.Long? = null, val category: Category? = null, - val tags: kotlin.Array? = null, + val tags: kotlin.collections.List? = null, /* pet status in the store */ val status: Pet.Status? = null ) : Serializable diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Tag.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Tag.kt index 49c2887a503..e9626b25c6d 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Tag.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Tag.kt @@ -18,7 +18,7 @@ import java.io.Serializable * @param id * @param name */ -data class Tag ( +data class Tag( val id: kotlin.Long? = null, val name: kotlin.String? = null ) : Serializable diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/User.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/User.kt index dee8de740bd..fdbdb4e1cff 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/User.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/User.kt @@ -24,7 +24,7 @@ import java.io.Serializable * @param phone * @param userStatus User Status */ -data class User ( +data class User( val id: kotlin.Long? = null, val username: kotlin.String? = null, val firstName: kotlin.String? = null, diff --git a/samples/server/petstore/python-flask/requirements.txt b/samples/server/petstore/python-flask/requirements.txt index 72ed547c442..70e1f0c5540 100644 --- a/samples/server/petstore/python-flask/requirements.txt +++ b/samples/server/petstore/python-flask/requirements.txt @@ -8,3 +8,4 @@ werkzeug == 0.16.1; python_version=="3.5" or python_version=="3.4" swagger-ui-bundle >= 0.0.2 python_dateutil >= 2.6.0 setuptools >= 21.0.0 +Flask == 1.1.2 diff --git a/website/src/dynamic/users.yml b/website/src/dynamic/users.yml index 38104947192..7b955bfe337 100644 --- a/website/src/dynamic/users.yml +++ b/website/src/dynamic/users.yml @@ -453,6 +453,11 @@ image: "img/companies/viadee.jpg" infoLink: "https://www.viadee.de" pinned: false +- + caption: "VMware" + image: "img/companies/vmware.png" + infoLink: "https://www.vmware.com/" + pinned: false - caption: Vonage image: "img/companies/vonage.png" diff --git a/website/static/img/companies/vmware.png b/website/static/img/companies/vmware.png new file mode 100644 index 00000000000..7e697256a9e Binary files /dev/null and b/website/static/img/companies/vmware.png differ