Simplifying several "is True"

This commit is contained in:
Adolfo Gómez García 2021-05-27 13:04:18 +02:00
parent 8fc5c759d8
commit cb92be3c66
14 changed files with 35 additions and 35 deletions

View File

@ -144,9 +144,9 @@ def webLoginRequired(
# logger.debug('No user found, redirecting to %s', url) # logger.debug('No user found, redirecting to %s', url)
return HttpResponseRedirect(reverse('page.login')) # type: ignore return HttpResponseRedirect(reverse('page.login')) # type: ignore
if admin is True or admin == 'admin': if admin is True or admin == 'admin': # bool or string "admin"
if request.user.isStaff() is False or ( if request.user.isStaff() is False or (
admin == 'admin' and request.user.is_admin is False admin == 'admin' and not request.user.is_admin
): ):
return HttpResponseForbidden(_('Forbidden')) # type: ignore return HttpResponseForbidden(_('Forbidden')) # type: ignore

View File

@ -84,7 +84,7 @@ class GroupsManager:
name = groupName.lower() name = groupName.lower()
res = [] res = []
for gName, grp in self._groups.items(): for gName, grp in self._groups.items():
if grp['pattern'] is True: if grp['pattern']:
logger.debug('Group is a pattern: %s', grp) logger.debug('Group is a pattern: %s', grp)
try: try:
logger.debug('Match: %s->%s', grp['name'][4:], name) logger.debug('Match: %s->%s', grp['name'][4:], name)
@ -114,14 +114,14 @@ class GroupsManager:
lst: typing.List[str] = [] lst: typing.List[str] = []
for g in self._groups.values(): for g in self._groups.values():
if g['valid'] is True: if g['valid']:
lst += (g['group'].dbGroup().id,) lst += (g['group'].dbGroup().id,)
yield g['group'] yield g['group']
# Now, get metagroups and also return them # Now, get metagroups and also return them
for g2 in DBGroup.objects.filter(manager__id=self._dbAuthenticator.id, is_meta=True): # @UndefinedVariable for g2 in DBGroup.objects.filter(manager__id=self._dbAuthenticator.id, is_meta=True): # @UndefinedVariable
gn = g2.groups.filter(id__in=lst, state=State.ACTIVE).count() gn = g2.groups.filter(id__in=lst, state=State.ACTIVE).count()
if g2.meta_if_any is True and gn > 0: if g2.meta_if_any and gn > 0:
gn = g2.groups.count() gn = g2.groups.count()
if gn == g2.groups.count(): # If a meta group is empty, all users belongs to it. we can use gn != 0 to check that if it is empty, is not valid if gn == g2.groups.count(): # If a meta group is empty, all users belongs to it. we can use gn != 0 to check that if it is empty, is not valid
# This group matches # This group matches
@ -133,7 +133,7 @@ class GroupsManager:
validated (using :py:meth:.validate) validated (using :py:meth:.validate)
""" """
for g in self._groups.values(): for g in self._groups.values():
if g['valid'] is True: if g['valid']:
return True return True
return False return False

View File

@ -86,7 +86,7 @@ class User:
) # pylint: disable=redefined-outer-name ) # pylint: disable=redefined-outer-name
if self._groups is None: if self._groups is None:
if self._manager.isExternalSource is True: if self._manager.isExternalSource:
self._manager.getGroups(self._dbUser.name, self._groupsManager()) self._manager.getGroups(self._dbUser.name, self._groupsManager())
self._groups = list(self._groupsManager().getValidGroups()) self._groups = list(self._groupsManager().getValidGroups())
logger.debug(self._groups) logger.debug(self._groups)

View File

@ -71,7 +71,7 @@ class DelayedTask(Environmentable):
""" """
from .delayed_task_runner import DelayedTaskRunner from .delayed_task_runner import DelayedTaskRunner
if check is True and DelayedTaskRunner.runner().checkExists(tag): if check and DelayedTaskRunner.runner().checkExists(tag):
return return
DelayedTaskRunner.runner().insert(self, suggestedTime, tag) DelayedTaskRunner.runner().insert(self, suggestedTime, tag)

View File

@ -89,7 +89,7 @@ class LogManager:
for i in qs.order_by('-created',)[GlobalConfig.MAX_LOGS_PER_ELEMENT.getInt() - 1:]: for i in qs.order_by('-created',)[GlobalConfig.MAX_LOGS_PER_ELEMENT.getInt() - 1:]:
i.delete() i.delete()
if avoidDuplicates is True: if avoidDuplicates:
try: try:
lg = models.Log.objects.filter(owner_id=owner_id, owner_type=owner_type, level=level, source=source).order_by('-created', '-id')[0] lg = models.Log.objects.filter(owner_id=owner_id, owner_type=owner_type, level=level, source=source).order_by('-created', '-id')[0]
if lg.data == message: if lg.data == message:

View File

