Skip to content

Commit

Permalink
Rename Exceptions to Errors.
Browse files Browse the repository at this point in the history
Add TileSourceFileNotFoundError when a file is attempted to be opened
that doesn't exist.  This is a subclass of both TileSourceError and
FileNotFoundError.

Renaming exceptions to errors follows standard Python naming
conventions.  Old names are still available for compatibility.
  • Loading branch information
manthey committed Sep 22, 2021
1 parent 2cbcb95 commit c0b6628
Show file tree
Hide file tree
Showing 24 changed files with 217 additions and 136 deletions.
10 changes: 5 additions & 5 deletions girder/girder_large_image/girder_tilesource.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from girder.models.item import Item
from large_image import tilesource
from large_image.constants import SourcePriority
from large_image.exceptions import TileSourceAssetstoreException, TileSourceException
from large_image.exceptions import TileSourceAssetstoreError, TileSourceError

AvailableGirderTileSources = {}
KnownMimeTypes = set()
Expand Down Expand Up @@ -101,13 +101,13 @@ def _getLargeImagePath(self):
try:
largeImagePath = File().getLocalFilePath(largeImageFile)
except AttributeError as e:
raise TileSourceException(
raise TileSourceError(
'No local file path for this file: %s' % e.args[0])
return largeImagePath
except (TileSourceAssetstoreException, FilePathException):
except (TileSourceAssetstoreError, FilePathException):
raise
except (KeyError, ValidationException, TileSourceException) as e:
raise TileSourceException(
except (KeyError, ValidationException, TileSourceError) as e:
raise TileSourceError(
'No large image file in this item: %s' % e.args[0])


Expand Down
22 changes: 11 additions & 11 deletions girder/girder_large_image/models/image_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
from girder.models.upload import Upload
from large_image.cache_util import getTileCache, strhash
from large_image.constants import TileOutputMimeTypes
from large_image.exceptions import TileGeneralException, TileSourceException
from large_image.exceptions import TileGeneralError, TileSourceError

from .. import constants, girder_tilesource

Expand Down Expand Up @@ -60,13 +60,13 @@ def createImageItem(self, item, fileObj, user=None, token=None,
createJob=True, notify=False, **kwargs):
# Using setdefault ensures that 'largeImage' is in the item
if 'fileId' in item.setdefault('largeImage', {}):
raise TileGeneralException('Item already has largeImage set.')
raise TileGeneralError('Item already has largeImage set.')
if fileObj['itemId'] != item['_id']:
raise TileGeneralException(
raise TileGeneralError(
'The provided file must be in the provided item.')
if (item['largeImage'].get('expected') is True and
'jobId' in item['largeImage']):
raise TileGeneralException(
raise TileGeneralError(
'Item is scheduled to generate a largeImage.')

item['largeImage'].pop('expected', None)
Expand All @@ -79,7 +79,7 @@ def createImageItem(self, item, fileObj, user=None, token=None,
item['largeImage']['sourceName'] = sourceName
if not sourceName or createJob == 'always':
if not createJob:
raise TileGeneralException(
raise TileGeneralError(
'A job must be used to generate a largeImage.')
# No source was successful
del item['largeImage']['fileId']
Expand Down Expand Up @@ -120,7 +120,7 @@ def _createLargeImageJob(self, item, fileObj, user, token, **kwargs):

def convertImage(self, item, fileObj, user=None, token=None, localJob=True, **kwargs):
if fileObj['itemId'] != item['_id']:
raise TileGeneralException(
raise TileGeneralError(
'The provided file must be in the provided item.')
if not localJob:
return self._convertImageViaWorker(item, fileObj, user, token, **kwargs)
Expand Down Expand Up @@ -187,7 +187,7 @@ def _tileFromHash(cls, item, x, y, z, mayRedirect=False, **kwargs):
sourceName = item['largeImage']['sourceName']
try:
sourceClass = girder_tilesource.AvailableGirderTileSources[sourceName]
except TileSourceException:
except TileSourceError:
return None
classHash = sourceClass.getLRUHash(item, **kwargs)
tileHash = sourceClass.__name__ + ' ' + classHash + ' ' + strhash(
Expand All @@ -206,17 +206,17 @@ def _tileFromHash(cls, item, x, y, z, mayRedirect=False, **kwargs):
@classmethod
def _loadTileSource(cls, item, **kwargs):
if 'largeImage' not in item:
raise TileSourceException('No large image file in this item.')
raise TileSourceError('No large image file in this item.')
if item['largeImage'].get('expected'):
raise TileSourceException('The large image file for this item is '
'still pending creation.')
raise TileSourceError('The large image file for this item is '
'still pending creation.')

sourceName = item['largeImage']['sourceName']
try:
# First try to use the tilesource we recorded as the preferred one.
# This is faster than trying to find the best source each time.
tileSource = girder_tilesource.AvailableGirderTileSources[sourceName](item, **kwargs)
except TileSourceException:
except TileSourceError:
# We could try any source
# tileSource = girder_tilesource.getGirderTileSource(item, **kwargs)
# but, instead, log that the original source no longer works are
Expand Down
4 changes: 2 additions & 2 deletions girder/girder_large_image/rest/large_image_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from girder.models.item import Item
from girder.models.setting import Setting
from large_image import cache_util
from large_image.exceptions import TileGeneralException
from large_image.exceptions import TileGeneralError

from .. import constants, girder_tilesource
from ..models.image_item import ImageItem
Expand All @@ -56,7 +56,7 @@ def createThumbnailsJobTask(item, spec):
else:
result = ImageItem().getThumbnail(item, checkAndCreate=True, **entry)
status['checked' if result is True else 'created'] += 1
except TileGeneralException as exc:
except TileGeneralError as exc:
status['failed'] += 1
status['lastFailed'] = str(item['_id'])
logger.info('Failed to get thumbnail for item %s: %r' % (item['_id'], exc))
Expand Down
24 changes: 12 additions & 12 deletions girder/girder_large_image/rest/tiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from girder.utility.progress import setResponseTimeLimit
from large_image.cache_util import strhash
from large_image.constants import TileInputUnits
from large_image.exceptions import TileGeneralException
from large_image.exceptions import TileGeneralError

from .. import loadmodelcache
from ..models.image_item import ImageItem
Expand Down Expand Up @@ -188,7 +188,7 @@ def createTiles(self, item, params):
createJob='always' if self.boolParam('force', params, default=False) else True,
notify=notify,
**params)
except TileGeneralException as e:
except TileGeneralError as e:
raise RestException(e.args[0])

@describeRoute(
Expand Down Expand Up @@ -251,7 +251,7 @@ def convertImage(self, item, params):
try:
return self.imageItemModel.convertImage(
item, largeImageFile, user, token, localJob=localJob, **params)
except TileGeneralException as e:
except TileGeneralError as e:
raise RestException(e.args[0])

@classmethod
Expand Down Expand Up @@ -325,7 +325,7 @@ def _getTilesInfo(self, item, imageArgs):
"""
try:
return self.imageItemModel.getMetadata(item, **imageArgs)
except TileGeneralException as e:
except TileGeneralError as e:
raise RestException(e.args[0], code=400)

def _setContentDisposition(self, item, contentDisposition, mime, subname, fullFilename=None):
Expand Down Expand Up @@ -383,7 +383,7 @@ def getTilesInfo(self, item, params):
def getInternalMetadata(self, item, params):
try:
return self.imageItemModel.getInternalMetadata(item, **params)
except TileGeneralException as e:
except TileGeneralError as e:
raise RestException(e.args[0], code=400)

@describeRoute(
Expand Down Expand Up @@ -462,7 +462,7 @@ def _getTile(self, item, z, x, y, imageArgs, mayRedirect=False):
try:
tileData, tileMime = self.imageItemModel.getTile(
item, x, y, z, mayRedirect=mayRedirect, **imageArgs)
except TileGeneralException as e:
except TileGeneralError as e:
raise RestException(e.args[0], code=404)
setResponseHeader('Content-Type', tileMime)
setRawResponse()
Expand Down Expand Up @@ -690,7 +690,7 @@ def getTilesThumbnail(self, item, params):
_handleETag('getTilesThumbnail', item, params)
try:
result = self.imageItemModel.getThumbnail(item, **params)
except TileGeneralException as e:
except TileGeneralError as e:
raise RestException(e.args[0])
except ValueError as e:
raise RestException('Value Error: %s' % e.args[0])
Expand Down Expand Up @@ -828,7 +828,7 @@ def getTilesRegion(self, item, params):
try:
regionData, regionMime = self.imageItemModel.getRegion(
item, **params)
except TileGeneralException as e:
except TileGeneralError as e:
raise RestException(e.args[0])
except ValueError as e:
raise RestException('Value Error: %s' % e.args[0])
Expand Down Expand Up @@ -884,7 +884,7 @@ def getTilesPixel(self, item, params):
])
try:
pixel = self.imageItemModel.getPixel(item, **params)
except TileGeneralException as e:
except TileGeneralError as e:
raise RestException(e.args[0])
except ValueError as e:
raise RestException('Value Error: %s' % e.args[0])
Expand Down Expand Up @@ -1005,7 +1005,7 @@ def getBandInformation(self, item, params):
def getAssociatedImagesList(self, item, params):
try:
return self.imageItemModel.getAssociatedImagesList(item)
except TileGeneralException as e:
except TileGeneralError as e:
raise RestException(e.args[0], code=400)

@describeRoute(
Expand Down Expand Up @@ -1049,7 +1049,7 @@ def getAssociatedImage(self, itemId, image, params):
_handleETag('getAssociatedImage', item, image, params)
try:
result = self.imageItemModel.getAssociatedImage(item, image, **params)
except TileGeneralException as e:
except TileGeneralError as e:
raise RestException(e.args[0], code=400)
if not isinstance(result, tuple):
return result
Expand Down Expand Up @@ -1217,7 +1217,7 @@ def tileFrames(self, item, params):
try:
result = self.imageItemModel.tileFrames(
item, checkAndCreate=checkAndCreate, **params)
except TileGeneralException as e:
except TileGeneralError as e:
raise RestException(e.args[0])
except ValueError as e:
raise RestException('Value Error: %s' % e.args[0])
Expand Down
11 changes: 10 additions & 1 deletion girder/test_girder/test_web_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,17 @@
@pytest.mark.plugin('large_image')
@pytest.mark.parametrize('spec', (
'imageViewerSpec.js',
'largeImageSpec.js',
))
def testWebClient(boundServer, fsAssetstore, db, spec, girderWorker):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(boundServer, spec, 15000)


@pytest.mark.usefixtures('unbindLargeImage')
@pytest.mark.plugin('large_image')
@pytest.mark.parametrize('spec', (
'largeImageSpec.js',
))
def testWebClientNoWorker(boundServer, fsAssetstore, db, spec):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(boundServer, spec, 15000)
19 changes: 16 additions & 3 deletions large_image/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@
class TileGeneralException(Exception):
import errno


class TileGeneralError(Exception):
pass


class TileSourceException(TileGeneralException):
class TileSourceError(TileGeneralError):
pass


class TileSourceAssetstoreException(TileSourceException):
class TileSourceAssetstoreError(TileSourceError):
pass


class TileSourceFileNotFoundError(TileSourceError, FileNotFoundError):
def __init__(self, *args, **kwargs):
return super().__init__(errno.ENOENT, *args, **kwargs)


TileGeneralException = TileGeneralError
TileSourceException = TileSourceError
TileSourceAssetstoreException = TileSourceAssetstoreError
11 changes: 8 additions & 3 deletions large_image/tilesource/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@

from .. import config
from ..constants import SourcePriority
from ..exceptions import TileGeneralException, TileSourceAssetstoreException, TileSourceException
from ..exceptions import (TileGeneralError, TileGeneralException,
TileSourceAssetstoreError,
TileSourceAssetstoreException, TileSourceError,
TileSourceException, TileSourceFileNotFoundError)
from .base import (TILE_FORMAT_IMAGE, TILE_FORMAT_NUMPY, TILE_FORMAT_PIL,
FileTileSource, TileOutputMimeTypes, TileSource,
dictToEtree, etreeToDict, nearPowerOfTwo)
Expand Down Expand Up @@ -108,7 +111,7 @@ def getTileSourceFromDict(availableSources, pathOrUri, *args, **kwargs):
sourceName = getSourceNameFromDict(availableSources, pathOrUri, *args, **kwargs)
if sourceName:
return availableSources[sourceName](pathOrUri, *args, **kwargs)
raise TileSourceException('No available tilesource for %s' % pathOrUri)
raise TileSourceError('No available tilesource for %s' % pathOrUri)


def getTileSource(*args, **kwargs):
Expand Down Expand Up @@ -151,7 +154,9 @@ def canRead(*args, **kwargs):

__all__ = [
'TileSource', 'FileTileSource',
'exceptions', 'TileGeneralException', 'TileSourceException', 'TileSourceAssetstoreException',
'exceptions', 'TileGeneralError', 'TileSourceError',
'TileSourceAssetstoreError', 'TileSourceFileNotFoundError',
'TileGeneralException', 'TileSourceException', 'TileSourceAssetstoreException',
'TileOutputMimeTypes', 'TILE_FORMAT_IMAGE', 'TILE_FORMAT_PIL', 'TILE_FORMAT_NUMPY',
'AvailableTileSources', 'getTileSource', 'canRead', 'getSourceNameFromDict', 'nearPowerOfTwo',
'etreeToDict', 'dictToEtree',
Expand Down
14 changes: 7 additions & 7 deletions large_image/tilesource/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def __init__(self, encoding='JPEG', jpegQuality=95, jpegSubsampling=0,
if not isinstance(self.style, dict):
raise TypeError
except TypeError:
raise exceptions.TileSourceException('Style is not a valid json object.')
raise exceptions.TileSourceError('Style is not a valid json object.')

@staticmethod
def getLRUHash(*args, **kwargs):
Expand Down Expand Up @@ -1374,17 +1374,17 @@ def _xyzInRange(self, x, y, z, frame=None, numFrames=None):
exception if not.
"""
if z < 0 or z >= self.levels:
raise exceptions.TileSourceException('z layer does not exist')
raise exceptions.TileSourceError('z layer does not exist')
scale = 2 ** (self.levels - 1 - z)
offsetx = x * self.tileWidth * scale
if not (0 <= offsetx < self.sizeX):
raise exceptions.TileSourceException('x is outside layer')
raise exceptions.TileSourceError('x is outside layer')
offsety = y * self.tileHeight * scale
if not (0 <= offsety < self.sizeY):
raise exceptions.TileSourceException('y is outside layer')
raise exceptions.TileSourceError('y is outside layer')
if frame is not None and numFrames is not None:
if frame < 0 or frame >= numFrames:
raise exceptions.TileSourceException('Frame does not exist')
raise exceptions.TileSourceError('Frame does not exist')

@methodcache()
def getTile(self, x, y, z, pilImageAllowed=False, numpyAllowed=False,
Expand Down Expand Up @@ -1639,7 +1639,7 @@ def _addRegionTileToImage(
(height, width, subimage.shape[2]),
dtype=subimage.dtype)
except MemoryError:
raise exceptions.TileSourceException(
raise exceptions.TileSourceError(
'Insufficient memory to get region of %d x %d pixels.' % (
width, height))
if subimage.shape[2] > image.shape[2]:
Expand Down Expand Up @@ -2342,5 +2342,5 @@ def canRead(cls, path, *args, **kwargs):
try:
cls(path, *args, **kwargs)
return True
except exceptions.TileSourceException:
except exceptions.TileSourceError:
return False
2 changes: 1 addition & 1 deletion large_image/tilesource/tiledict.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def __getitem__(self, key, *args, **kwargs):
tileData, **self.imageKwargs)
tileFormat = TILE_FORMAT_IMAGE
if tileFormat not in self.format:
raise exceptions.TileSourceException(
raise exceptions.TileSourceError(
'Cannot yield tiles in desired format %r' % (
self.format, ))
else:
Expand Down
Loading

0 comments on commit c0b6628

Please sign in to comment.