* Small fixes to authenticator (pip related mostly)

* Adding docstrings and fixing some REST related issues
This commit is contained in:
Adolfo Gómez García 2014-10-29 19:35:33 +01:00
parent ce52ac4acc
commit 2ecb274ed6
2 changed files with 62 additions and 26 deletions

View File

@ -55,11 +55,11 @@ class Authenticators(ModelHandler):
table_title = _('Current authenticators') table_title = _('Current authenticators')
table_fields = [ table_fields = [
{'name': {'title': _('Name'), 'visible': True, 'type': 'iconType'}}, {'name': {'title': _('Name'), 'visible': True, 'type': 'iconType'}},
{'comments': {'title': _('Comments')}}, {'comments': {'title': _('Comments')}},
{'priority': {'title': _('Priority'), 'type': 'numeric', 'width': '5em'}}, {'priority': {'title': _('Priority'), 'type': 'numeric', 'width': '5em'}},
{'small_name': {'title': _('Small name')}}, {'small_name': {'title': _('Small name')}},
{'users_count': {'title': _('Users'), 'type': 'numeric', 'width': '5em'}} {'users_count': {'title': _('Users'), 'type': 'numeric', 'width': '5em'}}
] ]
def enum_types(self): def enum_types(self):
@ -114,7 +114,7 @@ class Authenticators(ModelHandler):
return auth.searchUsers(term) return auth.searchUsers(term)
else: else:
return auth.searchGroups(term) return auth.searchGroups(term)
except: except Exception:
self.invalidRequestException() self.invalidRequestException()
def test(self, type_): def test(self, type_):
@ -125,8 +125,7 @@ class Authenticators(ModelHandler):
dct['_request'] = self._request dct['_request'] = self._request
res = authType.test(Environment.getTempEnv(), dct) res = authType.test(Environment.getTempEnv(), dct)
if res[0]: if res[0]:
return 'ok' return self.success()
else: else:
return res[1] return res[1]

View File

