Skip to content
GitLab
    • Explore Projects Groups Snippets
Projects Groups Snippets
  • /
  • Help
    • Help
    • Support
    • Community forum
    • Submit feedback
    • Contribute to GitLab
  • Sign in / Register
  • O openapi-generator
  • Project information
    • Project information
    • Activity
    • Labels
    • Members
  • Repository
    • Repository
    • Files
    • Commits
    • Branches
    • Tags
    • Contributors
    • Graph
    • Compare
  • Issues 3,476
    • Issues 3,476
    • List
    • Boards
    • Service Desk
    • Milestones
  • Merge requests 402
    • Merge requests 402
  • CI/CD
    • CI/CD
    • Pipelines
    • Jobs
    • Schedules
  • Deployments
    • Deployments
    • Environments
    • Releases
  • Packages and registries
    • Packages and registries
    • Package Registry
    • Infrastructure Registry
  • Monitor
    • Monitor
    • Incidents
  • Analytics
    • Analytics
    • Value stream
    • CI/CD
    • Repository
  • Wiki
    • Wiki
  • Snippets
    • Snippets
  • Activity
  • Graph
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
Collapse sidebar
  • OpenAPI Tools
  • openapi-generator
  • Merge requests
  • !2314

Fix regex in Python server model code

  • Review changes

  • Download
  • Email patches
  • Plain diff
Merged Administrator requested to merge github/fork/tomghyselinck/python-connexion-regex into master 6 years ago
  • Overview 0
  • Commits 3
  • Pipelines 0
  • Changes 10

Created by: tomghyselinck

PR checklist

  • Read the contribution guidelines.
  • Ran the shell script under ./bin/ to update Petstore sample so that CIs can verify the change. (For instance, only need to run ./bin/{LANG}-petstore.sh, ./bin/openapi3/{LANG}-petstore.sh, ./bin/security/{LANG}-petstore.sh and ./bin/openapi3/security/{LANG}-petstore.sh if updating the {LANG} (e.g. php, ruby, python, etc) code generator or {LANG} client's mustache templates). Windows batch files can be found in .\bin\windows\.
  • Filed the PR against the correct branch: master, 3.4.x, 4.0.x. Default: master.
  • Copied the technical committee to review the pull request if your PR is targeting a particular programming language. -- @taxpon @frol @mbohlool @cbornet @kenjones-cisco @tomplus @Jyhess

Description of the PR

The generated Python server model code incorrectly escapes the regular expressions. Fixes #1823 (closed)

The code in the Python client was generated correctly. Overriding DefaultCodegen::toRegularExpression seems to do the trick.

The client also overrides DefaultCodegen::addRegularExpressionDelimiter but it does not seem to be required. It is even incorrect IMHO (please correct me if I'm wrong).

I did tests on a local build with our company's product OpenAPI spec file. All regular expressions seem to be correct now.

Compare
  • master (base)

and
  • latest version
    d4565483
    3 commits, 2 years ago

10 files
+ 89
- 10

    Preferences

    File browser
    Compare changes
modules/openap‎i-generator/src‎
main/java/org/…/‎codegen/languages‎
PythonAbstractConnex‎ionServerCodegen.java‎ +9 -0
test/reso‎urces/3_0‎
petsto‎re.yaml‎ +2 -0
sam‎ples‎
client/petstore-se‎curity-test/python‎
do‎cs‎
FakeA‎pi.md‎ +1 -0
petsto‎re_api‎
api_cl‎ient.py‎ +11 -5
configur‎ation.py‎ +52 -5
READ‎ME.md‎ +2 -0
server/opena‎pi3/petstore‎
python-flask-pyth‎on2/openapi_server‎
mod‎els‎
categ‎ory.py‎ +4 -0
ope‎napi‎
openap‎i.yaml‎ +2 -0
python-flask/‎openapi_server‎
mod‎els‎
categ‎ory.py‎ +4 -0
ope‎napi‎
openap‎i.yaml‎ +2 -0
modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAbstractConnexionServerCodegen.java
+ 9
- 0
  • View file @ d4565483

  • Edit in single-file editor

  • Open in Web IDE


@@ -908,4 +908,13 @@ public class PythonAbstractConnexionServerCodegen extends DefaultCodegen impleme
}
}
/*
* We don't want to run `escapeText` on the pattern
* but forward it directly to the Python implementation.
*/
@Override
public String toRegularExpression(String pattern) {
return addRegularExpressionDelimiter(pattern);
}
}
modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAbstractConnexionServerCodegen.java
+ 9
- 0
  • View file @ d4565483

  • Edit in single-file editor

  • Open in Web IDE


