Fixed "has_key" and other issues

This commit is contained in:
Adolfo Gómez García 2019-09-24 10:02:05 +02:00
parent 917dd33349
commit a06fc617f0
9 changed files with 31 additions and 36 deletions

View File

@ -111,7 +111,7 @@ class Module(UserInterface, Environmentable, Serializable):
iconFile: typing.ClassVar[str] = 'base.png' # This is expected to be png, use this format always iconFile: typing.ClassVar[str] = 'base.png' # This is expected to be png, use this format always
# Not defined, but declared. If module is groupable, this value will contain to which group belongs # Not defined, but declared. If module is groupable, this value will contain to which group belongs
group: str group: typing.ClassVar[str]
class ValidationException(Exception): class ValidationException(Exception):
""" """

View File

@ -146,7 +146,7 @@ class ServiceProvider(Module):
return _type return _type
return None return None
def __init__(self, environment: Environment, values: Module.ValuesType = None, uuid: typing.Optional[str] = None): def __init__(self, environment: Environment, values: 'Module.ValuesType' = None, uuid: typing.Optional[str] = None):
""" """
Do not forget to invoke this in your derived class using "super(self.__class__, self).__init__(environment, values)" Do not forget to invoke this in your derived class using "super(self.__class__, self).__init__(environment, values)"
if you override this method. Better is to provide an "__initialize__" method, that will be invoked if you override this method. Better is to provide an "__initialize__" method, that will be invoked
@ -157,7 +157,7 @@ class ServiceProvider(Module):
super().__init__(environment, values, uuid=uuid) super().__init__(environment, values, uuid=uuid)
self.initialize(values) self.initialize(values)
def initialize(self, values: typing.Optional[Module.ValuesType]) -> None: def initialize(self, values: 'Module.ValuesType') -> None:
""" """
This method will be invoked from __init__ constructor. This method will be invoked from __init__ constructor.
This is provided so you don't have to provide your own __init__ method, This is provided so you don't have to provide your own __init__ method,

View File

@ -31,9 +31,9 @@
@author: Adolfo Gómez, dkmaster at dkmon dot com @author: Adolfo Gómez, dkmaster at dkmon dot com
""" """
from functools import wraps from functools import wraps
import typing
import logging import logging
import inspect import inspect
import typing
from uds.core.util.html import checkBrowser from uds.core.util.html import checkBrowser
from uds.web.util import errors from uds.web.util import errors
@ -41,29 +41,28 @@ from uds.web.util import errors
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
RT = typing.TypeVar('RT')
# Decorator that protects pages that needs at least a browser version # Decorator that protects pages that needs at least a browser version
# Default is to deny IE < 9 # Default is to deny IE < 9
def denyBrowsers( def denyBrowsers(
browsers: typing.Optional[typing.List[str]] = None, browsers: typing.Optional[typing.List[str]] = None,
errorResponse: typing.Callable = lambda request: errors.errorView(request, errors.BROWSER_NOT_SUPPORTED) errorResponse: typing.Callable = lambda request: errors.errorView(request, errors.BROWSER_NOT_SUPPORTED)
): ) -> typing.Callable[[typing.Callable[..., RT]], typing.Callable[..., RT]]:
""" """
Decorator to set protection to access page Decorator to set protection to access page
Look for samples at uds.core.web.views Look for samples at uds.core.web.views
""" """
if browsers is None: denied: typing.List[str] = browsers or ['ie<9']
browsers = ['ie<9']
def wrap(view_func):
def wrap(view_func: typing.Callable[..., RT]) -> typing.Callable[..., RT]:
@wraps(view_func) @wraps(view_func)
def _wrapped_view(request, *args, **kwargs): def _wrapped_view(request, *args, **kwargs) -> RT:
""" """
Wrapped function for decorator Wrapped function for decorator
""" """
for b in browsers: for b in denied:
if checkBrowser(request, b): if checkBrowser(request, b):
return errorResponse(request) return errorResponse(request)
@ -74,13 +73,13 @@ def denyBrowsers(
return wrap return wrap
def deprecated(func): def deprecated(func: typing.Callable[..., RT]) -> typing.Callable[..., RT]:
"""This is a decorator which can be used to mark functions """This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted as deprecated. It will result in a warning being emitted
when the function is used.""" when the function is used."""
@wraps(func) @wraps(func)
def new_func(*args, **kwargs): def new_func(*args, **kwargs) -> RT:
try: try:
caller = inspect.stack()[1] caller = inspect.stack()[1]
logger.warning('Call to deprecated function %s from %s:%s.', func.__name__, caller[1], caller[2]) logger.warning('Call to deprecated function %s from %s:%s.', func.__name__, caller[1], caller[2])
@ -101,7 +100,7 @@ def allowCache(
cacheTimeout: int, cacheTimeout: int,
cachingArgs: typing.Optional[typing.Union[typing.List[int], int]] = None, cachingArgs: typing.Optional[typing.Union[typing.List[int], int]] = None,
cachingKeyFnc: typing.Optional[typing.Callable[[typing.Any], str]] = None cachingKeyFnc: typing.Optional[typing.Callable[[typing.Any], str]] = None
): ) -> typing.Callable[[typing.Callable[..., RT]], typing.Callable[..., RT]]:
"""Decorator that give us a "quick& clean" caching feature on service providers. """Decorator that give us a "quick& clean" caching feature on service providers.
Note: This decorator is intended ONLY for service providers Note: This decorator is intended ONLY for service providers
@ -111,30 +110,29 @@ def allowCache(
:param cachingArgs: The caching args. Can be a single integer or a list. :param cachingArgs: The caching args. Can be a single integer or a list.
First arg (self) is 0, so normally cachingArgs are 1, or [1,2,..] First arg (self) is 0, so normally cachingArgs are 1, or [1,2,..]
""" """
if not cachingKeyFnc: keyFnc = cachingKeyFnc or (lambda x: '')
cachingKeyFnc = lambda x: ''
def allowCacheDecorator(fnc: typing.Callable): def allowCacheDecorator(fnc: typing.Callable[..., RT]) -> typing.Callable[..., RT]:
@wraps(fnc) @wraps(fnc)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs) -> RT:
if cachingArgs is not None: if cachingArgs:
if isinstance(cachingArgs, (list, tuple)): if isinstance(cachingArgs, (list, tuple)):
argList = [args[i] if i < len(args) else '' for i in cachingArgs] argList = [args[i] if i < len(args) else '' for i in cachingArgs]
else: else:
argList = args[cachingArgs] if cachingArgs < len(args) else '' argList = args[cachingArgs] if cachingArgs < len(args) else ''
cacheKey = '{}-{}.{}'.format(cachePrefix, cachingKeyFnc(args[0]), argList) cacheKey = '{}-{}.{}'.format(cachePrefix, keyFnc(args[0]), argList)
else: else:
cacheKey = '{}-{}.gen'.format(cachePrefix, cachingKeyFnc(args[0])) cacheKey = '{}-{}.gen'.format(cachePrefix, keyFnc(args[0]))
data = None data: typing.Any = None
if kwargs.get('force', False) is False and args[0].cache is not None: if kwargs.get('force', False) is False and args[0].cache is not None:
data = args[0].cache.get(cacheKey) data = args[0].cache.get(cacheKey)
if kwargs.has_key('force'): if 'force' in kwargs:
# Remove force key # Remove force key
del kwargs['force'] del kwargs['force']
if data is None: if data is None: # Not in cache...
data = fnc(*args, **kwargs) data = fnc(*args, **kwargs)
try: try:
# Maybe returned data is not serializable. In that case, cache will fail but no harm is done with this # Maybe returned data is not serializable. In that case, cache will fail but no harm is done with this