@ -69,7 +69,7 @@ def barChart(
axis.set_xlabel(data['xlabel']) axis.set_xlabel(data['xlabel'])
axis.set_ylabel(data['ylabel']) axis.set_ylabel(data['ylabel'])
if data.get('allTicks', True) is True: if data.get('allTicks', True):
axis.set_xticks(ind) axis.set_xticks(ind)
if 'xtickFnc' in data: if 'xtickFnc' in data:
@ -101,7 +101,7 @@ def lineChart(
axis.set_xlabel(data['xlabel']) axis.set_xlabel(data['xlabel'])
axis.set_ylabel(data['ylabel']) axis.set_ylabel(data['ylabel'])
if data.get('allTicks', True) is True: if data.get('allTicks', True):
axis.set_xticks(x) axis.set_xticks(x)
if 'xtickFnc' in data: if 'xtickFnc' in data:
@ -136,7 +136,7 @@ def surfaceChart(
axis = fig.add_subplot(111, projection='3d') axis = fig.add_subplot(111, projection='3d')
# axis.grid(color='r', linestyle='dotted', linewidth=0.1, alpha=0.5) # axis.grid(color='r', linestyle='dotted', linewidth=0.1, alpha=0.5)
if data.get('wireframe', False) is True: if data.get('wireframe', False):
axis.plot_wireframe( axis.plot_wireframe(
x, y, z, rstride=1, cstride=1, cmap=cm.coolwarm # type: ignore x, y, z, rstride=1, cstride=1, cmap=cm.coolwarm # type: ignore
) )
@ -150,7 +150,7 @@ def surfaceChart(
axis.set_ylabel(data['ylabel']) axis.set_ylabel(data['ylabel'])
axis.set_zlabel(data['zlabel']) axis.set_zlabel(data['zlabel'])
if data.get('allTicks', True) is True: if data.get('allTicks', True):
axis.set_xticks(data['x']) axis.set_xticks(data['x'])
axis.set_yticks(data['y']) axis.set_yticks(data['y'])

View File

@ -86,7 +86,7 @@ class ServiceProviderFactory:
offers = [] offers = []
for s in type_.offers: for s in type_.offers:
if s.usesCache_L2 is True: if s.usesCache_L2:
s.usesCache = True s.usesCache = True
if s.publicationType is None: if s.publicationType is None:
logger.error('Provider %s offers %s, but %s needs cache and do not have publicationType defined', type_, s, s) logger.error('Provider %s offers %s, but %s needs cache and do not have publicationType defined', type_, s, s)

View File

@ -196,7 +196,7 @@ class CalendarChecker:
+ str(offset.seconds) + str(offset.seconds)
+ str(int(time.mktime(checkFrom.timetuple()))) + str(int(time.mktime(checkFrom.timetuple())))
+ 'event' + 'event'
+ ('x' if startEvent is True else '_') + ('x' if startEvent else '_')
) )
next_event = CalendarChecker.cache.get(cacheKey, None) next_event = CalendarChecker.cache.get(cacheKey, None)
if next_event is None: if next_event is None:

View File

@ -81,7 +81,7 @@ class Config:
def get(self, force: bool = False) -> str: def get(self, force: bool = False) -> str:
# Ensures DB contains configuration values # Ensures DB contains configuration values
# From Django 1.7, DB can only be accessed AFTER all apps are initialized (and ofc, not migrating...) # From Django 1.7, DB can only be accessed AFTER all apps are initialized (and ofc, not migrating...)
if apps.ready is True: if apps.ready:
if not GlobalConfig.isInitialized(): if not GlobalConfig.isInitialized():
logger.debug('Initializing configuration & updating db values') logger.debug('Initializing configuration & updating db values')
GlobalConfig.initialize() GlobalConfig.initialize()
@ -108,7 +108,7 @@ class Config:
self.set(self._default) self.set(self._default)
self._data = self._default self._data = self._default
if self._crypt is True: if self._crypt:
return cryptoManager().decrypt(typing.cast(str, self._data)) return cryptoManager().decrypt(typing.cast(str, self._data))
return typing.cast(str, self._data) return typing.cast(str, self._data)
@ -154,7 +154,7 @@ class Config:
_saveLater.append((self, value)) _saveLater.append((self, value))
return return
if self._crypt is True: if self._crypt:
value = cryptoManager().encrypt(value) value = cryptoManager().encrypt(value)
# Editable here means that this configuration value can be edited by admin directly (generally, that this is a "clean text" value) # Editable here means that this configuration value can be edited by admin directly (generally, that this is a "clean text" value)
@ -206,7 +206,7 @@ class Config:
if cfg.field_type == Config.HIDDEN_FIELD: if cfg.field_type == Config.HIDDEN_FIELD:
continue continue
logger.debug('%s.%s:%s,%s', cfg.section, cfg.key, cfg.value, cfg.field_type) logger.debug('%s.%s:%s,%s', cfg.section, cfg.key, cfg.value, cfg.field_type)
if cfg.crypt is True: if cfg.crypt:
val = Config.section(cfg.section).valueCrypt(cfg.key) val = Config.section(cfg.section).valueCrypt(cfg.key)
else: else:
val = Config.section(cfg.section).value(cfg.key) val = Config.section(cfg.section).value(cfg.key)
@ -220,7 +220,7 @@ class Config:
if checkType and cfg.field_type in (Config.READ_FIELD, Config.HIDDEN_FIELD): if checkType and cfg.field_type in (Config.READ_FIELD, Config.HIDDEN_FIELD):
return False # Skip non writable elements return False # Skip non writable elements
if cfg.crypt is True: if cfg.crypt:
value = cryptoManager().encrypt(value) value = cryptoManager().encrypt(value)
cfg.value = value cfg.value = value
cfg.save() cfg.save()

View File

@ -128,7 +128,7 @@ def networksFromString(
v |= 1 << (31 - n) v |= 1 << (31 - n)
return v return v
if allowMultipleNetworks is True: if allowMultipleNetworks:
res = [] res = []
for strNet in re.split('[;,]', strNets): for strNet in re.split('[;,]', strNets):
if strNet != '': if strNet != '':

View File

@ -58,12 +58,14 @@ def getPermissions(obj: 'Model') -> typing.List[models.Permissions]:
def getEffectivePermission(user: 'models.User', obj: 'Model', root: bool = False) -> int: def getEffectivePermission(user: 'models.User', obj: 'Model', root: bool = False) -> int:
try: try:
if user.is_admin is True: if user.is_admin:
return PERMISSION_ALL return PERMISSION_ALL
if user.staff_member is False: if not user.staff_member:
return PERMISSION_NONE return PERMISSION_NONE
# Just check permissions for staff members
# root means for "object type" not for an object
if root is False: if root is False:
return models.Permissions.getPermissions(user=user, groups=user.groups.all(), object_type=ot.getObjectType(obj), object_id=obj.pk) return models.Permissions.getPermissions(user=user, groups=user.groups.all(), object_type=ot.getObjectType(obj), object_id=obj.pk)

View File

@ -136,7 +136,9 @@ class GlobalRequestMiddleware:
now = timezone.now() now = timezone.now()
expiry = request.session.get(EXPIRY_KEY, now) expiry = request.session.get(EXPIRY_KEY, now)
if expiry < now: if expiry < now:
webLogout(request=request) # Ignore the response, just processes usere session logout webLogout(
request=request
) # Ignore the response, just processes usere session logout
return HttpResponse(content='Session Expired', status=403) return HttpResponse(content='Session Expired', status=403)
# Update session timeout..self. # Update session timeout..self.
request.session[EXPIRY_KEY] = now + datetime.timedelta( request.session[EXPIRY_KEY] = now + datetime.timedelta(
@ -190,10 +192,9 @@ class GlobalRequestMiddleware:
proxies = request.META['HTTP_X_FORWARDED_FOR'].split(",") proxies = request.META['HTTP_X_FORWARDED_FOR'].split(",")
request.ip_proxy = proxies[0] request.ip_proxy = proxies[0]
if ( if not request.ip or behind_proxy:
not request.ip or behind_proxy is True # Request.IP will be None in case of nginx & gunicorn
): # Request.IP will be None in case of nginx & gunicorn # Some load balancers may include "domains" on x-forwarded for,
# F5 may include "domains" on x-forwarded for,
request.ip = request.ip_proxy.split('%')[0] # Stores the ip request.ip = request.ip_proxy.split('%')[0] # Stores the ip
# will raise "list out of range", leaving ip_proxy = proxy in case of no other proxy apart of nginx # will raise "list out of range", leaving ip_proxy = proxy in case of no other proxy apart of nginx

View File

@ -66,12 +66,12 @@ class AssignedAndUnused(Job):
).filter(outdated__gt=0, state=State.ACTIVE) ).filter(outdated__gt=0, state=State.ACTIVE)
for ds in outdatedServicePools: for ds in outdatedServicePools:
# Skips checking deployed services in maintenance mode or ignores assigned and unused # Skips checking deployed services in maintenance mode or ignores assigned and unused
if ds.isInMaintenance() is True or ds.ignores_unused: if ds.isInMaintenance() or ds.ignores_unused:
continue continue
# If do not needs os manager, this is # If do not needs os manager, this is
if ds.osmanager: if ds.osmanager:
osm = ds.osmanager.getInstance() osm = ds.osmanager.getInstance()
if osm.processUnusedMachines is True: if osm.processUnusedMachines:
logger.debug( logger.debug(
'Processing unused services for %s, %s', ds, ds.osmanager 'Processing unused services for %s, %s', ds, ds.osmanager
) )

View File

@ -96,11 +96,8 @@ class UserServiceRemover(Job):
for removableUserService in removableUserServices: for removableUserService in removableUserServices:
logger.debug('Checking removal of %s', removableUserService.name) logger.debug('Checking removal of %s', removableUserService.name)
try: try:
if ( if manager.canRemoveServiceFromDeployedService(
manager.canRemoveServiceFromDeployedService(
removableUserService.deployed_service removableUserService.deployed_service
)
is True
): ):
manager.remove(removableUserService) manager.remove(removableUserService)
except Exception: except Exception: