mendfixed REST images for python 3.x

This commit is contained in:
Adolfo Gómez García 2019-09-11 12:27:47 +02:00
parent fbcf635a60
commit 51b16ce895
8 changed files with 43 additions and 33 deletions

View File

@ -70,7 +70,7 @@ class Authenticators(ModelHandler):
{'tags': {'title': _('tags'), 'visible': False}},
]
def enum_types(self) -> typing.Iterable[typing.Type[auths.Authenticator]]: # override this
def enum_types(self) -> typing.Iterable[typing.Type[auths.Authenticator]]:
return auths.factory().providers().values()
def typeInfo(self, type_: typing.Type['Module']) -> typing.Dict[str, typing.Any]:

View File

@ -30,8 +30,9 @@
"""
@author: Adolfo Gómez, dkmaster at dkmon dot com
"""
import logging
import json
import logging
import typing
from django.utils.translation import ugettext as _
@ -62,7 +63,12 @@ class Client(Handler):
authenticated = False # Client requests are not authenticated
@staticmethod
def result(result=None, error=None, errorCode=0, retryable=False):
def result(
result: typing.Any = None,
error: typing.Optional[typing.Union[str, int]] = None,
errorCode: int = 0,
retryable: bool = False
) -> typing.Dict[str, typing.Any]:
"""
Helper method to create a "result" set for actor response
:param result: Result value to return (can be None, in which case it is converted to empty string '')
@ -76,34 +82,34 @@ class Client(Handler):
if error is not None:
if isinstance(error, int):
error = errors.errorString(error)
error = str(error) # Ensure error is an string
if errorCode != 0:
error += ' (code {0:04X})'.format(errorCode)
res['error'] = error
res['retryable'] = retryable and '1' or '0'
res['retryable'] = '1' if retryable else '0'
logger.debug('Client Result: %s', res)
return res
def test(self):
def test(self) -> typing.Dict[str, typing.Any]:
"""
Executes and returns the test
"""
return Client.result(_('Correct'))
def get(self):
def get(self): # pylint: disable=too-many-locals
"""
Processes get requests
"""
logger.debug('Client args for GET: %s', self._args)
if not self._args: # Gets version
url = self._request.build_absolute_uri(reverse('page.client-download'))
return Client.result({
'availableVersion': CLIENT_VERSION,
'requiredVersion': REQUIRED_CLIENT_VERSION,
'downloadUrl': url
'downloadUrl': self._request.build_absolute_uri(reverse('page.client-download'))
})
if len(self._args) == 1: # Simple test
@ -132,9 +138,8 @@ class Client(Handler):
try:
logger.debug(data)
res = userServiceManager().getService(self._request.user, self._request.os, self._request.ip, data['service'], data['transport'])
logger.debug('Res: %s', res)
ip, userService, userServiceInstance, transport, transportInstance = res
ip, userService, userServiceInstance, transport, transportInstance = userServiceManager().getService(self._request.user, self._request.os, self._request.ip, data['service'], data['transport'])
logger.debug('Res: %s %s %s %s %s', ip, userService, userServiceInstance, transport, transportInstance)
password = cryptoManager().symDecrpyt(data['password'], scrambler)
userService.setConnectionSource(srcIp, hostname) # Store where we are accessing from so we can notify Service
@ -151,11 +156,8 @@ class Client(Handler):
})
except ServiceNotReadyError as e:
# Refresh ticket and make this retrayable
TicketStore.revalidate(ticket, 20) # Retry will be in at most 5 seconds
TicketStore.revalidate(ticket, 20) # Retry will be in at most 5 seconds, so 20 is fine :)
return Client.result(error=errors.SERVICE_IN_PREPARATION, errorCode=e.code, retryable=True)
except Exception as e:
logger.exception("Exception")
return Client.result(error=str(e))
# Will never reach this
raise RuntimeError('Unreachable point reached!!!')

View File

@ -55,7 +55,12 @@ class Connection(Handler):
needs_staff = False
@staticmethod
def result(result: typing.Any = None, error: typing.Any = None, errorCode: int = 0, retryable: bool = False) -> typing.Dict[str, typing.Any]:
def result(
result: typing.Any = None,
error: typing.Optional[typing.Union[str, int]] = None,
errorCode: int = 0,
retryable: bool = False
) -> typing.Dict[str, typing.Any]:
"""
Helper method to create a "result" set for connection response
:param result: Result value to return (can be None, in which case it is converted to empty string '')
@ -64,9 +69,10 @@ class Connection(Handler):
"""
result = result if result is not None else ''
res = {'result': result, 'date': datetime.datetime.now()}
if error is not None:
if error:
if isinstance(error, int):
error = errors.errorString(error)
error = str(error) # Ensure error is an string
if errorCode != 0:
error += ' (code {0:04X})'.format(errorCode)
res['error'] = error
@ -79,6 +85,7 @@ class Connection(Handler):
# We look for services for this authenticator groups. User is logged in in just 1 authenticator, so his groups must coincide with those assigned to ds
from uds.web.util.services import getServicesData
# Ensure user is present on request, used by web views methods
self._request.user = self._user
return Connection.result(result=getServicesData(self._request))
@ -108,6 +115,7 @@ class Connection(Handler):
return Connection.result(error=str(e))
def script(self):
# Could be one-liner, (... = ..[0:4]), but mypy complains so this is fine :)
idService = self._args[0]
idTransport = self._args[1]
scrambler = self._args[2]

View File

@ -31,6 +31,7 @@
@itemor: Adolfo Gómez, dkmaster at dkmon dot com
"""
import logging
import typing
from django.utils.translation import ugettext_lazy as _, ugettext
from uds.models import Image
@ -48,29 +49,28 @@ class Images(ModelHandler):
"""
Handles the gallery REST interface
"""
# needs_admin = True
path = 'gallery'
model = Image
save_fields = ['name', 'data']
table_title = _('Image Gallery')
table_fields = [
{'thumb': {'title': _('Image'), 'visible': True, 'type': 'image', 'width': '96px' }},
{'thumb': {'title': _('Image'), 'visible': True, 'type': 'image', 'width': '96px'}},
{'name': {'title': _('Name')}},
{'size': {'title': _('Size')}},
]
def beforeSave(self, fields):
def beforeSave(self, fields: typing.Any) -> None:
fields['data'] = Image.prepareForDb(Image.decode64(fields['data'].encode('utf8')))
def afterSave(self, item):
def afterSave(self, item: Image) -> None:
# Updates the thumbnail and re-saves it
logger.debug('After save: item = {}'.format(item))
logger.debug('After save: item = %s', item)
item.updateThumbnail()
item.save()
def getGui(self, type_):
def getGui(self, type_: str) -> typing.List[typing.Any]:
return self.addField(
self.addDefaultFields([], ['name']), {
'name': 'data',
@ -82,14 +82,14 @@ class Images(ModelHandler):
}
)
def item_as_dict(self, item):
def item_as_dict(self, item: Image) -> typing.Dict[str, typing.Any]:
return {
'id': item.uuid,
'name': item.name,
'data': item.data64,
}
def item_as_dict_overview(self, item):
def item_as_dict_overview(self, item: Image) -> typing.Dict[str, typing.Any]:
return {
'id': item.uuid,
'size': '{}x{}, {} bytes (thumb {} bytes)'.format(item.width, item.height, len(item.data), len(item.thumb)),

View File

@ -670,20 +670,20 @@ class ModelHandler(BaseModelHandler):
# Delete related, checks if the item can be deleted
# If it can't be so, raises an exception
def checkDelete(self, item: models.Model):
def checkDelete(self, item: models.Model) -> None:
pass
# Save related, checks if the item can be saved
# If it can't be saved, raises an exception
def checkSave(self, item: models.Model):
def checkSave(self, item: models.Model) -> None:
pass
# Invoked to possibily fix fields (or add new one, or check
def beforeSave(self, fields: typing.List[typing.Dict[str, typing.Any]]):
def beforeSave(self, fields: typing.Any) -> None:
pass
# Invoked right after saved an item (no matter if new or edition)
def afterSave(self, item: models.Model):
def afterSave(self, item: models.Model) -> None:
pass
# End overridable

View File

@ -52,7 +52,7 @@ class ServicePoolGroup(UUIDModel):
name = models.CharField(max_length=128, default='', db_index=True, unique=True)
comments = models.CharField(max_length=256, default='')
priority = models.IntegerField(default=0, db_index=True)
image = models.ForeignKey(Image, null=True, blank=True, related_name='servicesPoolsGroup', on_delete=models.SET_NULL)
image: Image = models.ForeignKey(Image, null=True, blank=True, related_name='servicesPoolsGroup', on_delete=models.SET_NULL)
class Meta(UUIDModel.Meta):
"""

View File

@ -53,7 +53,7 @@ logger = logging.getLogger(__name__)
class ServicePoolPublicationChangelog(models.Model):
publication = models.ForeignKey(ServicePool, on_delete=models.CASCADE, related_name='changelog')
publication: ServicePool = models.ForeignKey(ServicePool, on_delete=models.CASCADE, related_name='changelog')
stamp = models.DateTimeField()
revision = models.PositiveIntegerField(default=1)
log = models.TextField(default='')

View File

@ -88,7 +88,7 @@ strings = [
]
def errorString(errorId):
def errorString(errorId) -> str:
errorId = int(errorId)
if errorId < len(strings):
return strings[errorId]