Skip to content

Use Black and isort for code formatting #368

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions .github/workflows/python-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -68,5 +68,31 @@ jobs:
with:
python-version: 3.9

- name: "Run static checks"
uses: pre-commit/[email protected]
- name: Get full Python version
id: full-python-version
run: echo ::set-output name=version::$(python -c "import sys; print('-'.join(str(v) for v in sys.version_info))")

- name: Bootstrap poetry
run: |
curl -sL https://raw.githubusercontent.com/python-poetry/poetry/master/install-poetry.py | python - -y
echo "$HOME/.local/bin" >> $GITHUB_PATH

- name: Configure poetry
run: poetry config virtualenvs.in-project true

- name: Set up cache
uses: actions/cache@v2
id: cache
with:
path: .venv
key: venv-${{ steps.full-python-version.outputs.version }}-${{ hashFiles('**/poetry.lock') }}

- name: Ensure cache is healthy
if: steps.cache.outputs.cache-hit == 'true'
run: timeout 10s poetry run pip --version || rm -rf .venv

- name: Install dependencies
run: poetry install

- name: Run static checks
run: poetry run pre-commit run -a
17 changes: 17 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,32 @@ repos:
- repo: meta
hooks:
- id: check-hooks-apply

- repo: https://github.com/asottile/pyupgrade
rev: v2.19.0
hooks:
- id: pyupgrade
args: ["--py36-plus"]

- repo: local
hooks:
- id: flynt
name: Convert to f-strings with flynt
entry: flynt
language: python
additional_dependencies: ['flynt==0.64']

- id: black
name: black
entry: black
language: system
require_serial: true
types: [python]

- id: isort
name: isort
entry: isort
args: ['--filter-files']
language: system
require_serial: true
types: [python]
12 changes: 6 additions & 6 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@

# -- Project information -----------------------------------------------------

project = 'openapi-core'
copyright = '2021, Artur Maciag'
author = 'Artur Maciag'
project = "openapi-core"
copyright = "2021, Artur Maciag"
author = "Artur Maciag"

# The full version, including alpha/beta/rc tags
release = openapi_core.__version__
Expand All @@ -40,20 +40,20 @@
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]


# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_theme = "sphinx_rtd_theme"

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
Expand Down
54 changes: 33 additions & 21 deletions openapi_core/__init__.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,44 @@
"""OpenAPI core module"""
from openapi_core.shortcuts import (
create_spec, validate_request, validate_response,
spec_validate_body, spec_validate_parameters, spec_validate_security,
spec_validate_data, spec_validate_headers,
)
from openapi_core.shortcuts import create_spec
from openapi_core.shortcuts import spec_validate_body
from openapi_core.shortcuts import spec_validate_data
from openapi_core.shortcuts import spec_validate_headers
from openapi_core.shortcuts import spec_validate_parameters
from openapi_core.shortcuts import spec_validate_security
from openapi_core.shortcuts import validate_request
from openapi_core.shortcuts import validate_response
from openapi_core.validation.request.validators import RequestBodyValidator
from openapi_core.validation.request.validators import (
RequestValidator,
RequestBodyValidator,
RequestParametersValidator,
RequestSecurityValidator,
)
from openapi_core.validation.request.validators import RequestSecurityValidator
from openapi_core.validation.request.validators import RequestValidator
from openapi_core.validation.response.validators import ResponseDataValidator
from openapi_core.validation.response.validators import (
ResponseValidator,
ResponseDataValidator,
ResponseHeadersValidator,
)
from openapi_core.validation.response.validators import ResponseValidator

__author__ = 'Artur Maciag'
__email__ = '[email protected]'
__version__ = '0.14.2'
__url__ = 'https://github.com/p1c2u/openapi-core'
__license__ = 'BSD 3-Clause License'
__author__ = "Artur Maciag"
__email__ = "[email protected]"
__version__ = "0.14.2"
__url__ = "https://github.com/p1c2u/openapi-core"
__license__ = "BSD 3-Clause License"

__all__ = [
'create_spec', 'validate_request', 'validate_response',
'spec_validate_body', 'spec_validate_parameters', 'spec_validate_security',
'spec_validate_data', 'spec_validate_headers',
'RequestValidator', 'ResponseValidator', 'RequestBodyValidator',
'RequestParametersValidator', 'RequestSecurityValidator',
'ResponseDataValidator', 'ResponseHeadersValidator',
"create_spec",
"validate_request",
"validate_response",
"spec_validate_body",
"spec_validate_parameters",
"spec_validate_security",
"spec_validate_data",
"spec_validate_headers",
"RequestValidator",
"ResponseValidator",
"RequestBodyValidator",
"RequestParametersValidator",
"RequestSecurityValidator",
"ResponseDataValidator",
"ResponseHeadersValidator",
]
11 changes: 3 additions & 8 deletions openapi_core/casting/schemas/casters.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@


class BaseSchemaCaster:

def __init__(self, schema):
self.schema = schema

Expand All @@ -17,7 +16,6 @@ def cast(self, value):


class CallableSchemaCaster(BaseSchemaCaster):

def __init__(self, schema, caster_callable):
super().__init__(schema)
self.caster_callable = caster_callable
Expand All @@ -26,30 +24,27 @@ def cast(self, value):
try:
return self.caster_callable(value)
except (ValueError, TypeError):
raise CastError(value, self.schema['type'])
raise CastError(value, self.schema["type"])


