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

WIP: Upgrade injector #128

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
14 changes: 14 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,20 @@
"tests/application/version_test.py"
]
},
{
"name": "Test: tests/resource/transactional_guard_test.py",
"type": "python",
"request": "launch",
"module": "pytest",
"env": {
"PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}/tests"
},
"args": [
"--capture=sys",
"--log-cli-level=DEBUG",
"tests/resource/transactional_guard_test.py"
]
},
{
"name": "Test: all",
"type": "python",
Expand Down
5 changes: 2 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ click>=7.0
enum34
future
Flask>=1.1
injector==0.12.1
injector>=0.18
redis>=3.2
requests>=2.22
SQLAlchemy>=1.3,<1.4
tox
typing>=3.7
Werkzeug>=0.16,<0.17
Werkzeug>=0.16
zsl_client
pytest
3 changes: 1 addition & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@
requirements = [
'flask>=1.1,<1.2',
'future',
'injector==0.12.1',
'injector==0.18.4',
'requests>=2.22',
'SQLAlchemy>=1.3,<1.4',
'typing>=3.7',
'Werkzeug>=0.15,<0.17',
]

Expand Down
5 changes: 0 additions & 5 deletions src/zsl/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@

.. moduleauthor:: Martin Babka <[email protected]>
"""
from __future__ import unicode_literals

from flask import Config
from injector import Module

Expand All @@ -24,9 +22,6 @@

Zsl = ServiceApplication

# placeholder for default value used in function declaration for arguments which will be injected
Injected = None

# just for autocomplete in various IDEs
inject = inject
Config = Config
Expand Down
2 changes: 0 additions & 2 deletions src/zsl/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

Main service module.
"""
from __future__ import unicode_literals

from zsl.interface.cli import cli

if __name__ == "__main__":
Expand Down
1 change: 0 additions & 1 deletion src/zsl/application/containers/celery_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
:mod:`zsl.application.containers.celery_container`
--------------------------------------------------
"""
from __future__ import unicode_literals

from zsl.application.containers.core_container import CoreContainer
from zsl.application.modules.celery_module import (CeleryCliModule, CeleryTaskQueueMainWorkerModule,
Expand Down
4 changes: 1 addition & 3 deletions src/zsl/application/containers/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@
:mod:`zsl.application.containers.container`
-------------------------------------------
"""
from __future__ import unicode_literals

import inspect


class IoCContainer(object):
class IoCContainer:
"""Collection of DI modules set as class attributes.

This is used for declarative DI configuration, which can be easily
Expand Down
2 changes: 0 additions & 2 deletions src/zsl/application/containers/core_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
:mod:`zsl.application.containers.core_container`
------------------------------------------------
"""
from __future__ import unicode_literals

from zsl.application.containers.container import IoCContainer
from zsl.application.modules.alchemy_module import AlchemyModule
from zsl.application.modules.cache_module import RedisCacheInjectionModule
Expand Down
1 change: 0 additions & 1 deletion src/zsl/application/containers/gearman_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
:mod:`zsl.application.containers.gearman_container`
---------------------------------------------------
"""
from __future__ import unicode_literals

from zsl.application.containers.core_container import CoreContainer
from zsl.application.modules.gearman_module import GearmanModule
Expand Down
2 changes: 0 additions & 2 deletions src/zsl/application/containers/web_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
:mod:`zsl.application.containers.web_container`
-----------------------------------------------
"""
from __future__ import unicode_literals

from zsl.application.containers.core_container import CoreContainer
from zsl.application.modules.web.web_context_module import WebContextModule

Expand Down
16 changes: 6 additions & 10 deletions src/zsl/application/error_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@
an error handler for a given exception type. It also provides default
error handlers.
"""
from __future__ import absolute_import, division, print_function, unicode_literals

from builtins import *
from functools import wraps
import http.client
import logging
Expand All @@ -30,7 +27,7 @@

class ErrorResponse(AppModel):
def __init__(self, code, message):
super(ErrorResponse, self).__init__({})
super().__init__({})
self.code = code
self.message = message

Expand All @@ -54,11 +51,11 @@ def can_handle(self, e):
def handle(self, ex):
logger = logging.getLogger(__name__)
logger.error(str(ex) + "\n" + traceback.format_exc())
logger.error("Request:\n{0}\n{1}\n".format(request.headers,
request.data))
logger.error("Request:\n{}\n{}\n".format(request.headers,
request.data))
link = documentation_link('error_handling')
logger.info("Provide your own error handler so that "
"a better error is produced, check {0}.".format(link))
"a better error is produced, check {}.".format(link))

add_responder(StatusCodeResponder(http.client.INTERNAL_SERVER_ERROR))
return ErrorResponse(self.ERROR_CODE, self.ERROR_MESSAGE)
Expand Down Expand Up @@ -122,9 +119,8 @@ def error_handler(f):

@wraps(f)
def error_handling_function(*args, **kwargs):
@inject(error_config=ErrorConfiguration)
def get_error_configuration(error_config):
# type:(ErrorConfiguration)->ErrorConfiguration
@inject
def get_error_configuration(error_config: ErrorConfiguration) -> ErrorConfiguration:
return error_config

def should_skip_handling():
Expand Down
9 changes: 5 additions & 4 deletions src/zsl/application/initialization_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,20 @@

.. moduleauthor:: Martin Babka
"""
from __future__ import unicode_literals
from typing import Any, List


class InitializationContext(object):
def __init__(self, unit_test=False, initializers=None):
class InitializationContext:

def __init__(self, unit_test: bool = False, initializers: List[Any] = None):
if not initializers:
initializers = []

self._unit_test = unit_test
self._initializers = initializers
self._is_initialized = False

def get_unit_testing(self):
def get_unit_testing(self) -> bool:
return self._unit_test

unit_testing = property(get_unit_testing)
Expand Down
13 changes: 6 additions & 7 deletions src/zsl/application/initializers/library_initializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@
:mod:`zsl.application.initializers.library_initializer`
-------------------------------------------------------
"""
from __future__ import unicode_literals

from builtins import object
import logging
import os
import sys
Expand All @@ -19,11 +16,13 @@ def append_paths(path, vendor_modules):
sys.path = new_path + sys.path


class LibraryInitializer(object):
class LibraryInitializer:
# TODO: Change to iface

"""Add vendor modules to current path."""
@staticmethod
@inject(config=Config)
def initialize(config):
@inject
def initialize(config: Config) -> None:
logging.debug("Initializing project external libraries.")

external_libraries = config.get('EXTERNAL_LIBRARIES', None)
Expand All @@ -33,5 +32,5 @@ def initialize(config):
vendor_path = external_libraries['vendor_path']
append_paths(vendor_path, external_libraries['libs'])

logging.info("Current PYTHON_PATH={0}.".format(sys.path))
logging.info("Current PYTHON_PATH={}.".format(sys.path))
logging.debug("Project external libraries initialized.")
25 changes: 12 additions & 13 deletions src/zsl/application/initializers/service_initializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,29 @@
:mod:`zsl.application.initializers.service_initializer`
-------------------------------------------------------
"""
from __future__ import unicode_literals

from builtins import object
import importlib
import logging

from injector import Binder, singleton

from zsl import Config, Injected, inject
from zsl import Config, inject
from zsl.utils.string_helper import camelcase_to_underscore


class ServiceInitializer(object):
class ServiceInitializer:
# TODO: change to iface

"""Add outside services to application injector."""
@staticmethod
@inject(binder=Binder)
def _bind_service(package_name, cls_name, binder=Injected):
@inject
def _bind_service(package_name: str, cls_name: str, binder: Binder) -> None:
"""Bind service to application injector.

:param package_name: service package
:type package_name: str
:param cls_name: service class
:type cls_name: str
:param binder: current application binder, injected
:param binder: current application binder
:type binder: Binder
"""
module = importlib.import_module(package_name)
Expand All @@ -36,14 +35,14 @@ def _bind_service(package_name, cls_name, binder=Injected):
to=binder.injector.create_object(cls),
scope=singleton
)
logging.debug("Created {0} binding.".format(cls))
logging.debug("Created {} binding.".format(cls))

