Skip to content
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

Updated type hinting #167

Merged
merged 2 commits into from
Sep 30, 2020
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
4 changes: 3 additions & 1 deletion pyms/config/resource.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from typing import Text

from pyms.config import get_conf


class ConfigResource:

config_resource = None
config_resource: Text = ""

def __init__(self, *args, **kwargs):
self.config = get_conf(service=self.config_resource, empty_init=True, uppercase=False, *args, **kwargs)
31 changes: 12 additions & 19 deletions pyms/flask/app/create_app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging
import os
from typing import Text
from typing import List

from flask import Flask

Expand All @@ -10,7 +10,7 @@
from pyms.crypt.driver import CryptResource
from pyms.flask.app.utils import SingletonMeta, ReverseProxied
from pyms.flask.healthcheck import healthcheck_blueprint
from pyms.flask.services.driver import ServicesResource
from pyms.flask.services.driver import ServicesResource, DriverService
from pyms.logger import CustomJsonFormatter
from pyms.utils import check_package_exists, import_from

Expand Down Expand Up @@ -72,11 +72,12 @@ def example():
Current services are swagger, request, tracer, metrics
"""
config_resource = CONFIG_BASE
services = []
application = None
swagger = False
request = False
tracer = False
services: List[DriverService] = []
application = Flask
swagger: DriverService = None
request: DriverService = None
tracer: DriverService = None
metrics: DriverService = None
_singleton = True

def __init__(self, *args, **kwargs):
Expand Down Expand Up @@ -137,7 +138,7 @@ def init_tracer(self) -> None:
"""Set attribute in flask `tracer`. See in `pyms.flask.services.tracer` how it works
:return: None
"""
if self._exists_service("tracer"):
if self.tracer:
FlaskTracing = import_from("flask_opentracing", "FlaskTracing")
client = self.tracer.get_client()
self.application.tracer = FlaskTracing(client, True, self.application)
Expand Down Expand Up @@ -169,7 +170,7 @@ def init_app(self) -> Flask:
run a "normal" Flask app.
:return: None
"""
if self._exists_service("swagger"):
if self.swagger:
application = self.swagger.init_app(config=self.config.to_flask(), path=self.path)
else:
check_package_exists("flask")
Expand All @@ -183,11 +184,11 @@ def init_app(self) -> Flask:

return application

def init_metrics(self):
def init_metrics(self) -> None:
"""Set attribute in flask `metrics`. See in `pyms.flask.services.metrics` how it works
:return: None
"""
if getattr(self, "metrics", False) and self.metrics:
if self.metrics:
self.application.register_blueprint(self.metrics.metrics_blueprint)
self.metrics.add_logger_handler(
self.application.logger,
Expand Down Expand Up @@ -231,14 +232,6 @@ def create_app(self):

return self.application

def _exists_service(self, service_name: Text) -> bool:
"""Check if service exists in the config.yml file
:param service_name:
:return: bool
"""
service = getattr(self, service_name, False)
return service and service is not None

def add_error_handlers(self):
"""Subclasses will override this method in order to add specific error handlers. This should be done with
calls to add_error_handler method.
Expand Down
5 changes: 4 additions & 1 deletion pyms/flask/app/utils.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from typing import Dict


class SingletonMeta(type):
"""
The Singleton class can be implemented in different ways in Python. Some
possible methods include: base class, decorator, metaclass. We will use the
metaclass because it is best suited for this purpose.
"""
_instances = {}
_instances: Dict[type, type] = {}
_singleton = True

def __call__(cls, *args, **kwargs):
Expand Down
4 changes: 2 additions & 2 deletions pyms/flask/services/driver.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging
from typing import Text, Tuple
from typing import Text, Tuple, Iterator

from pyms.config import ConfFile
from pyms.config.resource import ConfigResource
Expand Down Expand Up @@ -61,7 +61,7 @@ class ServicesResource(ConfigResource):
"""
config_resource = SERVICE_BASE

def get_services(self) -> Tuple[Text, DriverService]:
def get_services(self) -> Iterator[Tuple[Text, DriverService]]:
for k in self.config.__dict__.keys():
if k.islower() and not k.startswith("_"):
service = self.get_service(k)
Expand Down
3 changes: 2 additions & 1 deletion pyms/flask/services/metrics.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import time
import logging
from typing import Text

from flask import Blueprint, Response, request
from prometheus_client import Counter, Histogram, generate_latest
Expand Down Expand Up @@ -45,7 +46,7 @@ class Service(DriverService):
"""
Adds [Prometheus](https://prometheus.io/) metrics using the [Prometheus Client Library](https://github.com/prometheus/client_python).
"""
config_resource = "metrics"
config_resource: Text = "metrics"

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
Expand Down
1 change: 0 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
'requests>=2.24.0',
]
install_swagger_requires = [
'swagger-ui-bundle>=0.0.2',
'connexion[swagger-ui]>=2.7.0',
'swagger-ui-bundle>=0.0.6',
'semver>=2.10.1',
Expand Down
5 changes: 0 additions & 5 deletions tests/test_flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,6 @@ def test_swagger(self):
def test_exists_service(self):
self.assertTrue(isinstance(self.app.ms.swagger, DriverService))

def test_disabled_service(self):
with pytest.raises(AttributeError) as excinfo:
self.assertTrue(isinstance(self.app.ms.metrics, DriverService))
assert "'MyMicroservice' object has no attribute 'metrics'" in str(excinfo.value)

def test_reverse_proxy(self):
response = self.client.get('/my-proxy-path/ui/', headers={"X-Script-Name": "/my-proxy-path"})
self.assertEqual(200, response.status_code)
Expand Down