openapi-core/openapi_core/schema/specs/models.py

69 lines
2.1 KiB
Python
Raw Normal View History

2018-04-17 12:18:40 +00:00
# -*- coding: utf-8 -*-
"""OpenAPI core specs models module"""
import logging
2018-07-28 22:51:36 +00:00
from openapi_core.compat import partialmethod
2018-04-18 10:39:03 +00:00
from openapi_core.schema.operations.exceptions import InvalidOperation
2019-06-18 15:13:44 +00:00
from openapi_core.schema.paths.exceptions import InvalidPath
2018-04-18 10:39:03 +00:00
from openapi_core.schema.servers.exceptions import InvalidServer
2018-04-17 12:18:40 +00:00
log = logging.getLogger(__name__)
class Spec(object):
"""Represents an OpenAPI Specification for a service."""
2020-01-17 14:36:14 +00:00
def __init__(
self, info, paths, servers=None, components=None,
security=None, _resolver=None):
2018-04-17 12:18:40 +00:00
self.info = info
self.paths = paths and dict(paths)
self.servers = servers or []
self.components = components
self.security = security
2018-04-17 12:18:40 +00:00
2019-09-03 00:38:19 +00:00
self._resolver = _resolver
2019-06-18 15:13:44 +00:00
def __getitem__(self, path_pattern):
return self.get_path(path_pattern)
2018-04-17 12:18:40 +00:00
@property
def default_url(self):
return self.servers[0].default_url
def get_server(self, full_url_pattern):
for spec_server in self.servers:
if spec_server.default_url in full_url_pattern:
return spec_server
raise InvalidServer(full_url_pattern)
2018-04-17 12:18:40 +00:00
def get_server_url(self, index=0):
return self.servers[index].default_url
2019-06-18 15:13:44 +00:00
def get_path(self, path_pattern):
try:
return self.paths[path_pattern]
except KeyError:
raise InvalidPath(path_pattern)
2018-04-17 12:18:40 +00:00
def get_operation(self, path_pattern, http_method):
try:
return self.paths[path_pattern].operations[http_method]
except KeyError:
raise InvalidOperation(path_pattern, http_method)
2018-04-17 12:18:40 +00:00
def get_schema(self, name):
return self.components.schemas[name]
# operations shortcuts
get = partialmethod(get_operation, http_method='get')
put = partialmethod(get_operation, http_method='put')
post = partialmethod(get_operation, http_method='post')
delete = partialmethod(get_operation, http_method='delete')
options = partialmethod(get_operation, http_method='options')
head = partialmethod(get_operation, http_method='head')
patch = partialmethod(get_operation, http_method='patch')