@@ -908,4 +908,13 @@ public class PythonAbstractConnexionServerCodegen extends DefaultCodegen impleme
}
}
/*
* We don't want to run `escapeText` on the pattern
* but forward it directly to the Python implementation.
*/
@Override
public String toRegularExpression(String pattern) {
return addRegularExpressionDelimiter(pattern);
}
}
modules/openapi-generator/src/test/resources/3_0/petstore.yaml
+ 2
- 0
  • View file @ d4565483

  • Edit in single-file editor

  • Open in Web IDE


@@ -419,6 +419,7 @@ paths:
required: true
schema:
type: string
pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$'
- name: password
in: query
description: The password for login in clear text
@@ -606,6 +607,7 @@ components:
format: int64
name:
type: string
pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$'
xml:
name: Category
User:
samples/client/petstore-security-test/python/docs/FakeApi.md
+ 1
- 0
  • View file @ d4565483

  • Edit in single-file editor

  • Open in Web IDE


@@ -15,6 +15,7 @@ To test code injection */ ' \" =end -- \\r\\n \\n \\r
To test code injection */ ' \" =end -- \\r\\n \\n \\r
### Example
```python
from __future__ import print_function
import time
samples/client/petstore-security-test/python/petstore_api/api_client.py
+ 11
- 5
  • View file @ d4565483

  • Edit in single-file editor

  • Open in Web IDE


@@ -110,7 +110,7 @@ class ApiClient(object):
query_params=None, header_params=None, body=None, post_params=None,
files=None, response_type=None, auth_settings=None,
_return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None):
_preload_content=True, _request_timeout=None, _host=None):
config = self.configuration
@@ -157,7 +157,11 @@ class ApiClient(object):
body = self.sanitize_for_serialization(body)
# request url
url = self.configuration.host + resource_path
if _host is None:
url = self.configuration.host + resource_path
else:
# use server/host defined in path or operation instead
url = _host + resource_path
# perform request and return response
response_data = self.request(
@@ -290,7 +294,7 @@ class ApiClient(object):
body=None, post_params=None, files=None,
response_type=None, auth_settings=None, async_req=None,
_return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None):
_preload_content=True, _request_timeout=None, _host=None):
"""Makes the HTTP request (synchronous) and returns deserialized data.
To make an async_req request, set the async_req parameter.
@@ -333,7 +337,7 @@ class ApiClient(object):
body, post_params, files,
response_type, auth_settings,
_return_http_data_only, collection_formats,
_preload_content, _request_timeout)
_preload_content, _request_timeout, _host)
else:
thread = self.pool.apply_async(self.__call_api, (resource_path,
method, path_params, query_params,
@@ -342,7 +346,9 @@ class ApiClient(object):
response_type, auth_settings,
_return_http_data_only,
collection_formats,
_preload_content, _request_timeout))
_preload_content,
_request_timeout,
_host))
return thread
def request(self, method, url, query_params=None, headers=None,
samples/client/petstore-security-test/python/petstore_api/configuration.py
+ 52
- 5
  • View file @ d4565483

  • Edit in single-file editor

  • Open in Web IDE


@@ -60,10 +60,8 @@ class Configuration(six.with_metaclass(TypeWithDefault, object)):
self.username = ""
# Password for HTTP basic authentication
self.password = ""
# access token for OAuth
# access token for OAuth/Bearer
self.access_token = ""
# Logging Settings
self.logger = {}
self.logger["package_logger"] = logging.getLogger("petstore_api")
@@ -223,7 +221,6 @@ class Configuration(six.with_metaclass(TypeWithDefault, object)):
'key': 'api_key */ ' " =end -- \r\n \n \r',
'value': self.get_api_key_with_prefix('api_key */ ' " =end -- \r\n \n \r')
},
'petstore_auth':
{
'type': 'oauth2',
@@ -231,7 +228,6 @@ class Configuration(six.with_metaclass(TypeWithDefault, object)):
'key': 'Authorization',
'value': 'Bearer ' + self.access_token
},
}
def to_debug_report(self):
@@ -245,3 +241,54 @@ class Configuration(six.with_metaclass(TypeWithDefault, object)):
"Version of the API: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r\n"\
"SDK Package Version: 1.0.0".\
format(env=sys.platform, pyversion=sys.version)
def get_host_settings(self):
"""Gets an array of host settings
:return: An array of host settings
"""
return [
{
'url': "//petstore.swagger.io */ ' " =end -- \r\n \n \r/v2 */ ' " =end -- \r\n \n \r",
'description': "No description provided",
}
]
def get_host_from_settings(self, index, variables={}):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value
:return: URL based on host settings
"""
servers = self.get_host_settings()
# check array index out of bound
if index < 0 or index >= len(servers):
raise ValueError(
"Invalid index {} when selecting the host settings. Must be less than {}" # noqa: E501
.format(index, len(servers)))
server = servers[index]
url = server['url']
# go through variable and assign a value
for variable_name in server['variables']:
if variable_name in variables:
if variables[variable_name] in server['variables'][
variable_name]['enum_values']:
url = url.replace("{" + variable_name + "}",
variables[variable_name])
else:
raise ValueError(
"The variable `{}` in the host URL has invalid value {}. Must be {}." # noqa: E501
.format(
variable_name, variables[variable_name],
server['variables'][variable_name]['enum_values']))
else:
# use default value
url = url.replace(
"{" + variable_name + "}",
server['variables'][variable_name]['default_value'])
return url
samples/client/petstore-security-test/python/README.md
+ 2
- 0
  • View file @ d4565483

  • Edit in single-file editor

  • Open in Web IDE


@@ -51,6 +51,7 @@ import petstore_api
from petstore_api.rest import ApiException
from pprint import pprint
# create an instance of the API class
api_instance = petstore_api.FakeApi(petstore_api.ApiClient(configuration))
test_code_inject____end____rn_n_r = 'test_code_inject____end____rn_n_r_example' # str | To test code injection */ ' \\\" =end -- \\\\r\\\\n \\\\n \\\\r (optional)
@@ -86,6 +87,7 @@ Class | Method | HTTP request | Description
- **API key parameter name**: api_key */ ' " =end -- \r\n \n \r
- **Location**: HTTP header
## petstore_auth
- **Type**: OAuth
samples/server/openapi3/petstore/python-flask/openapi_server/models/category.py
+ 4
- 0
  • View file @ d4565483

  • Edit in single-file editor

  • Open in Web IDE


@@ -6,8 +6,10 @@ from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from openapi_server.models.base_model_ import Model
import re
from openapi_server import util
import re # noqa: E501
class Category(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
@@ -86,5 +88,7 @@ class Category(Model):
:param name: The name of this Category.
:type name: str
"""
if name is not None and not re.search(r'^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$', name): # noqa: E501
raise ValueError("Invalid value for `name`, must be a follow pattern or equal to `/^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$/`") # noqa: E501
self._name = name
samples/server/openapi3/petstore/python-flask/openapi_server/openapi/openapi.yaml
+ 2
- 0
  • View file @ d4565483

  • Edit in single-file editor

  • Open in Web IDE


@@ -433,6 +433,7 @@ paths:
name: username
required: true
schema:
pattern: ^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$
type: string
style: form
- description: The password for login in clear text
@@ -641,6 +642,7 @@ components:
format: int64
type: integer
name:
pattern: ^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$
type: string
title: Pet category
type: object
samples/server/openapi3/petstore/python-flask-python2/openapi_server/models/category.py
+ 4
- 0
  • View file @ d4565483

  • Edit in single-file editor

  • Open in Web IDE


@@ -6,8 +6,10 @@ from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from openapi_server.models.base_model_ import Model
import re
from openapi_server import util
import re # noqa: E501
class Category(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
@@ -86,5 +88,7 @@ class Category(Model):
:param name: The name of this Category.
:type name: str
"""
if name is not None and not re.search(r'^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$', name): # noqa: E501
raise ValueError("Invalid value for `name`, must be a follow pattern or equal to `/^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$/`") # noqa: E501
self._name = name
samples/server/openapi3/petstore/python-flask-python2/openapi_server/openapi/openapi.yaml
+ 2
- 0
  • View file @ d4565483

  • Edit in single-file editor

  • Open in Web IDE


@@ -433,6 +433,7 @@ paths:
name: username
required: true
schema:
pattern: ^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$
type: string
style: form
- description: The password for login in clear text
@@ -641,6 +642,7 @@ components:
format: int64
type: integer
name:
pattern: ^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$
type: string
title: Pet category
type: object
0 Assignees
None
Assign to
0 Reviewers
None
Request review from
Labels
2
Issue: Bug Server: Python
2
Issue: Bug Server: Python
    Assign labels
  • Manage project labels

Milestone
4.0.0
4.0.0 (expired)
None
Time tracking
No estimate or time spent
Lock merge request
Unlocked
2
2 participants
Administrator
Tomasz Prus
Reference: OpenAPITools/openapi-generator!2314
Source branch: github/fork/tomghyselinck/python-connexion-regex

Menu

Explore Projects Groups Snippets