@ -186,27 +186,38 @@ class BaseModelHandler(Handler):
return res return res
# Exceptions # Exceptions
def invalidRequestException(self): def invalidRequestException(self, message=None):
''' '''
Raises an invalid request error with a default translated string Raises an invalid request error with a default translated string
''' '''
raise RequestError(_('Invalid Request')) message = _('Invalid Request') if message is None else message
raise RequestError('{} {}: {}'.format(message, self.__class__, self._args))
def invalidMethodException(self): def invalidMethodException(self):
''' '''
Raises a NotFound exception with translated "Method not found" string to current locale Raises a NotFound exception with translated "Method not found" string to current locale
''' '''
raise NotFound(_('Method not found')) raise RequestError(_('Method not found in {}: {}'.format(self.__class__, self._args)))
def invalidItemException(self, msg=None): def invalidItemException(self, message=None):
msg = msg or _('Item not found') '''
raise NotFound(msg) Raises a NotFound exception, with location info
'''
message = _('Item not found') if message is None else None
raise NotFound('{} {}: {}'.format(message, self.__class__, self._args))
# Success methods # Success methods
def success(self): def success(self):
return 'done' '''
Utility method to be invoked for simple methods that returns nothing in fact
'''
logger.debug('Returning success on {} {}'.format(self.__class__, self._args))
return 'ok'
def test(self, type_): def test(self, type_):
'''
Invokes a test for an item
'''
logger.debug('Called base test for {0} --> {1}'.format(self.__class__.__name__, self._params)) logger.debug('Called base test for {0} --> {1}'.format(self.__class__.__name__, self._params))
return self.invalidMethodException() return self.invalidMethodException()
@ -226,6 +237,7 @@ class DetailHandler(BaseModelHandler):
[path]/types [path]/types
[path]/types/TYPE [path]/types/TYPE
[path]/tableinfo [path]/tableinfo
....?filter=[filter],[filter]..., filters are simple unix files filters, with ^ and $ supported
For PUT: For PUT:
[path] --> create NEW item [path] --> create NEW item
[path]/ID --> Modify existing item [path]/ID --> Modify existing item
@ -324,7 +336,7 @@ class DetailHandler(BaseModelHandler):
''' '''
Post will be used for, for example, testing Post will be used for, for example, testing
''' '''
raise NotFound('This objects does not accepts POSTs') self.invalidRequestException('This method does not accepts POST')
def delete(self): def delete(self):
''' '''
@ -341,14 +353,23 @@ class DetailHandler(BaseModelHandler):
# Invoked if default get can't process request # Invoked if default get can't process request
def fallbackGet(self): def fallbackGet(self):
raise self.invalidRequestException() '''
'''
raise self.invalidRequestException('Fallback invoked')
# Override this to provide functionality # Override this to provide functionality
# Default (as sample) getItems # Default (as sample) getItems
def getItems(self, parent, item): def getItems(self, parent, item):
if item is None: # Returns ALL detail items '''
return [] This must be overriden by desdendants
return {} # Returns one item Excepts to return a list of dictionaries or a single dictionary, depending on "item" param
If "item" param is None, ALL items are expected to be returned as a list of dictionaries
If "Item" param has an id (normally an uuid), one item is expected to be returned as dictionary
'''
# if item is None: # Returns ALL detail items
# return []
# return {} # Returns one item
raise NotImplementedError('Must provide an getItems method for {} class'.format(self.__class__))
# Default save # Default save
def saveItem(self, parent, item): def saveItem(self, parent, item):
@ -420,10 +441,18 @@ class ModelHandler(BaseModelHandler):
# Data related # Data related
def item_as_dict(self, item): def item_as_dict(self, item):
'''
Must be overriden by descendants.
Expects the return of an item as a dictionary
'''
pass pass
# types related # types related
def enum_types(self): # override this def enum_types(self): # override this
'''
Must be overriden by desdencents if they support types
Excpetcs the list of types that the handler supports
'''
return [] return []
def getTypes(self, *args, **kwargs): def getTypes(self, *args, **kwargs):
@ -609,8 +638,6 @@ class ModelHandler(BaseModelHandler):
if self._args[0] == OVERVIEW: if self._args[0] == OVERVIEW:
if nArgs != 2: if nArgs != 2:
self.invalidRequestException() self.invalidRequestException()
# TODO: Parse _args[1]
elif self._args[0] == TYPES: elif self._args[0] == TYPES:
if nArgs != 2: if nArgs != 2:
self.invalidRequestException() self.invalidRequestException()
@ -648,6 +675,9 @@ class ModelHandler(BaseModelHandler):
self.invalidMethodException() self.invalidMethodException()
def put(self): def put(self):
'''
Processes a PUT request
'''
logger.debug('method PUT for {0}, {1}'.format(self.__class__.__name__, self._args)) logger.debug('method PUT for {0}, {1}'.format(self.__class__.__name__, self._args))
self._params['_request'] = self._request self._params['_request'] = self._request
@ -682,8 +712,9 @@ class ModelHandler(BaseModelHandler):
# Store associated object if needed # Store associated object if needed
try: try:
if 'data_type' in self._params: # Needs to store instance data_type = self._params.get('data_type', self._params.get('type'))
item.data_type = self._params['data_type'] if data_type is not None:
item.data_type = data_type
item.data = item.getInstance(self._params).serialize() item.data = item.getInstance(self._params).serialize()
item.save() item.save()
@ -700,6 +731,9 @@ class ModelHandler(BaseModelHandler):
return res return res
def delete(self): def delete(self):
'''
Processes a DELETE request
'''
logger.debug('method DELETE for {0}, {1}'.format(self.__class__.__name__, self._args)) logger.debug('method DELETE for {0}, {1}'.format(self.__class__.__name__, self._args))
if len(self._args) > 1: if len(self._args) > 1:
return self.processDetail() return self.processDetail()
@ -713,7 +747,10 @@ class ModelHandler(BaseModelHandler):
except self.model.DoesNotExist: except self.model.DoesNotExist:
raise NotFound('Element do not exists') raise NotFound('Element do not exists')
return 'deleted' return 'ok'
def deleteItem(self, item): def deleteItem(self, item):
item.delete() '''
Basic, overridable method for deleting an item
'''
item.delete()