View File

@ -85,9 +85,6 @@ class CaseInsensitiveDict(dict):
def __contains__(self, key): def __contains__(self, key):
return super(CaseInsensitiveDict, self).__contains__(self.__class__._k(key)) return super(CaseInsensitiveDict, self).__contains__(self.__class__._k(key))
def has_key(self, key):
return super(CaseInsensitiveDict, self).has_key(self.__class__._k(key))
def pop(self, key, *args, **kwargs): def pop(self, key, *args, **kwargs):
return super(CaseInsensitiveDict, self).pop(self.__class__._k(key), *args, **kwargs) return super(CaseInsensitiveDict, self).pop(self.__class__._k(key), *args, **kwargs)

View File

@ -179,11 +179,12 @@ class Client: # pylint: disable=too-many-public-methods
self._authUrl += '/' self._authUrl += '/'
def _getEndpointFor(self, type_: str) -> str: # If no region is indicatad, first endpoint is returned def _getEndpointFor(self, type_: str) -> str: # If no region is indicatad, first endpoint is returned
for i in self._catalog: if not self._catalog:
if i['type'] == type_: raise Exception('No catalog for endpoints')
for j in i['endpoints']: for i in filter(lambda v: v['type'] == type_, self._catalog):
if j['interface'] == self._access and (self._region is None or j['region'] == self._region): for j in filter(lambda v: v['interface'] == self._access, i['endpoints']):
return j['url'] if not self._region or j['region'] == self._region:
return j['url']
raise Exception('No endpoint url found') raise Exception('No endpoint url found')
def _requestHeaders(self) -> typing.Dict[str, str]: def _requestHeaders(self) -> typing.Dict[str, str]:

File diff suppressed because one or more lines are too long

View File

@ -92,6 +92,6 @@
</svg> </svg>
</div> </div>
</uds-root> </uds-root>
<script src="/uds/res/admin/runtime.js?stamp=1568977772"></script><script src="/uds/res/admin/polyfills-es5.js?stamp=1568977772" nomodule></script><script src="/uds/res/admin/polyfills.js?stamp=1568977772"></script><script src="/uds/res/admin/main.js?stamp=1568977772"></script></body> <script src="/uds/res/admin/runtime.js?stamp=1569311997"></script><script src="/uds/res/admin/polyfills-es5.js?stamp=1569311997" nomodule></script><script src="/uds/res/admin/polyfills.js?stamp=1569311997"></script><script src="/uds/res/admin/main.js?stamp=1569311997"></script></body>
</html> </html>

View File

@ -35,7 +35,6 @@ import typing
from django.utils.translation import ugettext_noop as _ from django.utils.translation import ugettext_noop as _
from uds.core.util import os_detector as OsDetector from uds.core.util import os_detector as OsDetector
from uds.core.util import tools
from .x2go_base import BaseX2GOTransport from .x2go_base import BaseX2GOTransport
from . import x2go_file from . import x2go_file

View File

@ -61,7 +61,7 @@ ERR_USER_SERVICE_NOT_FOUND = 7
AUTHENTICATOR_NOT_FOUND = 8 AUTHENTICATOR_NOT_FOUND = 8
INVALID_CALLBACK = 9 INVALID_CALLBACK = 9
INVALID_REQUEST = 10 INVALID_REQUEST = 10
BROWSER_NOT_SUPPORTED = 11, BROWSER_NOT_SUPPORTED = 11
SERVICE_IN_MAINTENANCE = 12 SERVICE_IN_MAINTENANCE = 12
SERVICE_NOT_READY = 13 SERVICE_NOT_READY = 13
SERVICE_IN_PREPARATION = 14 SERVICE_IN_PREPARATION = 14