Fixed REST services_pools for python 3.x

This commit is contained in:
Adolfo Gómez García 2019-09-12 13:38:43 +02:00
parent 7f9b4c9274
commit f43a8a3bf4
8 changed files with 61 additions and 59 deletions

View File

@ -204,7 +204,7 @@ class MetaPools(ModelHandler):
def getFallbackAccess(self, item: MetaPool):
return item.fallbackAccess
# Returns the action list based on current element, for calendars (nothing right now for metapools)
# Returns the action list based on current element, for calendars (nothing right now for metapools, because no actions are allowed)
def actionsList(self, item: MetaPool):
validActions = ()
return validActions

View File

@ -52,8 +52,8 @@ from uds.core.ui.images import DEFAULT_THUMB_BASE64
from uds.core.util.state import State
from uds.core.util.model import processUuid
from uds.core.util import log
from uds.core.util import permissions
from uds.core.ui import gui
from uds.core.util import permissions
from uds.REST.model import ModelHandler
from uds.REST import RequestError, ResponseError
@ -111,13 +111,13 @@ class ServicesPools(ModelHandler):
summary = 'summarize' in self._params
# if item does not have an associated service, hide it (the case, for example, for a removed service)
# Access from dict will raise an exception, and item will be skipped
poolGroupId = None
poolGroupName = _('Default')
poolGroupThumb = DEFAULT_THUMB_BASE64
if item.servicesPoolGroup is not None:
poolGroupId: typing.Optional[str] = None
poolGroupName: str = _('Default')
poolGroupThumb: str = DEFAULT_THUMB_BASE64
if item.servicesPoolGroup:
poolGroupId = item.servicesPoolGroup.uuid
poolGroupName = item.servicesPoolGroup.name
if item.servicesPoolGroup.image is not None:
if item.servicesPoolGroup.image:
poolGroupThumb = item.servicesPoolGroup.image.thumb64
state = item.state
@ -191,8 +191,8 @@ class ServicesPools(ModelHandler):
# Gui related
def getGui(self, type_: str) -> typing.List[typing.Any]:
if OSManager.objects.count() < 1: # No os managers, can't create db
raise ResponseError(ugettext('Create at least one OS Manager before creating a new service pool'))
# if OSManager.objects.count() < 1: # No os managers, can't create db
# raise ResponseError(ugettext('Create at least one OS Manager before creating a new service pool'))
if Service.objects.count() < 1:
raise ResponseError(ugettext('Create at least a service before creating a new service pool'))
@ -319,7 +319,7 @@ class ServicesPools(ModelHandler):
return g
def beforeSave(self, fields: typing.Dict[str, typing.Any]) -> None:
def beforeSave(self, fields: typing.Dict[str, typing.Any]) -> None: # pylint: disable=too-many-branches,too-many-statements
# logger.debug(self._params)
try:
try:
@ -400,14 +400,14 @@ class ServicesPools(ModelHandler):
except Exception as e:
raise RequestError(str(e))
def afterSave(self, item):
def afterSave(self, item: ServicePool) -> None:
if self._params.get('publish_on_save', False) is True:
try:
item.publish()
except Exception:
pass
def deleteItem(self, item):
def deleteItem(self, item: ServicePool) -> None:
try:
logger.debug('Deleting %s', item)
item.remove() # This will mark it for deletion, but in fact will not delete it directly
@ -416,14 +416,14 @@ class ServicesPools(ModelHandler):
logger.exception('deleting service pool')
# Logs
def getLogs(self, item):
def getLogs(self, item: ServicePool) -> typing.List[typing.Dict]:
try:
return log.getLogs(item)
except Exception:
return []
# Set fallback status
def setFallbackAccess(self, item):
def setFallbackAccess(self, item: ServicePool):
self.ensureAccess(item, permissions.PERMISSION_MANAGEMENT)
fallback = self._params.get('fallbackAccess')
@ -433,12 +433,12 @@ class ServicesPools(ModelHandler):
item.save()
return item.fallbackAccess
def getFallbackAccess(self, item):
def getFallbackAccess(self, item: ServicePool):
return item.fallbackAccess
# Returns the action list based on current element, for calendar
def actionsList(self, item):
validActions = ()
def actionsList(self, item: ServicePool):
validActions: typing.Tuple[typing.Dict, ...] = ()
itemInfo = item.service.getType()
if itemInfo.usesCache is True:
validActions += (CALENDAR_ACTION_INITIAL, CALENDAR_ACTION_CACHE_L1, CALENDAR_ACTION_MAX)