@staticmethod
@inject(config=Config)
def initialize(config):
@inject
def initialize(config: Config) -> None:
"""Initialize method.

:param config: current application config, injected
:param config: current application config
:type config: Config
"""
service_injection_config = config.get('SERVICE_INJECTION', ())
Expand All @@ -61,5 +60,5 @@ def initialize(config):

for cls_name in services:
module_name = camelcase_to_underscore(cls_name)
package_name = "{0}.{1}".format(service_package, module_name)
package_name = "{}.{}".format(service_package, module_name)
ServiceInitializer._bind_service(package_name, cls_name)
16 changes: 7 additions & 9 deletions src/zsl/application/initializers/unittest_initializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@
:mod:`zsl.application.initializers.unittest_initializer`
--------------------------------------------------------
"""
from __future__ import unicode_literals

from builtins import object

from zsl import ApplicationContext, Config, inject


class UnitTestInitializer(object):
class UnitTestInitializer:
# TODO: Change to iface

"""Initializer handling the unit test settings."""
@staticmethod
@inject(config=Config)
def initialize(config):
@inject
def initialize(config: Config) -> None:

if not UnitTestInitializer.is_unit_testing():
return
Expand All @@ -26,6 +24,6 @@ def initialize(config):
'TEST_DATABASE_ENGINE_PROPS']

@staticmethod
@inject(ctx=ApplicationContext)
def is_unit_testing(ctx):
@inject
def is_unit_testing(ctx: ApplicationContext) -> bool:
return ctx.unit_testing
Loading