more upgrading models for 3.7

This commit is contained in:
Adolfo Gómez García 2019-08-12 13:32:29 +02:00
parent a6bf2c4cfc
commit 1e789132a5
6 changed files with 48 additions and 48 deletions

View File

@ -33,6 +33,7 @@
import datetime
import logging
import typing
from django.db import models
from django.utils.translation import ugettext_lazy as _
@ -48,7 +49,7 @@ logger = logging.getLogger(__name__)
WEEKDAYS = 'WEEKDAYS'
# Frequencies
freqs = (
freqs: typing.Tuple[typing.Tuple[str, str], ...] = (
('YEARLY', _('Yearly')),
('MONTHLY', _('Monthly')),
('WEEKLY', _('Weekly')),
@ -56,35 +57,35 @@ freqs = (
(WEEKDAYS, _('Weekdays'))
)
frq_to_rrl = {
frq_to_rrl: typing.Dict[str, int] = {
'YEARLY': rules.YEARLY,
'MONTHLY': rules.MONTHLY,
'WEEKLY': rules.WEEKLY,
'DAILY': rules.DAILY,
}
frq_to_mins = {
frq_to_mins: typing.Dict[str, int] = {
'YEARLY': 366 * 24 * 60,
'MONTHLY': 31 * 24 * 60,
'WEEKLY': 7 * 24 * 60,
'DAILY': 24 * 60,
}
dunits = (
dunits: typing.Tuple[typing.Tuple[str, str], ...] = (
('MINUTES', _('Minutes')),
('HOURS', _('Hours')),
('DAYS', _('Days')),
('WEEKS', _('Weeks')),
)
dunit_to_mins = {
dunit_to_mins: typing.Dict[str, int] = {
'MINUTES': 1,
'HOURS': 60,
'DAYS': 60 * 24,
'WEEKS': 60 * 24 * 7
}
weekdays = [rules.SU, rules.MO, rules.TU, rules.WE, rules.TH, rules.FR, rules.SA]
weekdays: typing.Tuple[rules.weekday, ...] = (rules.SU, rules.MO, rules.TU, rules.WE, rules.TH, rules.FR, rules.SA)
class CalendarRule(UUIDModel):
@ -107,7 +108,7 @@ class CalendarRule(UUIDModel):
db_table = 'uds_calendar_rules'
app_label = 'uds'
def as_rrule(self):
def as_rrule(self) -> rules.rrule:
if self.interval == 0: # Fix 0 intervals
self.interval = 1
@ -121,10 +122,9 @@ class CalendarRule(UUIDModel):
dw.append(weekdays[i])
l >>= 1
return rules.rrule(rules.DAILY, byweekday=dw, dtstart=self.start, until=end)
else:
return rules.rrule(frq_to_rrl[self.frequency], interval=self.interval, dtstart=self.start, until=end)
return rules.rrule(frq_to_rrl[self.frequency], interval=self.interval, dtstart=self.start, until=end)
def as_rrule_end(self):
def as_rrule_end(self) -> rules.rrule:
if self.interval == 0: # Fix 0 intervals
self.interval = 1
@ -138,18 +138,16 @@ class CalendarRule(UUIDModel):
dw.append(weekdays[i])
l >>= 1
return rules.rrule(rules.DAILY, byweekday=dw, dtstart=self.start + datetime.timedelta(minutes=self.duration_as_minutes), until=end)
else:
return rules.rrule(frq_to_rrl[self.frequency], interval=self.interval, dtstart=self.start + datetime.timedelta(minutes=self.duration_as_minutes), until=end)
return rules.rrule(frq_to_rrl[self.frequency], interval=self.interval, dtstart=self.start + datetime.timedelta(minutes=self.duration_as_minutes), until=end)
@property
def frequency_as_minutes(self):
def frequency_as_minutes(self) -> int:
if self.frequency != WEEKDAYS:
return frq_to_mins.get(self.frequency, 0) * self.interval
else:
return 7 * 24 * 60
return 7 * 24 * 60
@property
def duration_as_minutes(self):
def duration_as_minutes(self) -> int:
return dunit_to_mins.get(self.duration_unit, 1) * self.duration
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
@ -157,6 +155,7 @@ class CalendarRule(UUIDModel):
self.calendar.modified = getSqlDatetime()
res = super().save(force_insert, force_update, using, update_fields)
# Ensure saves associated calendar, so next execution of actions is updated with rule values
self.calendar.save()
return res

View File

@ -59,5 +59,4 @@ class Config(models.Model):
app_label = 'uds'
def __str__(self):
return u"Config {0} = {1}".format(self.key, self.value)
return "Config {} = {}".format(self.key, self.value)

View File

@ -32,6 +32,7 @@
.. moduleauthor:: Adolfo Gómez, dkmaster at dkmon dot com
"""
import logging
import typing
from django.db import models
from uds.models.UUIDModel import UUIDModel
@ -49,9 +50,9 @@ class DBFile(UUIDModel):
modified = models.DateTimeField()
@property
def data(self):
def data(self) -> bytes:
try:
return encoders.decode(encoders.decode(self.content, 'base64'), 'zip')
return typing.cast(bytes, encoders.decode(encoders.decode(self.content, 'base64'), 'zip'))
except Exception:
logger.error('DBFile %s has errors and cannot be used', self.name)
try:
@ -59,13 +60,12 @@ class DBFile(UUIDModel):
except Exception:
logger.error('Could not even delete %s!!', self.name)
return ''
return b''
@data.setter
def data(self, value):
def data(self, value: typing.Union[str, bytes]):
self.size = len(value)
content = encoders.encode(encoders.encode(value, 'zip'), 'base64', asText=True)
self.content = content
self.content = typing.cast(str, encoders.encode(encoders.encode(value, 'zip'), 'base64', asText=True))
def __str__(self):
return 'File: {} {} {} {}'.format(self.name, self.size, self.created, self.modified)

View File

@ -62,5 +62,4 @@ class DelayedTask(models.Model):
app_label = 'uds'
def __str__(self):
return u"Run Queue task {0} owned by {3},inserted at {1} and with {2} seconds delay".format(self.type, self.insert_date, self.execution_delay, self.execution_time)
return "Run Queue task {0} owned by {3},inserted at {1} and with {2} seconds delay".format(self.type, self.insert_date, self.execution_delay, self.execution_time)

View File

@ -31,20 +31,23 @@
.. moduleauthor:: Adolfo Gómez, dkmaster at dkmon dot com
"""
import logging
import typing
from django.db import models
from django.db.models import signals
from uds.core.util.State import State
from uds.core.util import log
from uds.core.auths.BaseAuthenticator import Authenticator as AuthenticatorInstance
from .UUIDModel import UUIDModel
from .Authenticator import Authenticator
from .User import User
from .Util import UnsavedForeignKey, getSqlDatetime
# Not imported in runtime, just for type checking
if typing.TYPE_CHECKING:
from uds.core import auths
logger = logging.getLogger(__name__)
@ -75,7 +78,7 @@ class Group(UUIDModel):
def pretty_name(self) -> str:
return self.name + '@' + self.manager.name
def getManager(self) -> AuthenticatorInstance:
def getManager(self) -> 'auths.Authenticator':
"""
Returns the authenticator object that owns this user.

View File

@ -29,15 +29,15 @@
.. moduleauthor:: Adolfo Gómez, dkmaster at dkmon dot com
"""
import io
import logging
import typing
from django.db import models
from django.db.models import signals
from django.http import HttpResponse
from PIL import Image as PILImage # @UnresolvedImport
from PIL import Image as PILImage
from uds.models.UUIDModel import UUIDModel
from uds.models.Util import getSqlDatetime
@ -72,15 +72,15 @@ class Image(UUIDModel):
app_label = 'uds'
@staticmethod
def encode64(data):
return encoders.encode(data, 'base64', asText=True).replace('\n', '') # Removes \n
def encode64(data: bytes) -> str:
return typing.cast(str, encoders.encode(data, 'base64', asText=True)).replace('\n', '') # Removes \n
@staticmethod
def decode64(data64):
return encoders.decode(data64, 'base64')
def decode64(data64: str) -> bytes:
return typing.cast(bytes, encoders.decode(data64, 'base64'))
@staticmethod
def prepareForDb(data):
def prepareForDb(data: bytes) -> bytes:
try:
stream = io.BytesIO(data)
image = PILImage.open(stream)
@ -94,35 +94,35 @@ class Image(UUIDModel):
return output.getvalue()
@property
def data64(self):
def data64(self) -> str:
"""
Returns the value of the image (data) as a base 64 encoded string
"""
return Image.encode64(self.data)
@data64.setter
def data64(self, value):
def data64(self, value: str):
"""
Sets the value of image (data) from a base 64 encoded string
"""
self.data = Image.decode64(value)
@property
def thumb64(self):
def thumb64(self) -> str:
"""
Returns the value of the image (data) as a base 64 encoded string
"""
return Image.encode64(self.thumb)
@thumb64.setter
def thumb64(self, value):
def thumb64(self, value: str):
"""
Sets the value of image (data) from a base 64 encoded string
"""
self.thumb = Image.decode64(value)
@property
def image(self):
def image(self) -> PILImage:
"""
Returns an image (PIL Image)
"""
@ -133,13 +133,13 @@ class Image(UUIDModel):
return PILImage.new('RGBA', Image.MAX_IMAGE_SIZE)
@property
def size(self):
def size(self) -> typing.Tuple[int, int]:
"""
Returns the image size
"""
return self.width, self.height
def updateThumbnail(self):
def updateThumbnail(self) -> None:
thumb = self.image
self.width, self.height = thumb.size
thumb.thumbnail(Image.THUMBNAIL_SIZE, PILImage.ANTIALIAS)
@ -147,25 +147,25 @@ class Image(UUIDModel):
thumb.save(output, 'png')
self.thumb = output.getvalue()
def _processImageStore(self):
def _processImageStore(self) -> None:
self.data = Image.prepareForDb(self.data)
self.updateThumbnail()
def storeImageFromBinary(self, data):
def storeImageFromBinary(self, data) -> None:
self.data = data
self._processImageStore()
def storeImageFromBase64(self, data64):
def storeImageFromBase64(self, data64: str):
"""
Stores an image, passed as base64 string, resizing it as necessary
"""
self.data64 = data64
self._processImageStore()
def imageResponse(self):
def imageResponse(self) -> HttpResponse:
return HttpResponse(self.data, content_type='image/png')
def thumbnailResponse(self):
def thumbnailResponse(self) -> HttpResponse:
return HttpResponse(self.thumb, content_type='image/png')
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):