View File

@ -182,7 +182,7 @@ class BaseModelHandler(Handler):
return gui
def ensureAccess(self, obj: typing.Any, permission: int, root=False) -> int:
def ensureAccess(self, obj: models.Model, permission: int, root: bool = False) -> int:
perm = permissions.getEffectivePermission(self._user, obj, root)
if perm < permission:
raise self.accessDenied()
@ -967,7 +967,7 @@ class ModelHandler(BaseModelHandler):
return res
def delete(self):
def delete(self) -> str:
"""
Processes a DELETE request
"""
@ -989,7 +989,7 @@ class ModelHandler(BaseModelHandler):
return OK
def deleteItem(self, item: models.Model):
def deleteItem(self, item: models.Model) -> None:
"""
Basic, overridable method for deleting an item
"""

View File

@ -32,33 +32,32 @@
import logging
import typing
from uds.models import (
UserService, ServicePoolPublication,
ServicePool, Service,
Provider, User,
Group, Authenticator,
MetaPool
)
from uds import models
from uds.core.util import log
from uds.core.util.config import GlobalConfig
# Not imported at runtime, just for type checking
if typing.TYPE_CHECKING:
from django.db.models import Model
logger = logging.getLogger(__name__)
OT_USERSERVICE, OT_PUBLICATION, OT_DEPLOYED_SERVICE, OT_SERVICE, OT_PROVIDER, OT_USER, OT_GROUP, OT_AUTHENTICATOR, OT_METAPOOL = range(9) # @UndefinedVariable
# Dict for translations
transDict = {
UserService: OT_USERSERVICE,
ServicePoolPublication: OT_PUBLICATION,
ServicePool: OT_DEPLOYED_SERVICE,
Service: OT_SERVICE,
Provider: OT_PROVIDER,
User: OT_USER,
Group: OT_GROUP,
Authenticator: OT_AUTHENTICATOR,
MetaPool: OT_METAPOOL,
transDict: typing.Dict['Model', int] = {
models.UserService: OT_USERSERVICE,
models.ServicePoolPublication: OT_PUBLICATION,
models.ServicePool: OT_DEPLOYED_SERVICE,
models.Service: OT_SERVICE,
models.Provider: OT_PROVIDER,
models.User: OT_USER,
models.Group: OT_GROUP,
models.Authenticator: OT_AUTHENTICATOR,
models.MetaPool: OT_METAPOOL,
}
@ -72,7 +71,7 @@ class LogManager:
pass
@staticmethod
def manager():
def manager() -> 'LogManager':
if not LogManager._manager:
LogManager._manager = LogManager()
return LogManager._manager
@ -126,7 +125,7 @@ class LogManager:
Log.objects.filter(owner_id=owner_id, owner_type=owner_type).delete()
def doLog(self, wichObject: typing.Any, level: typing.Union[int, str], message: str, source: str, avoidDuplicates: bool = True):
def doLog(self, wichObject: 'Model', level: typing.Union[int, str], message: str, source: str, avoidDuplicates: bool = True):
"""
Do the logging for the requested object.
@ -141,7 +140,7 @@ class LogManager:
else:
logger.debug('Requested doLog for a type of object not covered: %s', wichObject)
def getLogs(self, wichObject: typing.Any, limit: int) -> typing.List[typing.Dict]:
def getLogs(self, wichObject: 'Model', limit: int) -> typing.List[typing.Dict]:
"""
Get the logs associated with "wichObject", limiting to "limit" (default is GlobalConfig.MAX_LOGS_PER_ELEMENT)
"""
@ -155,7 +154,7 @@ class LogManager:
logger.debug('Requested getLogs for a type of object not covered: %s', wichObject)
return []
def clearLogs(self, wichObject: typing.Any):
def clearLogs(self, wichObject: Model):
"""
Clears all logs related to wichObject
@ -163,7 +162,7 @@ class LogManager:
"""
owner_type = transDict.get(type(wichObject), None)
if owner_type is not None:
if owner_type:
self.__clearLogs(owner_type, wichObject.id)
else:
logger.debug('Requested clearLogs for a type of object not covered: %s', wichObject)

File diff suppressed because one or more lines are too long

View File

@ -138,7 +138,7 @@ class gui:
return {'id': str(id_), 'text': str(text)}
@staticmethod
def choiceImage(id_: typing.Union[str, int], text: str, img: bytes) -> typing.Dict[str, typing.Union[str, bytes]]:
def choiceImage(id_: typing.Union[str, int], text: str, img: str) -> typing.Dict[str, str]:
return {'id': str(id_), 'text': str(text), 'img': img}
@staticmethod

View File

@ -33,9 +33,12 @@
import logging
import typing
from uds.core.managers import logManager
# Not imported at runtime, just for type checking
if typing.TYPE_CHECKING:
from django.db.models import Model
logger = logging.getLogger(__name__)
useLogger = logging.getLogger('useLog')
@ -74,15 +77,14 @@ def logStrFromLevel(level: int) -> str:
def useLog(
type_: str,
serviceUniqueId:
str,
serviceUniqueId: str,
serviceIp: str,
username: str,
srcIP: typing.Optional[str] = None,
srcUser: typing.Optional[str] = None,
userServiceName: typing.Optional[str] = None,
poolName: typing.Optional[str] = None
):
) -> None:
"""
Logs an "use service" event (logged from actors)
:param type_: Type of event (commonly 'login' or 'logout')
@ -101,17 +103,17 @@ def useLog(
def doLog(
wichObject: typing.Any,
wichObject: 'Model',
level: typing.Union[int, str],
message: str,
source: str = UNKNOWN,
avoidDuplicates: bool = True
):
) -> None:
logger.debug('%s %s %s', wichObject, level, message)
logManager().doLog(wichObject, level, message, source, avoidDuplicates)
def getLogs(wichObject: typing.Any, limit: typing.Optional[int] = None) -> typing.List[typing.Dict]:
def getLogs(wichObject: 'Model', limit: typing.Optional[int] = None) -> typing.List[typing.Dict]:
"""
Get the logs associated with "wichObject", limiting to "limit" (default is GlobalConfig.MAX_LOGS_PER_ELEMENT)
"""
@ -123,7 +125,7 @@ def getLogs(wichObject: typing.Any, limit: typing.Optional[int] = None) -> typin
return logManager().getLogs(wichObject, limit)
def clearLogs(wichObject: typing.Any):
def clearLogs(wichObject: 'Model') -> None:
"""
Clears the logs associated with the object using the logManager
"""

View File

@ -31,6 +31,7 @@
.. moduleauthor:: Adolfo Gómez, dkmaster at dkmon dot com
"""
import logging
import typing
from django.db import models
from django.utils.translation import ugettext as _
@ -65,7 +66,7 @@ class ServicePoolGroup(UUIDModel):
return 'Service Pool group {}({})'.format(self.name, self.comments)
@property
def as_dict(self):
def as_dict(self) -> typing.Dict[str, typing.Any]:
return {
'id': self.uuid,
'name': self.name,
@ -75,9 +76,9 @@ class ServicePoolGroup(UUIDModel):
}
@property
def thumb64(self):
return self.image.thumb64 if self.image is not None else DEFAULT_THUMB_BASE64
def thumb64(self) -> str:
return self.image.thumb64 if self.image else DEFAULT_THUMB_BASE64
@staticmethod
def default():
def default() -> 'ServicePoolGroup':
return ServicePoolGroup(name=_('General'), comments='', priority=-10000)