class Device(with_metaclass(ContractsMeta)): @contract def __init__(self, device_id: str, device_type: str, label=None): self._id = device_id self._type = device_type self._label = label @property def id(self) -> str: return self._id @property def type(self) -> str: return self._type @property def label(self) -> str: return self._label if self._label is not None else self.id @label.setter @contract def label(self, label: str): self._label = label @label.deleter def label(self): self._label = None
class Endpoint(with_metaclass(ContractsMeta)): @contract def __init__(self, name: str, path: str, request_type: RequestType, response_type: ResponseType): self._name = name self._path = path self._request_type = request_type self._response_type = response_type @property @contract def name(self) -> str: return self._name @property @contract def path(self) -> str: return self._path @property @contract def request_type(self) -> RequestType: return self._request_type @property @contract def response_type(self) -> ResponseType: return self._response_type @abc.abstractmethod @contract def handle(self, request: Request) -> Response: pass
class A(with_metaclass(ContractsMeta, object)): # inverse order @contract(a='>0') @abstractmethod def f(self, a): pass
class DeviceRepository(with_metaclass(ContractsMeta)): @contract def get_device(self, device_id: str) -> Device: pass @contract def get_devices(self) -> Iterable: pass
class MessageType(with_metaclass(ContractsMeta)): @contract def __init__(self, name: str): self._name = name @property @contract def name(self) -> str: return self._name
class A(with_metaclass(ContractsMeta, object)): @abstractmethod @contract(a='>0') def f(self, a): pass @contract(a='>0') @abstractmethod def g(self, a): pass
class EndpointRepository(with_metaclass(ContractsMeta)): def get_endpoint(self, endpoint_name: str) -> Optional[Endpoint]: endpoints = self.get_endpoints() for endpoint in endpoints: if endpoint_name == endpoint.name: return endpoint raise EndpointNotFound(endpoint_name, endpoints) @contract def get_endpoints(self) -> Iterable: pass
class SchemaProxy(with_metaclass(ContractsMeta)): """ Proxies JSON Schemas. JSON Schemas may require lazy-loading, because they are computed, for instance. """ def __init__(self): self._schemas = None def get_schema(self, schema_id: str) -> Optional[Dict]: if self._schemas is None: self._aggregate_schemas() # Normalize root schemas by appending empty fragments. if '#' not in schema_id: schema_id += '#' try: return self._schemas[schema_id] except KeyError: raise SchemaNotFound(schema_id, self._schemas) @contract def get_schemas(self) -> Dict: if self._schemas is None: self._aggregate_schemas() return self._schemas def _aggregate_schemas(self): self._schemas = {} for schema in App.current.services(tag='json_schema'): self._add_schema(schema) @contract def _add_schema(self, schema: Dict): cls = validator_for(schema) cls.check_schema(schema) assert 'id' in schema # Normalize root schemas by appending empty fragments. if '#' not in schema['id']: schema['id'] += '#' assert schema['id'] not in self._schemas self._schemas[schema['id']] = schema
class ResourceRepository(with_metaclass(ContractsMeta)): """ Allows internal data as to be retrieved through the REST-ful HTTP API. Register child classes as Extension services with the "resources" tag, and HTTP GET endpoints will be available automatically. """ @abc.abstractmethod def get_type(self) -> ResourceType: pass @abc.abstractmethod @contract def get_resource(self, resource_id: str): pass @abc.abstractmethod @contract def get_resources(self, ids=None, filters: Iterable = ()) -> Iterable: pass
class AbstractBase(with_metaclass(ContractsMeta, object)): _common_attributes = {'this': str, 'that': int} def __init__(self): """ Make sure the common attributes of IntegralsBase have been defined. """ for attr, attr_type in AbstractBase._common_attributes.items(): if not (hasattr(self, attr) and isinstance(getattr(self, attr), attr_type)): raise ClassAttributeContractNotRespected( "Attribute '{:s}' must be initialized with type '{:s}'.". format(attr, attr_type.__name__)) @abstractmethod @contract(returns='array[NxN](float64), N>10') def get_square_array(self): """ Compute overlap integrals for this molecule and basis set. < mu(1) | nu(1) > """ pass
class Extension(with_metaclass(ContractsMeta)): """ Extensions integrate share their functionality with the rest of the app. Shared functionality is achieved through services. These provide key functionality, and are instantiated once and re-used throughout the application. The .service_definitions property exposes each extension's services to the application. The following shortcut is available: - Any method decorated with Extension.service() will be exposed automatically. """ class service: class NamedServiceFactory: """ Wraps a decorated service factory. """ def __init__(self, factory, instance): self._factory = factory self._instance = instance def __call__(self, *args, **kwargs): return self._factory(self._instance, *args, **kwargs) def __str__(self): """ As __call__ just invokes the wrapped factory, name ourselves after it for easy debugging. :return: """ return str(self._factory) """ Decorates a method and marks it as a service definition. :return: """ def __init__(self, name: Optional[str] = None, tags: Optional[Iterable[str]] = None, weight: int = 0): self._name = name self._tags = tags if tags is not None else [] self._factory = None self._weight = weight def __call__(self, factory, *args, **kwargs): self._factory = factory return self def get_definition(self, instance): """ :param instance: The instance the factory method must be called on. :return: """ name = self._name if self._name is not None else self._factory.__name__.strip( '_') return ServiceDefinition(instance.name(), name, self.NamedServiceFactory( self._factory, instance), self._tags, weight=self._weight) def __init__(self): self._service_definitions = [] @staticmethod @abc.abstractmethod def name() -> str: pass @staticmethod def dependencies() -> Iterable: return [] @property @contract def service_definitions(self) -> Iterable: for name, attribute in self.__class__.__dict__.items(): if isinstance(attribute, self.service): yield attribute.get_definition(self)
class PayloadType(with_metaclass(ContractsMeta)): @abc.abstractmethod def get_content_types(self) -> Iterable[str]: pass
class Message(with_metaclass(ContractsMeta)): pass
class A(with_metaclass(ContractsMeta, object)): @classmethod @contract(a='>0') def f(cls, a): print('called A.f(%s)' % a) pass
class A(with_metaclass(ContractsMeta, object)): @staticmethod @contract(a='>0') def f(a): pass
class Rewriter(with_metaclass(ContractsMeta)): @abc.abstractmethod @contract def rewrite(self, schema: Dict) -> Dict: pass
class A(with_metaclass(ContractsMeta, object)): @contract(a='>0') @classmethod def f(cls, a): pass
class AbstractBase(with_metaclass(AttributeContractMeta, object)): _common_attributes = {'this': str, 'that': int} def _check_common_attributes(self): check_common_attributes(self, AbstractBase._common_attributes)