Since I wasn't too happy with the "return dict()" statements in
controller classes, I wrote my own response class.
And since I needed to be able to direct flash messages to more than one
place in a form, I also wrote some extra Flash functionality. With
which you can set a flash with an ID.
I hope you like it! Please let me know.
(code alert)
class Response(dict):
"""Create a minimal Response: a dict that can be
accessed via attributes.
This class should not contain any TG logic, since it
could be used as a base class for XML-RPC / JSON-RPC
or any response type.
>>> result = Response()
>>> result.a
Traceback (most recent call last):
...
KeyError: 'a'
>>> result.a = 1
>>> result.a
1
>>> result['a']
1
"""
def __init__(self, *arg, **kw):
"""Initialise as a dict """
dict.__init__(self, *arg, **kw)
def __setattr__(self, attr, value):
"""Enable value setting by attribute """
self[attr] = value
def __getattr__(self, attr):
"""Enable value retrieval by attribute """
return self[attr]
class Flash:
"""The TG default flash message behaviour.
Flashes set will be available in the current and
following response(s)
Nonexisting flashes will be returned as None
>>> memory = {}
>>> request_0 = Flash(memory)
>>> str(request_0)
''
>>> request_0.get()
>>> request_0.set('todo')
>>> str(request_0)
"'_default': 1, 'todo'\\n"
>>> request_0.set('Hello!', 'greeting')
>>> request_0.get('greeting')
'Hello!'
>>> request_1 = Flash(memory)
>>> request_1.get()
'todo'
>>> request_1.get('greeting')
'Hello!'
>>> request_2 = Flash(memory)
>>> request_2.get()
>>> request_2.get('greeting')
>>>
"""
def __init__(self, session, name='tg_flashes'):
"""Initiate the Flash instance with some session """
self._session = session
# Reserve space for the flashes in the session
self._session.setdefault(name, {})
self._session.setdefault(name + '_count', {})
# create an easy accessible references
self._flashes = self._session[name]
self._count = self._session[name + '_count']
# Erase expired messages
self._countdown()
def set(self, message, id_='_default', count=1):
"""Set a message to be available in next 'count' responses.
The message can be assigned to an optional message id, to
enable multiple message to be set.
"""
self._flashes[id_] = message
self._count[id_] = count
def get(self, id_='_default'):
"""Retrieve a flash message.
Messages can be retieved with an optional id. If no id is
specified, the default message will be returned and erased
from the flash memory.
Does not yet do any error handling: requesting a
nonexisting flash will return None
"""
if id_ in self._flashes:
return self._flashes[id_]
else:
return None
def _countdown(self):
"""Erase flashes that have expired (count < 0) """
for key in self._flashes.keys():
# keys in _flashes should be a key in _count
self._count[key] -= 1
if self._count[key] < 0:
del(self._flashes[key])
del(self._count[key])
def __str__(self):
"""String representation """
result = ""
for key in self._flashes:
result += "'%s': %d, '%s'\n" % (key,
self._count[key],
self.get(key))
return result
class TGResponse(Response):
"""TurboGears logic will be in Response.tg """
def __init__(self, *arg, **kw):
"""Constructor """
TGResponse.__init__(self, *arg, **kw)
self.tg = Response()
self.tg.flash = Flash(cherrypy.session)
# More tg functionality could be added
class CustomResponse(TGResponse):
"""TG users can make their own application-specific
Respons logic. For example to make sure that some attribute
always exists. Or to implement some protocol.
If a user would want to prevent 'tg_flash' or other TG
logic to be present in the response, she should inherit
from Respons.
"""
def __init__(self):
"""Constructor
>>> result = LijstResponse()
>>> result.message
>>> result.message = 'nederhoed'
>>> result.message
'nederhoed'
>>> type(result.user)
<type 'dict'>
"""
TGResponse.__init__(self)
self.message = None
self.code = 0
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"TurboGears" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/turbogears
-~----------~----~----~----~------~----~------~--~---