class DummyCaster(BaseSchemaCaster):

def cast(self, value):
return value


class ComplexCaster(BaseSchemaCaster):

def __init__(self, schema, casters_factory):
super().__init__(schema)
self.casters_factory = casters_factory


class ArrayCaster(ComplexCaster):

@property
def items_caster(self):
return self.casters_factory.create(self.schema / 'items')
return self.casters_factory.create(self.schema / "items")

def cast(self, value):
try:
return list(map(self.items_caster, value))
except (ValueError, TypeError):
raise CastError(value, self.schema['type'])
raise CastError(value, self.schema["type"])
1 change: 1 addition & 0 deletions openapi_core/casting/schemas/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
@dataclass
class CastError(OpenAPIError):
"""Schema cast operation error"""

value: str
type: str

Expand Down
20 changes: 11 additions & 9 deletions openapi_core/casting/schemas/factories.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,27 @@
from openapi_core.casting.schemas.casters import (
ArrayCaster, CallableSchemaCaster, DummyCaster,
)
from openapi_core.casting.schemas.casters import ArrayCaster
from openapi_core.casting.schemas.casters import CallableSchemaCaster
from openapi_core.casting.schemas.casters import DummyCaster
from openapi_core.casting.schemas.util import forcebool


class SchemaCastersFactory:

DUMMY_CASTERS = [
'string', 'object', 'any',
"string",
"object",
"any",
]
PRIMITIVE_CASTERS = {
'integer': int,
'number': float,
'boolean': forcebool,
"integer": int,
"number": float,
"boolean": forcebool,
}
COMPLEX_CASTERS = {
'array': ArrayCaster,
"array": ArrayCaster,
}

def create(self, schema):
schema_type = schema.getkey('type', 'any')
schema_type = schema.getkey("type", "any")

if schema_type in self.DUMMY_CASTERS:
return DummyCaster(schema)
Expand Down
6 changes: 4 additions & 2 deletions openapi_core/contrib/django/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
DjangoOpenAPIResponse = DjangoOpenAPIResponseFactory().create

__all__ = [
'DjangoOpenAPIRequestFactory', 'DjangoOpenAPIResponseFactory',
'DjangoOpenAPIRequest', 'DjangoOpenAPIResponse',
"DjangoOpenAPIRequestFactory",
"DjangoOpenAPIResponseFactory",
"DjangoOpenAPIRequest",
"DjangoOpenAPIResponse",
]
23 changes: 10 additions & 13 deletions openapi_core/contrib/django/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@

from openapi_core.exceptions import MissingRequiredParameter
from openapi_core.templating.media_types.exceptions import MediaTypeNotFound
from openapi_core.templating.paths.exceptions import (
ServerNotFound, OperationNotFound, PathNotFound,
)
from openapi_core.templating.paths.exceptions import OperationNotFound
from openapi_core.templating.paths.exceptions import PathNotFound
from openapi_core.templating.paths.exceptions import ServerNotFound
from openapi_core.validation.exceptions import InvalidSecurity


Expand All @@ -22,24 +22,21 @@ class DjangoOpenAPIErrorsHandler:

@classmethod
def handle(cls, errors, req, resp=None):
data_errors = [
cls.format_openapi_error(err)
for err in errors
]
data_errors = [cls.format_openapi_error(err) for err in errors]
data = {
'errors': data_errors,
"errors": data_errors,
}
data_error_max = max(data_errors, key=cls.get_error_status)
return JsonResponse(data, status=data_error_max['status'])
return JsonResponse(data, status=data_error_max["status"])

@classmethod
def format_openapi_error(cls, error):
return {
'title': str(error),
'status': cls.OPENAPI_ERROR_STATUS.get(error.__class__, 400),
'class': str(type(error)),
"title": str(error),
"status": cls.OPENAPI_ERROR_STATUS.get(error.__class__, 400),
"class": str(type(error)),
}

@classmethod
def get_error_status(cls, error):
return error['status']
return error["status"]
14 changes: 7 additions & 7 deletions openapi_core/contrib/django/middlewares.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@ class DjangoOpenAPIMiddleware:
def __init__(self, get_response):
self.get_response = get_response

if not hasattr(settings, 'OPENAPI_SPEC'):
if not hasattr(settings, "OPENAPI_SPEC"):
raise ImproperlyConfigured("OPENAPI_SPEC not defined in settings")

request_validator = RequestValidator(settings.OPENAPI_SPEC)
response_validator = ResponseValidator(settings.OPENAPI_SPEC)
self.validation_processor = OpenAPIProcessor(
request_validator, response_validator)
request_validator, response_validator
)

def __call__(self, request):
openapi_request = self._get_openapi_request(request)
Expand All @@ -38,19 +39,18 @@ def __call__(self, request):

openapi_response = self._get_openapi_response(response)
resp_result = self.validation_processor.process_response(
openapi_request, openapi_response)
openapi_request, openapi_response
)
if resp_result.errors:
return self._handle_response_errors(resp_result, request, response)

return response

def _handle_request_errors(self, request_result, req):
return self.errors_handler.handle(
request_result.errors, req, None)
return self.errors_handler.handle(request_result.errors, req, None)

def _handle_response_errors(self, response_result, req, resp):
return self.errors_handler.handle(
response_result.errors, req, resp)
return self.errors_handler.handle(response_result.errors, req, resp)

def _get_openapi_request(self, request):
return self.request_factory.create(request)
Expand Down
Loading