"""Each request will have a new context."""
__docformat__ = "restructuredtext"
# Created: Tue Jan 11 14:06:59 PST 2000
# Author: Shannon -jj Behrens
# Email: jjinux@users.sourceforge.net
#
# Copyright (c) Shannon -jj Behrens. All rights reserved.
from cStringIO import StringIO
import aquarium.conf.AquariumProperties as properties
class Context:
"""Each request will have a new context.
This class defines a container for all of the information that gets passed
around to all of the various screens, layouts, etc. Not everything in the
context will have request scope. However, access to almost everything is
provided via the context. The context is normally named ``ctx``. Most
classes subclass aquarium.util.AquariumClass_ and thus have ``self._ctx``.
All templates subclass aquarium.util.AquariumTemplate_ which puts ``ctx``
in the ``_searchList``. Hence::
In Python In Cheetah
========= ==========
self._ctx.foo = $foo
Here is a list of things to expect in the context:
wsa
This wsadaptor object abstracts our interface to the Web server. See
aquarium.wsadaptor.WebServerAdaptor_.
iLib
This object contains a bunch of internal Aquarium functions. See
aquarium.util.InternalLibrary_.
form
This is an instance of aquarium.util.FormDict_. It is a dict-like object
representing the form.
request.cookie, response.cookie
This are instances of ``Cookie.SimpleCookie``. See the ``Cookie``
module in the Python standard library.
cookiesVerified
If True, then we can safely use cookies.
db
This is a reference to a Python database module. Use ``dba`` instead.
See the `Python documentation`_.
dba
This is an adaptor for ``db``. See
aquarium.database.DatabaseAssistant_.
session
This is a dict-like instance containing session data. See
aquarium.session.SessionContainer.Session_.
url
This is an urlscheme. urlscheme classes dictate how the screen
parameter is positioned in URL's. See aquarium.urlscheme.UrlSchemeAPI_.
screen
This is the module name (relative to the screen directory) of the
currently active or requested screen.
screenInstance
This is an instance of the above screen. See aquarium.screen.ScreenAPI_.
screenList
aquarium.util.Aquarium.screenLoop_ will add the name of the screen it is
about to execute to this list before attempting to execute it.
controller
If you use aquarium.screen.Controller_ as the super class for your
controllers, it will save a reference to the controller in the rare case
you need to access the controller from the view.
actionResults
Messages that must be shown to the user can be set here by controller
screens to be shown later by view screens. It is usually the layout's
responsibility to output the message. You may choose to store
``actionResults`` in the session instead of ``ctx`` if you wish for it to
survive redirects. See aquarium.screen.ScreenAPI_ and
aquarium.layout.LayoutAPI_. Also, see aquarium.util.ActionResults_ if
you want more than just a simple string.
The following are for working with gettext:
translation
This is ``gettext.translation(...)``. See ``gettext.translation`` from
the Python standard library.
\_
This is ``ctx.translation.gettext``. It also serves to mark the string
for translation. Always use a a local variable to reference this (i.e.
``_("foo")`` instead of ``self._ctx._("foo")``) or gettext will not be
able to successfully note that the string is marked for translation.
gettext
This is the same as \_, but does not mark the string for translation.
This is useful if the string is a variable instead of a literal.
ngettext
This is ``ctx.translation.ngettext``. It is like ``_``, but for plurals.
N\_
This is the identity function. It doesn't do anything other than mark
the string for translation.
The following are for convenience:
properties
I.e. aquarium.conf.AquariumProperties_.
cell0
The string ``cellspacing="0" cellpadding="0" border="0"``
clearGif
An instance of aquarium.widget.ClearGif_.
htmlent
A shortcut for ``self._ctx.iLib.htmlEntities``.
jsEsc
A shortcut for ``self._ctx.iLib.javaScriptEscape``.
jsQuote
A shortcut for ``self._ctx.iLib.javaScriptQuote``.
.. _aquarium.util.AquariumClass:
aquarium.util.AquariumClass.AquariumClass-class.html
.. _aquarium.util.AquariumTemplate:
aquarium.util.AquariumTemplate.AquariumTemplate-class.html
.. _aquarium.wsadaptor.WebServerAdaptor:
aquarium.wsadaptor.WebServerAdaptor.WebServerAdaptor-class.html
.. _aquarium.util.InternalLibrary:
aquarium.util.InternalLibrary.InternalLibrary-class.html
.. _aquarium.util.FormDict: aquarium.util.FormDict.FormDict-class.html
.. _Python documentation: http://python.org/topics/database
.. _aquarium.database.DatabaseAssistant:
aquarium.database.DatabaseAssistant.DatabaseAssistant-class.html
.. _aquarium.session.SessionContainer.Session:
aquarium.session.SessionContainer.Session-class.html
.. _aquarium.urlscheme.UrlSchemeAPI:
aquarium.urlscheme.UrlSchemeAPI-module.html
.. _aquarium.screen.ScreenAPI: aquarium.screen.ScreenAPI-module.html
.. _aquarium.util.Aquarium.screenLoop:
aquarium.util.Aquarium.Aquarium-class.html#screenLoop
.. _aquarium.screen.Controller:
aquarium.screen.Controller.Controller-class.html
.. _aquarium.layout.LayoutAPI: aquarium.layout.LayoutAPI-module.html
.. _aquarium.util.ActionResults:
aquarium.util.ActionResults.ActionResults-class.html
.. _aquarium.conf.AquariumProperties:
aquarium.conf.AquariumProperties-module.html
.. _aquarium.widget.ClearGif: aquarium.widget.ClearGif.ClearGif-class.html
"""
def __init__(self):
"""Initialize all the convenience attributes."""
self.properties = properties
self.cell0 = 'cellspacing="0" cellpadding="0" border="0"'
self.request = Request()
self.response = Response()
def __getattr__(self, attr):
"""Some of the convenience attributes can't be set in ``__init__``.
Some of them are only available after ``self.iLib`` is set which is
sometime later.
"""
className = self.__class__.__name__
if attr in ["clearGif", "htmlent", "jsEsc", "jsQuote"]:
if not hasattr(self, "iLib"):
raise AttributeError("""\
%s instance has no attribute '%s' until %s.iLib gets set""" %
(className, attr, className))
if attr == "clearGif":
return self.iLib.aquariumFactory("widget.ClearGif")
if attr == "htmlent":
return self.iLib.htmlEntities
if attr == "jsEsc":
return self.iLib.javaScriptEscape
if attr == "jsQuote":
return self.iLib.javaScriptQuote
raise AttributeError("%s instance has no attribute '%s'" %
(className, attr))
def __repr__(self):
"""Return a string representation of the ``ctx``.
No HTML formatting will be used. This is so that you can use it from
the shell. Use ``<pre>`` and ``htmlent`` if you need to use this on an
HTML page.
The code below is funky. I did it this way so that:
* Everything in the ``ctx`` gets printed.
* Stuff that isn't in the ``ctx`` yet doesn't get printed.
* Certain fields need to be printed in certain ways.
"""
buf = StringIO()
try:
buf.write("Context:\n")
keys = self.__dict__.keys()
keys.sort()
for key in keys:
value = self.__dict__[key]
if key == "wsa":
buf.write(" wsa: %s\n" % `value`)
buf.write(" getCgiEnv:\n")
buf.write(self._dictRepr(value.getCgiEnv(), " "))
elif key in ["request", "response"]:
buf.write(" %s: %s\n" % (key, `value`))
if hasattr(value, "cookie"):
buf.write(" cookie:\n")
buf.write(self._indent(" ", str(value.cookie)))
buf.write("\n")
elif key == "screenInstance":
pass
elif hasattr(value, "keys"):
buf.write(" %s:\n" % key)
buf.write(self._dictRepr(value))
else:
buf.write(" %s: %s\n" % (key, value))
return buf.getvalue()
finally:
buf.close()
def _indent(self, indentation, s, includingFirstLine=True):
"""Return ``s`` with indentation at the beginning of each line."""
if includingFirstLine:
s = indentation + s
return s.replace("\n", "\n" + indentation)
def _dictRepr(self, dict, indentation=" "):
"""This is a ``repr`` for dicts used by ``__repr__`` above."""
keys = dict.keys()
keys.sort()
return "".join(["%s%s: %s\n" % (indentation, key, dict[key])
for key in keys])
def _N(self, s):
"""This is the identity function.
It serves to tell gettext to mark the string for translation.
"""
return s
# I have to do alias tricks or xgettext will think the definition of N_ is
# actually a call to N_.
N_ = _N
class Request: pass
class Response: pass
|