"""
def index(self):
return self.html
Chula-0.7.0/apps/basic/example/www/controllers/imports/syntax_exception.py 0000644 0001750 0001750 00000000331 11370740256 030066 0 ustar jmcfarlane jmcfarlane from chula.www import controller
class Syntax_exception(controller.Controller):
def index(self):
for missing_colon_in_expression in xrange(5)
pass
return 'This will never get called'
Chula-0.7.0/apps/basic/example/www/controllers/imports/__init__.py 0000644 0001750 0001750 00000000000 11370740256 026212 0 ustar jmcfarlane jmcfarlane Chula-0.7.0/apps/basic/example/www/controllers/imports/global_exception.py 0000644 0001750 0001750 00000000217 11370740256 030003 0 ustar jmcfarlane jmcfarlane """
This module cannot be imported because raises an exception a the
global scope, which happens during import
"""
print variable_not_defined
Chula-0.7.0/apps/basic/example/www/__init__.py 0000644 0001750 0001750 00000000000 11370740256 022147 0 ustar jmcfarlane jmcfarlane Chula-0.7.0/apps/basic/example/configuration.py 0000644 0001750 0001750 00000001740 11370740256 022447 0 ustar jmcfarlane jmcfarlane import os
from chula import config
# Development configuration
dev = config.Config()
dev.classpath = 'example.www.controllers'
dev.construction_controller = 'error'
dev.construction_trigger = '/tmp/chula_example.stop'
dev.debug = True
dev.error_controller = 'error'
dev.session = False
if 'CHULA_REGEX_MAPPER' in os.environ:
dev.mapper = (
# Home controller
(r'^$', 'home.index'),
(r'^/home/?$', 'home.index'),
(r'^/home/index/?$', 'home.index'),
# Sample controller
(r'^/sample/?$', 'sample.index'),
(r'^/sample/page/?$', 'sample.page'),
# Bad imports
(r'^/imports/bad_import/index/?$',
'imports.bad_import.index'),
# Controller raising exceptions
(r'^/imports/global_exception/index/?$',
'imports.global_exception.index'),
# Controller with syntax errors
(r'^/imports/syntax_exception/index/?$',
'imports.syntax_exception.index'),
)
Chula-0.7.0/apps/basic/example/__init__.py 0000644 0001750 0001750 00000000000 11370740256 021323 0 ustar jmcfarlane jmcfarlane Chula-0.7.0/docs/ 0000755 0001750 0001750 00000000000 11412546122 014466 5 ustar jmcfarlane jmcfarlane Chula-0.7.0/docs/conf.py 0000644 0001750 0001750 00000014337 11370740256 016004 0 ustar jmcfarlane jmcfarlane # -*- coding: utf-8 -*-
#
# Chula documentation build configuration file, created by
# sphinx-quickstart on Thu Dec 10 17:52:47 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
import chula
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.append(os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Chula'
copyright = u'2009, John McFarlane'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = chula.version
# The full version, including alpha/beta/rc tags.
release = chula.version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'Chuladoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Chula.tex', u'Chula Documentation', u'John McFarlane', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
Chula-0.7.0/docs/install.rst 0000644 0001750 0001750 00000003764 11370740256 016707 0 ustar jmcfarlane jmcfarlane ============
Installation
============
You can install Chula in various ways, depending on what type of
operating system you have, and how your system is configured.
Chula
+++++
Easy Install
^^^^^^^^^^^^
Probably the easiest way to install Chula is to use ``easy_install``.
If your system has Setuptools installed, you can simply do::
sudo easy_install chula
If you do not have ``easy_install`` you can easily get it for Linux,
Mac, and windows from their website: http://pypi.python.org/pypi/setuptools.
Tarball
^^^^^^^
If you don't have Setuptools, or don't want to use ``easy_install`` for
whatever reason, you can download the latest source tarball from
:ref:`downloads` and do the following, where you would replace "a.b.c"
with "|version|" - you get the idea: ::
tar -zxvf Chula-a.b.c.tar.gz
cd Chula-a.b.c
sudo python setup.py install
Windows
^^^^^^^
For you windows cats, you can use the two methods above, or you can
download the windows specific installer found here :ref:`downloads`.
Then just execute the installer, and follow the prompts.
Dependencies
++++++++++++
Mandatory
^^^^^^^^^
If you installed Chula via ``easy_install`` you already have the two
mandatory requirements (Pytz and Simplejson), as they were installed
in automatically. If not, on Ubuntu it's really easy to install
them::
sudo apt-get install python-simplejson
Optional
^^^^^^^^
If you want support for session, you will use one of the following:
Postgresql
~~~~~~~~~~
Install the server and client::
sudo apt-get intall postgresql python-psycopg2
Then download the source Chula tarball from :ref:`downloads` and do::
tar -zxvf path/to/downloaded/tarball
sudo su - postgres
cd /path/to/exploded/tarball
./sql/session/rebuild
This will create a user, database, and schema.
CouchDB
~~~~~~~
Install the server and client::
sudo apt-get intall couchdb python-couchdb
.. External hyperlinks
.. _Python: http://www.python.org
.. _reST: http://www.restructuredtext.org
.. _Simplejson: http://www.undefined.org/python/
Chula-0.7.0/docs/library.rst 0000644 0001750 0001750 00000000171 11370740256 016672 0 ustar jmcfarlane jmcfarlane Modules
=======
.. toctree::
:maxdepth: 2
library/cache
library/collection
library/config
library/error
Chula-0.7.0/docs/library/ 0000755 0001750 0001750 00000000000 11412546122 016132 5 ustar jmcfarlane jmcfarlane Chula-0.7.0/docs/library/collection.rst 0000644 0001750 0001750 00000002206 11370740256 021026 0 ustar jmcfarlane jmcfarlane :mod:`collection`
=================
.. index::
single: collection
.. data:: collection.UNSET
:class:`collection.base.Base` key who's value has not yet been set by the
consumer.
:class:`Base`
+++++++++++++
.. module:: collection.base
.. class:: Base()
Flexible collection that supports both dictionary and attribute
style access.
:class:`Restricted`
+++++++++++++++++++
.. module:: collection.restricted
.. class:: RestrictedCollection()
Collection with constrained keys. This means that every instance
of this class is guaranteed to **only** have the keys defined in
the class. Removal of any of it's keys raise an
:class:`error.RestrictecCollectionKeyRemovalError`, and any key
additions will result in :class:`error.InvalidCollectionKeyError`
being raised. Though the keys in this class are guarenteed, their
values can either be defaulted, or set by the consumer. The
setting of the keys by the consumer is enforced by an
:class:`error.RestrictecCollectionMissingDefaultAttrError`
exception being raised if :const:`collection.UNSET`.
This class inherits from :class:`collection.base.Base`.
Chula-0.7.0/docs/library/cache.rst 0000644 0001750 0001750 00000002763 11370740256 017746 0 ustar jmcfarlane jmcfarlane :mod:`cache` -- Wrapper module for upstream memcache.py
=======================================================
.. index::
single: caching
single: wrapper
pair: upstream; wrapper
pair: wrapper; upstream
pair: caching; objects
.. module:: cache
.. data:: ENCODING
Encoding to be used with memcache keys. Default value is ``ASCII``
.. data:: SANITIZE
Should invalid characters in the key be removed. Default is ``False``
.. class:: Cache(servers)
Takes a list of two element tuples representing a memcached cluster
.. staticmethod:: clean_key(key, sanitize=SANITIZE)
Return a valid key encoded via :const:`ENCODING`. Sanitization
of illegal caracters from the key will be performed if
*sanitize* is ``True``. If the key is too long, or *sanitize*
is ``False`` and illegal characters are found in the key, an
:class:`error.InvalidCacheKeyError` exception will be raised.
.. method:: close()
Close client connection to server.
.. method:: delete(key)
Delete *key* from the cluster, returning ``True`` if deleted,
``False`` if not.
.. method:: get(key)
Fetch the value in memcache associated with *key*.
.. method:: purge(key)
Alias for :meth:`delete`.
.. method:: set(key, value)
Set *value* in the memcache cluster using *key*. Returns
``True`` if successfully persisted, else returns ``False``.
.. method:: stats()
Return a ``list`` of stats per server.
Chula-0.7.0/docs/library/config.rst 0000644 0001750 0001750 00000032447 11370740256 020152 0 ustar jmcfarlane jmcfarlane :mod:`config` -- Chula Configuration
====================================
.. index::
single: config
single: configuration
pair: application; configuration
.. module:: config
Chula applications read all configurations from a configuration file.
This file holds a :class:`Config` object. Here's an example
configuration file::
from chula import config
prod = config.Config()
prod.classpath = 'example.www.controllers'
prod.construction_controller = 'construction'
prod.construction_trigger = '/tmp/chula_example.stop'
prod.debug = False
prod.error_controller = 'error'
prod.session = False
Of the configuration options above, the only two that you need to
understand now are the :attr:`Config.classpath` and
:attr:`Config.error_controller` options.
.. class:: Config()
This class provides an organized structure to hold all supported
chula configuration options. This class inherits from
:class:`collection.restricted.RestrictedCollection`
.. note::
The following two attributes are **mandatory**, meaning your
configuration must provide values for them.
.. attribute:: classpath
The :attr:`classpath` option specifies a package in Python's path that
holds one or more Chula controllers. The convention typically used is
``project.www.controllers``. You can use any location you like, it
just needs to be a valid Python package in Python's path.
Most applications will either be installed or use a symlink expose the
package without actually installing it. Another option that's handy
for development is to alter ``sys.path`` and inject the classpath at
runtime. This is really easy for standalone type apps - but might be
able to do this with Mod_python_ and Mod_WSGI_ too. The important
thing here is that you need to have code that bootstraps Chula (so you
can have a way to alter ``sys.path`` before Chula gets to it.
There are two controllers that are special in that Chula needs to know
exactly where they without any mapping logic. These controllers also
must have a few methods implemented. The location of these
controllers are relative to the defined :attr:`classpath`.
.. attribute:: error_controller
The :attr:`error_controller` specifies the controller to be
called when something goes wrong. Here are a few example use
cases that will result in the error controller being called, and
the corresponding method called:
============= ===========================================================
Method Use case
============= ===========================================================
:meth:`e404` The inbound request does not map to a controller.
:meth:`e500` During the processing of a request, and unhandled exception
is thrown within the controller.
============= ===========================================================
Using an example configuration, if a request is made that cannot
be mapped, Chula will call
``example.www.controllers.error.Error.e404()``. If an unhandled
exception occurs ``example.www.controllers.error.Error.e500()``
will be called. This also means that if a request is made that
cannot be mapped, and something goes wrong inside :meth:`e404`
then both controller methods will actually get called. This
makes it very important that your error controller not be
capable of throwing unhandled exceptions.
If you want to have informative error pages during development,
you'll want to place that code inside your error controller's
:meth:`e500` method that exposes this information. You can find a
very simple implementation that does this inside this
application's error controller and view.
.. note::
The following attributes are all optional.
.. attribute:: add_timer
If :attr:`add_timer` is ``True`` an HTML fragment will be added to the
body of the page, including the following pieces of information:
* Chula adapter being used
* Server hostname
* Chula version
* Processing time (server side)
The fragment will look something like this::
FCGI/WSGI
li83-242
0.5.0
104.279995 ms
This information can be used by client side javascript to display how
fast search results were obtained, for example. If your application
happens to use aggressive caching (like full html caching) the timer
will still be accurate.
.. attribute:: construction_controller
The :attr:`construction_controller` specifies the controller to
be called in the event the application is marked "under
construction". This is optional, but you'll be glad it's there
when you need it. The basic idea of the construction controller
is that all requests get routed to it when a specific file
exists on disk. This means that when you need to take your site
down for maintenance or something you can just *touch* the file
configured via :attr:`construction_trigger`.
The mandatory method that must exist in this controller is
``index()``. For example with the above configuration this would be
``example.www.controllers.construction.Construction.index()``.
.. attribute:: construction_trigger
Fully qualified path to a file on disk. If the file exists, the
construction controller will be called for all requests.
.. attribute:: debug
The :attr:`debug` flag has a default value of ``True`` and is
only used by the Chula queue server. It's main intention is
really to be a hook that your application can use to alter it's
behavior during development.
.. attribute:: local
The Chula configuration class is
:class:`collection.restricted.RestrictedCollection`, meaning
it's a dictionary with a pre defined set of keys. Any key
additions or removals will result in an exception. This is done
to ensure that the configuration is extremely stable. In the
event you would like to store configutation local to your
application, the :attr:`local` attribute is available. This can
hold anything of your choosing.
.. attribute:: log
Fully qualified path to a file on disk. This will will hold
Chula specific logging. The data sent to this file will only be
``warnings`` and above. The default value is
:file:`/tmp/chula.log`. The user running the application must have
write access to this file.
.. attribute:: mapper
Chula currently has support for classpath and regex based url
mappings. The default value is to perform automatic classpath
based mappings.
**Classpath Mapper**
The classpath mapper uses an algorithm to choose the right controller
method for a given url. Here are a few examples of the mapping
algorithm used (assuming the configuration example at the top of this
page):
* http://localhost
1. ``example.www.controllers.home.Home.index()``
With no :const:`env.REQUEST_URI` a direct call to the home
controller can be made. The home controller is named ``home``
and is expected to be at the root of the specified
:attr:`config.Config.classpath`, with a class named ``Home``
and a method named ``index()``.
* http://localhost/products
1. ``example.www.controllers.products.Products.index()``
#. ``example.www.controllers.home.Home.products()``
#. ``example.www.controllers.error.Error.e404()``
When there is a single part this can either be a specified
controller (and an assumed method) or this could be a specified
method on the home controller.
* http://localhost/products/dog
1. ``example.www.controllers.products.Products.Dog()``
#. ``example.www.controllers.error.Error.e404()``
When there are two parts, it must be a specified controller and
method.
* http://localhost/products/dog/small
1. ``example.www.controllers.products.dog.Dog.index()``
#. ``example.www.controllers.error.Error.e404()``
When there are more than two parts, it must be fully qualified,
meaning a package(s), module, and controller.
**Regex Mapper**
In the event you would like to use regex style mappings, set this
value to a tuple of dictionaries containing the regex:controller
mappings. Here is an example regex mapper::
mapper = (
(r'^$', 'home.index'),
(r'^/about/?$', 'home.about'),
(r'^/login/?$', 'auth.login'),
(r'^/logout/?$', 'auth.logout')
)
In the map above, the first argument is a regular expression
(this might actually become a compiled regex in time) that
matches against :const:`env.REQUEST_URI`, and the second argument is a
dot syntax that matches the relative path to a controller
method. The syntax assumes the path is all lower case, but it
will expect all actual controller classes to have an upper cased
first letter, and the parens on the method are implied. So
using the last map in the map above, the actual class/method
used would be: ``example.www.controllers.auth.Auth.logout()``
.. attribute: mqueue_db
Fully qualified path to a directory on disk. When the Chula
queue is used, this directory will be used to hold queue data.
The default value is :file:`/tmp/chula/mqueue`. The user running
the queue must have write access to the directory.
.. attribute:: mqueue_host
Hostname that the Chula queue client and server should use. The
default value is ``localhost``.
.. attribute:: session
if :attr:`session` is ``True`` session is enabled, else not.
Session is enabled by default. See session_ for additional
detail on setup and configuration.
.. attribute:: session_db
Database name used for persisting session. The default value is
``chula_session``.
.. attribute:: session_encryption_key
I think this is a value no longer being used. At one point the
cookie value was being hashed. Currently Chula is directly
using :class:`Cookie.SimpleCookie` and at some point lost support for
hashing the value. This might be added back in at some point.
.. attribute:: session_host
Database host used for persisting session (currently only PostgreSQL)
.. attribute:: session_max_stale_count
The maximum number of session requests allowed to be served
directly from the cache. The default value for this setting is
``10``. When the number of reqeusts exceed this value, the
configured backend will be used. This is designed to increase
the scalability of the session store. Chula session is always
fronted by Memcached, and it's assumed that Memcached is
reasonably reliable, thus with the default configuration the
session backend will only see 10% of the traffic. In the event
of a cache miss, the backend is always used. The only value in
decreasing this value is to reduce the changes of stale data in
the event of a cache failure.
.. attribute:: session_memcache
Memcached cluser to be used for session. This value holds a list of
tuples - each containing a hostname:port syntax. The default value is
``[('localhost:11211', 1)]``. This value is directly fed to
memcache.py which happens to be bundled with Chula.
NOTE: There are plans to add support for libmemcached_
.. attribute:: session_name
The name of the the session cookie to be sent to the browser. The
default value is ``chula-session``.
.. attribute:: session_nosql
HTTP path to a running CouchDB_ installation. If this value is
specified, CouchDB will be used for the session backend instead of
PostgreSQL. The default value is ``None`` - which means PostgreSQL_ is
currently the default backend session store.
.. attribute:: session_password
Password to the PostgreSQL session database
.. attribute:: session_port
Port to the PostgreSQL session database
.. attribute:: session_timeout
Session timeout value
.. attribute:: session_username
Username to the PostgreSQL session database
.. attribute:: strict_method_resolution
If :attr:`strict_method_resolution` is ``True`` the url mapper
will send the request directly to the error controller (:meth:`e404`
method) if a direct map is not possible. So basically the
mappers will not attempt to use the implied ``index()`` method.
This is not true for the homepage, as it's always an implied map
to ``home.index()``. The default value is ``False``.
.. _session: session.html
.. _FastCGI: http://en.wikipedia.org/wiki/FastCGI
.. _Memcached: http://www.memcached.org
.. _Mod_python: http://www.modpython.org
.. _Mod_WSGI: http://code.google.com/p/modwsgi/
.. _MySQL: http://www.mysql.org
.. _PostgreSQL: http://www.postgresql.org
.. _libmemcached: http://code.google.com/p/python-libmemcached/
.. _CouchDB: http://couchdb.apache.org
Chula-0.7.0/docs/library/error.rst 0000644 0001750 0001750 00000011060 11370740256 020022 0 ustar jmcfarlane jmcfarlane :mod:`error` -- Chula exceptions
================================
.. index::
single: exceptions
single: errors
pair: exception; handling
.. module:: error
.. class:: ChulaException(msg=None, append=None)
Chula exception class which adds additional functionality to aid in
efficiently raising custom exceptions.
.. method:: _get_message()
Getter for a message property, to avoid using an attribute named
"message" which will raise deprecation errors in Python-2.6.
Returns self._message
.. method:: _set_message(msg)
Getter for a message property, to avoid using an attribute
named "message" which will raise deprecation errors in
Python-2.6.
.. method:: __str__(append=None)
Return the message itself
.. method:: msg()
When the msg method is not overloaded, return a generic
message
.. class:: ControllerClassNotFoundError(_pkg, append=None)
Exception indicating the requested controller class not found.
Inherits from :class:`ChulaException`
.. class:: ControllerImportError(_pkg, append=None)
Exception while trying to import the controller. Inherits from
:class:`ChulaException`
.. class:: ControllerMethodNotFoundError(_pkg, append=None)
Exception indicating the requested controller method not found.
Inherits from :class:`ChulaException`
.. class:: ControllerModuleNotFoundError(_pkg, append=None)
Exception indicating the requested module method not found.
Inherits from :class:`ChulaException`
.. class:: ControllerMethodReturnError()
Exception indicating that a controller method is returning
``None``, which is probably not on purpose. It's true that we do
cast all output as a string, thus 'None' is technically valid, it's
most likely that the controller method simply forgot to return.
This will save time by pointing this out. If you really need to
return ``None``, then return: 'None'. Inherits from
:class:`ChulaException`
.. class:: ControllerRedirectionError()
Exception indicating that the controller was unable to perform the
requested redirect. Inherits from :class:`ChulaException`
.. class:: InvalidAttributeError(key, append=None)
Exception indicating an invalid attribute was used. Inherits from
:class:`ChulaException`
.. class:: InvalidCacheKeyError(key, append=None)
Exception indicating an invalid key was used against a cache
source. Inherits from :class:`ChulaException`
.. class:: InvalidCollectionKeyError(key, append=None)
Exception indicating an invalid key was used against a restricted
collection class. Inherits from :class:`ChulaException`
.. class:: MalformedConnectionStringError()
Exception indicating that the database connection string used is
invalid. Inherits from :class:`ChulaException`
.. class:: MalformedPasswordError()
Exception indicating that the password used does not meet minimum
requirements (aka: isn't strong enough). Inherits from
:class:`ChulaException`
.. class:: TypeConversionError(_value, _type, append=None)
Exception indicating that the requested data type conversion was
not possible. Inherits from :class:`ChulaException`
.. class:: UnsupportedDatabaseEngineError(engine, append=None)
Exception indicating a requst for an unsupported database engine
Inherits from :class:`ChulaException`
.. class:: UnsupportedMapperError(_pkg, append=None)
Exception indicating an invalid mapper configuration Inherits from
:class:`ChulaException`
.. class:: UnsupportedUsageError()
Exception indicating the chula api is being misused. Inherits
from :class:`ChulaException`
.. class:: MissingDependencyError(_pkg, append=None)
Exception indicating a required dependency of chula is either
missing or of an incompatible version. Inherits from
:class:`ChulaException`
.. class:: RestrictecCollectionKeyRemovalError(key, append=None)
It is illegal to remove a key from a RestrictedCollection object.
Inherits from :class:`ChulaException`
.. class:: RestrictecCollectionMissingDefaultAttrError(key, append=None)
Exception indicating that a restricted attribute was not given a
default value. Inherits from :class:`ChulaException`
.. class:: SessionUnableToPersistError()
Chula is unable to persist either to PostgreSQL or Memached.
Inherits from :class:`ChulaException`
.. class:: WebserviceUnknownTransportError(key, append=None)
Exception indicating that the specified webservice transport is
either unknown or unsupported. Inherits from
:class:`ChulaException`
Chula-0.7.0/docs/changelog.rst 0000644 0001750 0001750 00000022462 11412545770 017165 0 ustar jmcfarlane jmcfarlane .. _downloads:
=======================
Downloads/Release Notes
=======================
Chula v0.8.0 (dev)
++++++++++++++++++
*Still under development*
:Source: http://github.com/jmcfarlane/chula
Chula v0.7.0
++++++++++++
*Released 2010-06-29*
* Added support for native couchdb sorting
* Removed support for app level sorting of couchdb documents
:Documentation: `Chula-0.7.0 0.7.0/>`_
:Download: ``_
:Download: ``_
:Download: ``_
:Download: ``_ (unsupported)
:Download: ``_ (unsupported)
:Download: ``_
:Source: http://github.com/jmcfarlane/chula/tree/v0.7.0
Chula v0.6.0
++++++++++++
*Released 2010-05-07*
* Updated the manifest to include apps, and test cases
* Added support for Google App Engine.
* Added ability to fetch data from CouchDB using views
* Removed dependency on pytz.
* Removed usage of :func:`socket.gethostname`, which can have a
negative impact on performance (especially in heavily threaded
applications). This also makes it possible to use Chula in
environments that do not have access to :mod:`socket`.
* When looking for :mod:`simplejson`, also try using the copy that
ships with Django.
* Updated the logger to not use a file handler when
:attr:`config.Config.log` is ``None``.
* Fixed defect in Couchdb connection cache.
* Performance improvements to :mod:`nosql.couch`
:Documentation: `Chula-0.6.0 0.6.0/>`_
:Download: ``_
:Download: ``_
:Download: ``_
:Download: ``_ (unsupported)
:Download: ``_ (unsupported)
:Download: ``_
:Source: http://github.com/jmcfarlane/chula/tree/v0.6.0
Chula v0.5.0
++++++++++++
*Released 2010-02-22*
* Added support for Setuptools. This results in Chula being
installable via ``easy_install``.
* Added a bit more documentation on how to install Chula.
:Documentation: `Chula-0.5.0 0.5.0/>`_
:Download: ``_
:Download: ``_
:Download: ``_
:Download: ``_ (unsupported)
:Download: ``_ (unsupported)
:Download: ``_
:Source: http://github.com/jmcfarlane/chula/tree/v0.5.0
Chula v0.4.0
++++++++++++
*Released 2010-02-10*
* Added simple wrapper around couchdb-python
* Added support for couchdb session store. This means you now can
choose between PostgreSQL/Memcached or CouchDB/Memcached.
* Added singleton decorator
* Added initial logging support
* Added a regex style url mapper. This means you can now choose
between automatic class mapping and hand crafted mappings via regular
expressions (this should be similar to Django style routing).
* Added (initial) documentation using Sphinx (not yet published)
* Updated memcache.py to version 1.45
* Fixed regression in chula.www.cookie where the cookie domain was
getting prefixed with "." once for every cookie - oops.
* Refactored session into a package. When the couchdb backend was
added, not all of the failover logic was being implemented. To clean
things up properly the session logic had to be abstracted away from
the backends. Now there is a single session class that supports n
number of backends that all use the same interface.
* Moved third party libs (selenium, memcache) into chula.vendor
:Download: `Chula-0.4.0.tar.gz `_
:Documentation: `Chula-0.4.0 0.4.0/>`_
:Source: http://github.com/jmcfarlane/chula/tree/v0.4.0
Chula v0.3.0
++++++++++++
*Released 11/03/2009*
* Improved cookie handling (better RFC compliance)
* worked around Python-2.6 deprecation of Exception.message
* More unit and bat tests
* Enforced str key types with memcached
* Disabled memcached key sanitization by default
:Download: `Chula-0.3.0.tar.gz `_
:Source: http://github.com/jmcfarlane/chula/tree/v0.3.0
Chula v0.2.0
++++++++++++
*Released 09/27/2009*
* Added chula.data.str2unicode
* Added initial bat tests
* Improved handling of exceptions during controller import
* Improved chula.mail to properly handle unicode
* Moved unit tests out of the source tree
* Added support for Selenium tests
:Download: `Chula-0.2.0.tar.gz `_
:Source: http://github.com/jmcfarlane/chula/tree/v0.2.0
Chula v0.1.0
++++++++++++
*Released 06/29/2009*
* Fixed corner case in FieldStorage array structures
* Fixed defect in chula.date.str2date() with UTC +n
* Fixed run_tests so it works without Chula being installed
* Improved chula.data.str2date to support years 1000 to 2999 (jmathai).
* Improved chula.data.str2date to support a unix timetamp
* Added two sample applications
* Added documentation (one of the sample apps)
* Added support for custom queue messages
* Minor tweaks to reduce memory consumption
* Made session optional, but enabled by default
:Download: `Chula-0.1.0.tar.gz `_
:Source: http://github.com/jmcfarlane/chula/tree/v0.1.0
Chula v0.0.6
++++++++++++
*Released 04/11/2009*
* Added support for FasgCGI
* Added an ASCII transport to chula.webservice
* Added a webservice decorator: chula.webservice.expose
* Added testutils module
* Fixed defect where error controller not found when using controller packages
* Fixed defect in data.commaify with less than 2 decimals
* Improved the timer to not break xhtml compliance
:Download: `Chula-0.0.6.tar.gz `_
:Source: http://github.com/jmcfarlane/chula/tree/v0.0.6
Chula v0.0.5
++++++++++++
*Released 12/11/2008*
* Improved chula.collection adding an add() method
* Improved chula.webservice removing dependency on mod_python
* Improved chula.www.cookie removing dependency on mod_python
* Improved env to hold GET, POST (previously only a combo)
* Improved support for copy.deepcopy on chula.collection
* Improved error.e404 used when method resolution fails
* Improved "under construction" flow by removing dependency on session
* Improved chula.queue to keep processed/failed messages for later review
* Changed behavior to always call the error controller on exception.
This is slightly less convienent, but encourages better testing of
error handling code paths for apps using Chula.
* Changed behavior to call e404 when the controller requested isn't found
* Added initial support for WSGI
* Added initial suport for the Python simple_server
:Download: `Chula-0.0.5.tar.gz `_
:Source: http://github.com/jmcfarlane/chula/tree/v0.0.5
Chula v0.0.4
++++++++++++
*Released 8/19/2008*
* Changed dependency checking to be further down the stack
* Cleaned up directory structure of source tree a little
* Improved installer to use distro specific locations
* Promoted chula.collection into a package
* Promoted chula.db into a package (much better now)
* Fixed defect in chula.collection when copy.deepcopy is used
* Wired up specified error controller (previously unused)
* Added chula.collection.UboundCollection
* Added chula.data.isregex and chula.db.cregex
* Added chula.mail
* Added chula.system
* Added support for an "under construction" controller
* Added support for sqlite to chula.db.datastore
* Added tcp based message queue (working, but very much not ready to be used)
:Download: `Chula-0.0.4.tar.gz `_
:Source: http://github.com/jmcfarlane/chula/tree/v0.0.4
Chula v0.0.3
++++++++++++
*Released 6/15/2008*
* Added module for working with caching services, currently only
Memcache is supported.
* Added support for controllers inside of packages, previously only a
single namespace was supported. Note that this feature is probably
going to be moved into a FileMapper so the StandardMapper can move to
more of a map based model.
* Added render method to pager.Pager for those that want to subclass the
output. The base method simply returns the pager unmodified.
* Remove "danger" logic from db.py as it's best left up to the
consumer to handle that type of logic. It was poorly implemented
anyway :)
:Download: `Chula-0.0.3.tar.gz `_
:Source: http://github.com/jmcfarlane/chula/tree/v0.0.3
Chula v0.0.2
++++++++++++
*Released 1/21/2008*
* Fixed defect where env.host is None
* Fixed defect where env.protocol_type is None
* Fixed defect where request_uri of: "/?" was loading e404
* Fixed defect where session not deleted on logout
* More gracefully handle clients lacking cookie support
* Allow the controller to have direct access to the cookie object.
This provides access to it's destroy() method, useful for logout
pages.
* Tweaks to improve support for static content
* Improved reliability/accuracy of session
* Added timer to html output (turn off with config.add_timer)
* Handle exception on premature client disconnection
:Download: `Chula-0.0.2.tar.gz `_
:Source: http://github.com/jmcfarlane/chula/tree/v0.0.2
Chula v0.0.1
++++++++++++
*Released 12/14/2007*
* Initial release
:Download: `Chula-0.0.1.tar.gz `_
:Source: http://github.com/jmcfarlane/chula/tree/v0.0.1
Chula-0.7.0/docs/getting_started.rst 0000644 0001750 0001750 00000031527 11370740256 020426 0 ustar jmcfarlane jmcfarlane ===============
Getting Started
===============
.. toctree::
:maxdepth: 2
install
Terminology
+++++++++++
Welcome to Chula. Let's go thru a few things before you get started
building your first app. Chula is a simple toolkit that is based on
the MVC_ pattern. From now on we'll use the terms "*model*",
"*view*", and "*controller*" when describing things. Here's a brief
summary of what these terms as they relate to Chula:
=========== ===================================================================
Term Description
=========== ===================================================================
Model The logic and data of an application. These are usually
standard Python classes. They do work, implement
algorithms, and hold data.
View The view is responsible for presentation. Examples of
this would be:
* Mako_
* Cheetah_
* reST_ (restructured text)
Controller The controller is the main class responsible for coordinating
everything. The controller is responsible for capturing
user input, calling the model for processing, invoking the
view, passing the model to the view, and returning
view's output to the client.
=========== ===================================================================
Application structure
+++++++++++++++++++++
Here is an example file structure of a bare bones Chula application::
|-- example
| |-- __init__.py
| |-- configuration.py
| `-- www
| |-- __init__.py
| `-- controllers
| |-- __init__.py
| |-- error.py
| `-- home.py
`-- webserver
In the list of files above there is a Python package_ named ``example``
that holds the entire application. Inside it there are two
controllers, a configuration, and a webserver. The webserver is not
specific to Chula really, but rather a quick and dirty way to launch a
Chula application without needing a webserver installed and
configured. Technically speaking this is all you need to run a Chula
application.
Run a sample Chula application
++++++++++++++++++++++++++++++
If you would like to try the above application right now, you'd type
this in your terminal::
cd wherever_you_unpacked_the_chula_tarball
./apps/basic/webserver
At this point you should be able to point your browser at
http://localhost:8080 and browse a hello world application that ships
with Chula. The actual purpose of the application is to serve as a
way to run BAT_ tests, but it's useful for this purpose as well.
Hit :kbd:`Control-c` to stop the server, and let's move on.
Create your own hello world application
+++++++++++++++++++++++++++++++++++++++
Directory structure
~~~~~~~~~~~~~~~~~~~
The structure we want so far will support view templates, web server
configuration, client side static files, and a python package::
cd Desktop
mkdir -p Myapp/config # Web server configs
mkdir -p Myapp/myapp # Python package
mkdir -p Myapp/view # View emplates
mkdir -p Myapp/www # Static files (client side)
Make ``myapp`` an actual python package::
touch Myapp/myapp/__init__.py
Configuration
~~~~~~~~~~~~~
Create the following file in :file:`Myapp/myapp/configuration.py`::
from chula import config
# Development configuration
dev = config.Config()
dev.classpath = 'myapp.controllers'
dev.construction_controller = 'error'
dev.construction_trigger = '/tmp/myapp.stop'
dev.debug = True
dev.error_controller = 'error'
dev.session = False
Controllers
~~~~~~~~~~~
Create a package called ``controllers`` to hold all app controllers,
this makes it easy to distinguish controllers from your other python
modules you might have::
mkdir Myapp/myapp/controllers
touch Myapp/myapp/controllers/__init__.py
Create the **mandatory** ``error`` controller configured previously by creating :file:`Myapp/myapp/controllers/error.py` ::
from chula.www import controller
class Error(controller.Controller):
def index(self):
return 'Sorry, the site is down for maintenance'
def e404(self):
return 'Page not found'
def e500(self):
return 'Trapped Error: %s' % self.model.exception.exception
Now create a controller that will serve as the homepage, as well as a
blog or something, :file:`Myapp/myapp/controllers/home.py` ::
from chula.www import controller
class Home(controller.Controller):
def index(self):
return 'Hello world'
def blog(self):
return 'This is my blog'
At this point we have a full Chula application, but we don't have a
way to run it. For now, let's create a standalone web server script
for testing purposes. Next, we'll actually wire up the application
against a few different web servers.
Test server
~~~~~~~~~~~
Create :file:`Myapp/webserver.py` ::
import os
import sys
from wsgiref.simple_server import make_server
from chula.www.adapters.wsgi import adapter
# Expose the myapp python package, as it's not "installed"
sys.path.insert(0, os.getcwd())
# Import my configuration we created above
from myapp import configuration
# Define a wsgi application, passing in our (dev) configuration
@adapter.wsgi
def application():
return configuration.dev
# Setup a simple server using the proxy app and it's configuration
port = 8080
httpd = make_server('', port, application)
try:
print 'Starting server on: http://localhost:%s' % port
httpd.serve_forever()
except KeyboardInterrupt:
sys.exit()
Test it!
~~~~~~~~
Let's try out what we have so far::
cd Myapp
python webserver.py
At this point you should be able to browse the following urls:
#. http://localhost:8080
#. http://localhost:8080/home/blog
Hit :kbd:`Control-c` to stop the server.
Add env vars
~~~~~~~~~~~~
Let's add a page that's a little bit more usefull. This one will
generate an HTML table of the environment variables. This page will
also use Mako_ for the view.
Update controller
^^^^^^^^^^^^^^^^^
Let's update our ``home`` controller
to look like this, :file:`Myapp/myapp/controllers/home.py` ::
from chula.www import controller
# This is a new import
from mako.template import Template
class Home(controller.Controller):
def index(self):
return 'Hello world'
def blog(self):
return 'This is my blog'
# This is the new method
def envinfo(self):
# Add env variables to the model
self.model.env = self.env
# Load our Mako template
view = Template(filename='view/envinfo.tmpl')
# Return the rendered template, passing in our model
return view.render(model=self.model)
Mako template
^^^^^^^^^^^^^
Now let's create the mako template referenced above,
:file:`Myapp/view/envinfo.tmpl` ::
Env Variables
Environment Variables
Key
Value
%for key, value in model.env.iteritems():
${key}
${value}
%endfor
Try it!
^^^^^^^
Let's see what this looks like now::
cd Myapp
python webserver.py
Now browse to http://localhost:8080/envinfo and you should see a table
of environment variables. It's a little hard to read because the keys
are not sorted, but that's because keys in the standard dict are not
sorted. I leave the sorting issue as an excercise for the reader :)
Hit :kbd:`Control-c` to stop the server.
Web server integration
+++++++++++++++++++++++
Chula integrates with WSGI_, Mod_python_, and FastCGI_. Let's go
thru how you would integrate your hello world application with each of
these.
Nginx via FastCGI
~~~~~~~~~~~~~~~~~
The first step in FastCGI_ integration, is to create the application
server that Nginx_ will sent requests to. For this example, we'll use
a unix domain socket, rather than TCP/IP for connectivity between the
two.
FastCGI process
^^^^^^^^^^^^^^^
Create :file:`Myapp/fastcgi.py` ::
try:
from flup.server.fcgi_fork import WSGIServer
except ImportError:
from chula.vendor.fcgi import WSGIServer
print "Unable to import flup.server.fcgi import WSGIServer"
print " >>> Falling back on old version available in Chula"
from chula.www.adapters.fcgi import adapter
from myapp import configuration
@adapter.fcgi
def application():
return configuration.dev
# Start the server which will handle calls from the webserver
WSGIServer(application, bindAddress='/tmp/myapp.socket').run()
Start up the FastCGI_ process::
python Myapp/fastcgi.py
Make sure Nginx has permissions to write to the socket::
chmod o+w /tmp/myapp.socket
TODO: Provide an example init script to properly startup the socket,
setting permissions and what not.
Nginx config
^^^^^^^^^^^^
Configure Nginx_ to proxy application requests to our
application. Add this to the ``server`` block of your Nginx_
configuration::
# Send all requests without a file extension to myapp:
location ~ ^([a-z/_])+$ {
# This is needed when using Ubuntu
include /etc/nginx/fastcgi_params;
# FastCGI parameter settings
fastcgi_read_timeout 3m;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SERVER_ADMIN NA;
fastcgi_param SERVER_SIGNATURE nginx/$nginx_version;
# The path to our running unix domain socket
server unix:/tmp/myapp.socket;
}
Restart Nginx_ ::
sudo /etc/init.d/nginx restart
Try it!
^^^^^^^
Now you should be able to hit: http://your-server/home/blog
WSGI via Mod_WSGI
~~~~~~~~~~~~~~~~~
Mod_WSGI_ is the best choice if you want to run your app on Apache_.
This configuration also happens is a little easier to setup.
Register app
^^^^^^^^^^^^
When running applications under Apache, the Python interpreter is
owned by ``nobody`` or ``apache`` or something, thus you need to
register your application so that it's in python's ``path``. The
easiest way to do this is via a symlink. You'll use something similar
to one of these (but specific to your computer's setup)::
# Gentoo
sudo ln -s /path/to/Myapp/myapp /usr/lib/python2.6/site-packages/myapp
# Ubuntu
sudo ln -s /path/to/Myapp/myapp /usr/local/lib/python2.6/dist-packages/myapp
WSGI handler
^^^^^^^^^^^^
Create :file:`Myapp/wsgi.py`, which will be loaded by Mod_WSGI_ ::
from chula.www.adapters.wsgi import adapter
from myapp import configuration
@adapter.wsgi
def application():
return configuration.dev
Apache config
^^^^^^^^^^^^^
Add this to your ``VirtualHost`` ::
WSGIScriptAliasMatch ^([a-z/_])+$ /full/path/to/Myapp/wsgi.py
Try it!
^^^^^^^
Restart Apache::
sudo /etc/init.d/apache restart
Now you should be able to hit: http://your-server/home/blog
Apache via Mod_python
~~~~~~~~~~~~~~~~~~~~~
Mod_PYTHON_ was the first way to run Python applications under Apache
with excellent performance. It's still awesome, though Mod_WSGI_ has
superceeded it.
Register app
^^^^^^^^^^^^
When running applications under Apache, the Python interpreter is
owned by ``nobody`` or ``apache`` or something, thus you need to
register your application so that it's in python's ``path``. The
easiest way to do this is via a symlink. You'll use something similar
to one of these (but specific to your computer's setup)::
# Gentoo
sudo ln -s /path/to/Myapp/myapp /usr/lib/python2.6/site-packages/myapp
# Ubuntu
sudo ln -s /path/to/Myapp/myapp /usr/local/lib/python2.6/dist-packages/myapp
Mod_python handler
^^^^^^^^^^^^^^^^^^
Create :file:`Myapp/myapp/mod_python.py`, which will be loaded by Mod_PYTHON_ ::
from chula.www.adapters.mod_python import adapter
from myapp import configuration
@adapter.handler
def application():
return configuration.dev
Apache config
^^^^^^^^^^^^^
Update your apache ``VirtualHost`` to have::
# Send all application requests to a stub with a ".py" extension
AliasMatch ^([a-z/_])+$ PLACEHOLDER.py
PythonDebug On
# Send requests to *.py to myapp's handler
AddHandler mod_python .py
PythonHandler myapp.mod_python
Try it!
^^^^^^^
Restart Apache::
sudo /etc/init.d/apache restart
Now you should be able to hit: http://your-server/home/blog
What's next
+++++++++++
When creating your own application is's going to be important that you
understand the configuration options available. You'll also want to
learn more about featues available, and how to use them. You can find
detail on configuration `here `_.
.. _Apache: http://www.apache.org
.. _BAT: http://en.wikipedia.org/wiki/Acceptance_testing
.. _Cheetah: http://www.cheetahtemplate.org
.. _FastCGI: http://en.wikipedia.org/wiki/FastCGI
.. _Mako: http://www.makotemplates.org
.. _Mod_python: http://www.modpython.org
.. _Mod_WSGI: http://code.google.com/p/modwsgi/
.. _MVC: http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
.. _Nginx: http://nginx.org
.. _package: http://docs.python.org/tutorial/modules.html#packages
.. _reST: http://www.restructuredtext.org
.. _WsGI: http://www.wsgi.org
Chula-0.7.0/docs/_static/ 0000755 0001750 0001750 00000000000 11412546122 016114 5 ustar jmcfarlane jmcfarlane Chula-0.7.0/docs/_static/flow.dot 0000644 0001750 0001750 00000002226 11370740256 017604 0 ustar jmcfarlane jmcfarlane digraph chula {
ADAPTER [label="Chula Adapter" style="filled" fillcolor="yellow"]
apache [label="Apache"]
browser [label="Web Browser" style=filled fillcolor=orange]
cheetah [label="Cheetah"]
config [label="Chula Config" style=filled fillcolor="#91cdfb"]
controller [label="Chula Controller" style=filled fillcolor=green]
data [label="Your data"]
fastcgi [label="FastCGI"]
kid [label="Kid"]
lighttpd [label="Lighttpd"]
mako [label="Mako"]
memcache [label="Memcached"]
model [label="Chula Model" style="filled" fillcolor="#ffcd85"]
mod_python [label="Mod_python"]
nginx [label="Nginx"]
postgres [label="PostgreSQL"]
session [label="Session Cluster"]
wsgi [label="WSGI"]
/* Controller */
controller->model
controller->session
controller->cheetah
controller->mako
controller->kid
/* Web Servers */
HTTP->apache->ADAPTER
HTTP->lighttpd->ADAPTER
HTTP->nginx->ADAPTER
/* Adapter */
ADAPTER->mod_python->controller
ADAPTER->wsgi->controller
ADAPTER->fastcgi->controller
/* Session */
session->postgres
session->memcache
/* Glue */
model->data
browser->HTTP
model->controller
config->ADAPTER
}
Chula-0.7.0/docs/index.rst 0000644 0001750 0001750 00000001122 11370740256 016332 0 ustar jmcfarlane jmcfarlane .. Chula documentation master file, created by
sphinx-quickstart on Thu Dec 10 17:52:47 2009.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to Chula's documentation!
=================================
.. toctree::
:maxdepth: 2
about
getting_started
session
Download Chula
==============
.. toctree::
:maxdepth: 3
changelog
Module Library
==============
.. toctree::
:maxdepth: 1
library
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
Chula-0.7.0/docs/about.rst 0000644 0001750 0001750 00000010767 11370740256 016354 0 ustar jmcfarlane jmcfarlane ===========
About Chula
===========
History
+++++++
Chula is written by John McFarlane (aka me). When I first wanted to learn
Python I started a project named *Apple*. At the time there were lots
of frameworks for building web applications with Python, but I was
interested in learning Python so it seemed more fun to make my own.
Additionally I was surprised by the complexity of other frameworks. I
was looking for something a bit simpler.
I hacked on Apple for a few years, and then decided to start over and
try to improve things based on what I had learned - 3 months later I
released the first version of Chula. Since that time I've tried to
improve things and add features as needed, but I never lost sight of
it's main purpose: to be a vehicle for me to have fun and learn stuff.
If you're really wanting to build the next killer application I'd
prolly recommend using `Django `__. If
you're looing for something smaller or even just something *different*
then give Chula a try :)
Features
++++++++
* Web servers: Most of the common setups are supported (Mod_Python_,
Mod_WSGI_, and FastCGI_).
* Session: Uses both Memcached_ and PostgreSQL_ for cluster safe
storage that scales pretty well.
* Message queue: Support for asynchronous processing of messages
* Typical stuff: Environment, GET and POST variables
* Speed: Chula seems to perform pretty well
Dependencies
++++++++++++
Chula depends on the following packages, some of which are optional
depending on configuration:
Mandatory
~~~~~~~~~
#. Python_ 2.6 (2.5 can work with minor changes, see Roadmap_)
#. Simplejson_
Optional
~~~~~~~~
* CouchDB_ and the couchdb-python_ driver
* Flup_ (If using FastCGI this is recommended, but still optional)
* Mako_ (Optional but recommended)
* Memcached_
* PostgreSQL_ and the Psycopg2_ driver
* Web server: Nginx_, Apache_, etc.
If you intend on enabling support for session, you will need
Memcached, and either PostgreSQL or CouchDB and their respective
drivers. You can learn more about session `here `_.
Source code
+++++++++++
Chula uses the Git_ version control system. The official Chula repository
can be found on Github_.
Issue tracker
+++++++++++++
Chula uses the issue tracker that's integrated with Github_. If you
find defects or have ideas for improvement please feel free to file
issues. In the event Chula becomes more popular, a more sophisticated
tracker will be used.
The link to the Github tracker is here:
http://github.com/jmcfarlane/chula/issues
Release cycle
+++++++++++++
Generally there are about 4 releases a year
Roadmap
+++++++
The roadmap right now is pretty small. Here are the features I'm
currently thinking about:
1. Profiling - profilng of both Chula and apps running on it
#. Support for MySQL_ based session. Currently only PostgreSQL_ and
CouchDB are supported. With either backend Memcached_ will continue to be
used.
#. Consider adding back support for Python-2.5. This wouldn't be too
difficult - just need to change how the logging singleton works.
The other complication would be managing early versions of 2.5 that
did not include httplib2, as this is needed by couchdb (if that
session backend is used). To further complicate things, the
version of httplib2 available to most distros [that ship such an
old version of Python] is not compatible with couchdb-python_.
Who's using it
++++++++++++++
I don't actually know of anyone that's using it. If you're using it,
let me know.
.. Internal hyperlinks
.. _About: about.html
.. _`Getting Started`: getting_started.html
.. External hyperlinks
.. _Apache: http://www.apache.org
.. _Cheetah: http://www.cheetahtemplate.org
.. _CouchDB: http://couchdb.apache.org
.. _couchdb-python: http://code.google.com/p/couchdb-python/
.. _FastCGI: http://en.wikipedia.org/wiki/FastCGI
.. _Flup: http://trac.saddi.com/flup
.. _Git: http://www.git.cz
.. _Github: http://www.github.com/jmcfarlane/chula
.. _Mako: http://www.makotemplates.org
.. _Memcached: http://www.memcached.org
.. _Mod_python: http://www.modpython.org
.. _Mod_WSGI: http://code.google.com/p/modwsgi/
.. _MVC: http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
.. _MySQL: http://www.mysql.org
.. _Nginx: http://nginx.org
.. _package: http://docs.python.org/tutorial/modules.html#packages
.. _PostgreSQL: http://www.postgresql.org
.. _Psycopg2: https://dndg.it/cgi-bin/gitweb.cgi?p=public/psycopg2.git
.. _Python: http://www.python.org
.. _reST: http://www.restructuredtext.org
.. _Simplejson: http://www.undefined.org/python/
Chula-0.7.0/docs/session.rst 0000644 0001750 0001750 00000006773 11370740256 016727 0 ustar jmcfarlane jmcfarlane =======
Session
=======
Chula includes session support via cookies and backend servers.
Currently there are three supported backends:
1. Memcached
2. PostgreSQL
3. CouchDB
Via configuration you can choose between PostgreSQL or CouchDB as the
main session store - Memcached is always used as a cache.
Cluster Safe
++++++++++++
Because local storage is not used, Chula is has cluster safe session.
Basically this means that you can fire up multiple instances of your
application and they all share session. This also means you don't
have to use `sticky sessions` in your load balancer configuration.
Scalable
++++++++
Chula maintains session in Memcached_ backed by a persistent data
store. Because Memcache is reasonably reliable, only a percentage of
session requests are actually sent to the backend. The default
configuration is to update the backend every 10 requests. This means
the session backend (which is slower than cache) is only serving 10%
of the actual traffic. The frequency of backend updates is
configurable via :attr:`config.Config.session_max_stale_count`, and
the backend is always consulted in the event of a cache miss.
A current limitation of the session store is that it does not use
connection pooling. This can optionally be added by fronting your
PostgreSQL server with pgpool_. When CouchDB is used as the backend,
connection pooling isn't relevent as it uses HTTP.
Native Storage
++++++++++++++
Chula stores your session values as pickle_'d strings (via cPickle) thus
you can store any values that are serializeable by cPickle.
Maintenance
+++++++++++
Chula does not clean up all PostgreSQL based sessions. You will
likely want to configure a cron job to periodically delete stale
sessions from the database. When CouchDB is used, the sessions are
sharded by year/month. This allows you to easily purge off old
sessions by year/month.
Setup
+++++
PostgreSQL
----------
In order to use Chula session you will need to create the database
used by the backend. Use the following command to create them::
user# sudo su - postgres ## Or whatever user PostgreSQL is running as
postgres# cd wherever_you_unpacked_the_chula_tarball
postgres# ./sql/session/reload
The above command will create a user named ``chula`` and a database
named ``chula_session``. Next you'll need to make sure your server is
configured to support requests over TCP/IP. Usually this is done by
setting ``listen_addresses = 'localhost'`` or another hostname in
``postgresql.conf``.
Assuming you're connecting to the server running locally, you're all
done!
If you're connecting to a remote server, you need to add the hostname
in your configuration via :attr:`config.Config.session_host`. If you
want to use a different user/password/port/server you are free to do
so.
CouchDB
-------
You wil need to configure :attr:`config.Config.session_nosql` with the
full HTTP path to your CouchDB server. If this is a local install,
you'd set the value to http://localhost:5984. Don't worry about the
database, as it wil be created automatically on demand.
Memcached
---------
You need to configure your cluster information via
:attr:`config.Config.session_memcache`. If you're using a local
install of Memcached you can just take the defaults, else configure it
with something like this::
[('host1:11211', 1), ('host2:11211', 1), ('host3:11211', 1)]
Reference
+++++++++
For more detail on Chula configuration in general, see
:mod:`config`.
.. _pgpool: http://pgpool.projects.postgresql.org/
.. _pickle: http://docs.python.org/library/pickle.html
Chula-0.7.0/docs/template.txt 0000644 0001750 0001750 00000000652 11370740256 017054 0 ustar jmcfarlane jmcfarlane =======================
This is the page header
=======================
Main text under the header
This is the first main header
+++++++++++++++++++++++++++++
Text under the first section
The second header
-----------------
Text under the second section
The third header
~~~~~~~~~~~~~~~~
Text under the third header
Here's a list, that *includes* a link:
1. `Getting Started`_ is a linked page
2. A another element
Chula-0.7.0/LICENSE 0000644 0001750 0001750 00000043131 11370740256 014554 0 ustar jmcfarlane jmcfarlane GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.
Chula-0.7.0/chula/ 0000755 0001750 0001750 00000000000 11412546122 014632 5 ustar jmcfarlane jmcfarlane Chula-0.7.0/chula/db/ 0000755 0001750 0001750 00000000000 11412546122 015217 5 ustar jmcfarlane jmcfarlane Chula-0.7.0/chula/db/functions.py 0000644 0001750 0001750 00000013412 11370740256 017611 0 ustar jmcfarlane jmcfarlane """Functions to make working with databases easier"""
import re
from chula import data, error
def cbool(input_):
"""
Returns a formatted string safe for use in SQL. If None is passed, it
will return 'NULL' so as to insert a NULL value into the database.
@param input_: String to be cleaned
@type input_: String
@return: String I{TRUE/FALSE}, or 'NULL'
>>> print 'SET active = %s;' % cbool(True)
SET active = TRUE;
"""
if input_ in [None, '']:
return 'NULL'
input_ = str(input_).lower()
if input_ in data.TRUE:
return 'TRUE'
elif input_ in data.FALSE:
return 'FALSE'
else:
raise error.TypeConversionError(input_, 'sql boolean')
def cdate(input_, doquote=True, isfunction=False):
"""
Returns a formatted string safe for use in SQL. If None or an empty
string is passed, it will return 'NULL' so as to insert a NULL value
into the database.
B{Todo:}
I{This function needs to be able to receive datetime.datetime types too.}
@param input_: Date to be cleaned
@type input_: String
@return: String, or 'NULL'
>>> print 'SET updated = %s;' % cdate('1/1/2005')
SET updated = '1/1/2005';
>>> print 'SET updated = %s;' % cdate('now()', isfunction=True)
SET updated = now();
"""
if input_ in [None, '', 'NULL']:
return 'NULL'
elif isfunction:
return input_
else:
input_ = str(input_)
if data.isdate(input_):
if doquote:
input_ = data.wrap(input_, "'")
else:
raise error.TypeConversionError(input_, 'sql date')
return input_
def cfloat(input_):
"""
Returns a formatted string safe for use in SQL. If None is passed, it
will return 'NULL' so as to insert a NULL value into the database.
@param input_: Float to be cleaned
@type input_: Anything
@return: Float, or 'NULL'
>>> print 'WHERE field = %s;' % cfloat("45")
WHERE field = 45.0;
"""
# Check if the data passed is a NULL value
if input_ is None or str(input_).lower() == 'null' or input_ == '':
return 'NULL'
elif isinstance(input_, float):
return input_
try:
return float(input_)
except:
raise error.TypeConversionError(input_, 'sql float')
def cint(input_):
"""
Returns a formatted string safe for use in SQL. If None is passed, it
will return 'NULL' so as to insert a NULL value into the database.
@param input_: Integer to be cleaned
@type input_: Anything
@return: Integer, or 'NULL'
>>> print 'WHERE field = %s;' % cint("45")
WHERE field = 45;
"""
# Check if the data passed is a NULL value
if input_ is None or str(input_).lower() == 'null' or input_ == '':
return 'NULL'
elif isinstance(input_, int):
return input_
try:
return int(input_)
except:
raise error.TypeConversionError(input_, 'sql float')
def cregex(input_, doquote=True):
"""
Returns a regular expression safe for use in SQL. If None is
passed if will raise an exception as None is not a valid regular
expression. The intented use is with regex based SQL expressions.
@param input_: Value to evaluate
@type input_: str
@param doquote: I{OPTIONAL}: Wrapped in single quotes, defaults to B{True}
@type doquote: bool
@return: str
"""
if data.isregex(input_):
if doquote:
return data.wrap(input_, "'")
else:
return input_
else:
raise error.TypeConversionError(input_, 'sql regex')
def cstr(input_, doquote=True, doescape=True):
"""
Returns a formatted string safe for use in SQL. If None is passed, it
will return 'NULL' so as to insert a NULL value into the database.
Single quotes will be escaped.
@param input_: String to be cleaned
@type input_: String
@param doquote: I{OPTIONAL}: Wrapped in single quotes, defaults to B{True}
@type doquote: bool
@param doescape: I{OPTIONAL}: Escape single quotes, defaults to B{True}
@type doescape: bool
@return: String, or 'NULL'
>>> print 'SET description = %s;' % cstr("I don't")
SET description = 'I don''t';
>>> print 'SET now = %s;' % cstr("CURRENT_TIME", doquote=False)
SET now = CURRENT_TIME;
"""
if input_ is None:
return 'NULL'
input_ = str(input_)
if doescape:
escape = {"'":"''", "\\":"\\\\"}
input_ = data.replace_all(escape, input_)
if doquote:
return data.wrap(input_, "'")
else:
return input_
def ctags(input_):
"""
Returns a string safe for use in a sql statement
@param: input_
@type input_: Anything
@return: 'NULL', or input_ string
>>> print ctags('')
NULL
>>> print ctags('linux git foo')
'foo git linux'
"""
if input_ in [None, '']:
return 'NULL'
if isinstance(input_, list):
input_ = ' '.join(input_)
tags = data.tags2str(data.str2tags(input_))
return "'%s'" % tags.lower()
def empty2null(input_):
"""
Returns NULL if an empty string or None is passed, else returns the
input_ string.
@param: input_
@type input_: Anything
@return: 'NULL', or input_ string
>>> print empty2null('')
NULL
"""
if input_ in [None, '']:
return 'NULL'
else:
return input_
def unquote(input_):
"""
Return string not padded with single quotes. This is useful to
clean something changed by cstr()
@param: input_
@type input_: str
@return: str, or input unchanged
"""
if isinstance(input_, str):
if input_.startswith("'") and input_.endswith("'"):
input_ = input_[1:-1]
return input_
Chula-0.7.0/chula/db/engines/ 0000755 0001750 0001750 00000000000 11412546122 016647 5 ustar jmcfarlane jmcfarlane Chula-0.7.0/chula/db/engines/sqlite.py 0000644 0001750 0001750 00000003504 11370740256 020533 0 ustar jmcfarlane jmcfarlane """Chula Sqlite datastore object"""
try:
import sqlite3
except:
raise error.MissingDependencyError('sqlite3')
from chula import error
from chula.db.engines import engine
ISOLATION_LEVELS = ['DEFERRED',
'EXCLUSIVE',
'IMMEDIATE',
None]
class DataStore(engine.Engine):
"""
Sqlite engine class
"""
def __init__(self, uri, *args, **kwargs):
super(DataStore, self).__init__()
# Handle in memory databases
if uri == 'memory':
uri = ':memory:'
# Handle the initial isolation level
if 'isolation' in kwargs:
isolation = kwargs['isolation']
else:
isolation = None
# Handle the initial timeout level
if 'timeout' in kwargs:
timeout = kwargs['timeout']
else:
timeout = 5
# Create a database connection
self.conn = sqlite3.connect(uri,
isolation_level=isolation,
timeout=timeout)
def cursor(self, type='dict'):
if type == 'dict':
self.conn.row_factory = sqlite3.Row
return super(DataStore, self).cursor()
def interrupt(self):
self.conn.interupt()
def set_isolation(self, level=None):
"""
Toggle the isolation level. Here are the available
isolation levels:
- DEFFERED = ?
- EXCLUSIVE = Prevents anyone else from reading/writing
- IMMEDIATE = ?
- None = Autocommit mode (the default)
@param level: Isolation level
@type level: str
"""
if level in ISOLATION_LEVELS:
self.conn.isolation_level = level
else:
raise error.InvalidAttributeError(level)
Chula-0.7.0/chula/db/engines/couch.py 0000755 0001750 0001750 00000001766 11370740256 020346 0 ustar jmcfarlane jmcfarlane from couchdb import Server, ResourceNotFound, PreconditionFailed
from chula.db.engines import engine
class DataStore(engine.Engine):
"""
CouchDB engine class
"""
def __init__(self, uri, *args, **kwargs):
super(DataStore, self).__init__()
self.conn = Server(uri)
def delete(self, db):
try:
del self.conn[db]
except ResourceNotFound, ex:
pass
def db(self, db):
try:
return self.conn[db]
except ResourceNotFound, ex:
try:
return self.conn.create(db)
except PreconditionFailed, ex:
# Work around the situation where a client/server
# mismatch results in a PreconditionFailed error being
# raised, even when it was actually created
# successfully. Remove this maybe in time.
if db in self.conn:
return self.conn[db]
else:
raise
Chula-0.7.0/chula/db/engines/engine.py 0000644 0001750 0001750 00000001504 11370740256 020475 0 ustar jmcfarlane jmcfarlane """
Chula database engine module
"""
from chula import collection
class Engine(object):
def __init__(self):
self.conn = None
self.error = collection.Collection()
def set_isolation(self, level=1):
"""
Set the database connection isolation level
"""
pass
def close(self):
"""
Destroy a database connection object
"""
self.conn.close()
def commit(self):
"""
Perform database commit
"""
self.conn.commit()
def rollback(self):
"""
Perform query rollback
"""
self.conn.rollback()
def cursor(self):
"""
Create database cursor
@return: Instance
"""
return self.conn.cursor()
Chula-0.7.0/chula/db/engines/__init__.py 0000644 0001750 0001750 00000000034 11370740256 020764 0 ustar jmcfarlane jmcfarlane """Chula database stores"""
Chula-0.7.0/chula/db/engines/postgresql.py 0000644 0001750 0001750 00000004560 11370740256 021440 0 ustar jmcfarlane jmcfarlane """Chula Postgresql datastore object"""
import re
from chula import error
try:
import psycopg2
from psycopg2 import extensions, extras
except:
raise error.MissingDependencyError('Psycopg2')
from chula.db.engines import engine
class DataStore(engine.Engine):
"""
Postgresql engine class using the Psycopg2 driver
"""
def __init__(self, uri, passwd='', *args, **kwargs):
super(DataStore, self).__init__()
m = re.match(r'(?P[-a-zA-Z0-9]+)@'
r'(?P[-a-zA-Z0-9]+)/'
r'(?P[-a-zA-Z0-9_]+)$', uri)
if m is None:
raise error.MalformedConnectionStringError(engine)
parts = m.groupdict()
parts['pass'] = passwd
conn = 'host=%(host)s dbname=%(db)s user=%(user)s password=%(pass)s'
self.conn = psycopg2.connect(conn % parts)
# Expose the psycopg2 exceptions
self.error.DataError = psycopg2.DataError
self.error.DatabasError = psycopg2.DatabaseError
self.error.Error = psycopg2.Error
self.error.IntegrityError = psycopg2.IntegrityError
self.error.InterfaceError = psycopg2.InterfaceError
self.error.InternalError = psycopg2.InternalError
self.error.NotSupportedError = psycopg2.NotSupportedError
self.error.OperationalError = psycopg2.OperationalError
self.error.ProgrammingError = psycopg2.ProgrammingError
def set_isolation(self, level=1):
"""
Toggle the isolation level. Here are the available
isolation levels:
- 0 = No isolation
- 1 = READ COMMITTED (the default)
- 3 = SERIALIZABLE
@param level: Isolation level
@type level: Integer
"""
self.conn.set_isolation_level(level)
def cursor(self, type='dict'):
"""
Create database cursor
@param type: Type of cursor to return
@type type: string, I{dict} or I{tuple}
@return: Instance
"""
if type == 'tuple':
return self.conn.cursor(cursor_factory=psycopg2.extensions.cursor)
elif type == 'dict':
return self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
else:
msg = 'Invalid cursor type, use either tuple or dict'
raise error.UnsupportedUsageError(append=msg)
Chula-0.7.0/chula/db/datastore.py 0000644 0001750 0001750 00000004530 11370740256 017570 0 ustar jmcfarlane jmcfarlane """
Chula datastore object, provides consistent access to all supported
database engines
"""
import re
# Loading ourselves before third party is bad, but we need to be able
# to raise our own exception if things go wrong
from chula import error, data
class DataStoreFactory(object):
"""
The Database class creates an instance of a supported database
engine (aka datastore)
"""
def __new__(cls, conn, *args, **kwargs):
"""
Creates an instance of a DataStore class.
The connection string is a tuple with the following values in order:
1. Database type B{(Currently the only supported option is: pg)}
2. Username
3. Host
4. Database name
eg: pg:username@server/databasename
@param conn: Connection string
@type conn: String
@param passwd: Database password
@type passwd: String
@return: Instance
>>> conn = DataStoreFactory('pg:chula@localhost/chula_test', 'passwd')
>>> cursor = conn.cursor()
>>> cursor.execute('SELECT * FROM cars LIMIT 1;')
>>> data = cursor.fetchone()
>>> print data
[1, 'Honda', 'Civic']
>>> print data['make']
Honda
>>> print dict(data)
{'model': 'Civic', 'make': 'Honda', 'uid': 1}
>>>
>>> cursor = conn.cursor(type='tuple')
>>> cursor.execute('SELECT * FROM cars LIMIT 1;')
>>> print cursor.fetchone()
(1, 'Honda', 'Civic')
>>>
>>> conn.close()
"""
try:
parts = conn.split(':')
if len(parts) > 1:
engine = parts[0]
uri = ':'.join(parts[1:])
else:
raise error.MalformedConnectionStringError
except AttributeError:
raise error.MalformedConnectionStringError(conn)
if engine == 'pg':
from chula.db.engines import postgresql as engine
elif engine == 'couchdb':
from chula.db.engines import couch as engine
elif engine == 'sqlite':
from chula.db.engines import sqlite as engine
else:
raise error.UnsupportedDatabaseEngineError(engine)
# Return a database engine instance
return engine.DataStore(uri, *args, **kwargs)
Chula-0.7.0/chula/db/__init__.py 0000644 0001750 0001750 00000000271 11370740256 017337 0 ustar jmcfarlane jmcfarlane """Chula database package, a simple db abstraction layer"""
from functions import *
# For now support legacy style acess (for now)
from datastore import DataStoreFactory as DataStore
Chula-0.7.0/chula/www/ 0000755 0001750 0001750 00000000000 11412546122 015456 5 ustar jmcfarlane jmcfarlane Chula-0.7.0/chula/www/cookie.py 0000644 0001750 0001750 00000004564 11370740256 017321 0 ustar jmcfarlane jmcfarlane """
Cookie reads and writes cookies
"""
from Cookie import SimpleCookie
from datetime import datetime
from chula import data
class CookieCollection(SimpleCookie):
def __init__(self, config=None, timeout=20, path='/', input=None):
"""
Create a collection of cookies
@param timeout: How long the cookie should live
@type timeout: int (Unit of measure: minutes)
"""
super(CookieCollection, self).__init__(input)
self.timeout = timeout
self.path = path
self.domain = None
def headers(self):
timeout = self.timeout * 60
now = datetime.utcnow()
expires = data.date_add('s', timeout, now)
expires = expires.strftime('%a, %d-%b-%Y %H:%M:%S %Z')
cookies = []
for key, cookie in self.iteritems():
# Don't write out cookies that are prefixed with underbars
# as they are considered private. This also has the side
# effect of not writing out Urchin cookies like crazy :)
if key.startswith('_'):
# TODO: find a better way to avoid writing Urchin cookies
continue
if not self.domain is None:
# Domain must be prefixed with "." and exclude the
# port. If the domain already has a "." prefix we've
# already seen this domain name and can skip.
# REFERENCE: RFC 2109, RFC 2965
if not self.domain.startswith('.'):
self.domain = '.' + self.domain.split(':')[0]
# If the domain doesn't look to be a real FQDN, remove:
if not self.domain.count('.') > 1:
self.domain = None
# Always include the name of the cookie first
header = []
header.append('%s=%s' % (key, cookie.value))
# Supported cookie attributes
header.append('Expires=%s' % expires)
header.append('Path=%s' % self.path)
# Don't include the domain for sites that only use hostnames
# eg: http://wiki/foo/bar/file.html
if not self.domain is None:
header.append('Domain=%s' % self.domain)
# Create the full header tuple
cookies.append(('Set-Cookie', '; '.join(header)))
return cookies
def destroy(self):
self.timeout = -10000
Chula-0.7.0/chula/www/adapters/ 0000755 0001750 0001750 00000000000 11412546122 017261 5 ustar jmcfarlane jmcfarlane Chula-0.7.0/chula/www/adapters/fcgi/ 0000755 0001750 0001750 00000000000 11412546122 020171 5 ustar jmcfarlane jmcfarlane Chula-0.7.0/chula/www/adapters/fcgi/env.py 0000644 0001750 0001750 00000001042 11370740256 021337 0 ustar jmcfarlane jmcfarlane """
Manage the environment when python is using fcgi
"""
import os
import socket
from chula.www.adapters.wsgi import env
FCGI = 'FCGI/WSGI'
PATH = os.environ.get('PATH')
class Environment(env.Environment):
def __init__(self, environ):
super(Environment, self).__init__(environ)
# Indicate what type of adapter this is
self.chula_adapter = FCGI
# Set the remote_host from the remote_addr
self.REMOTE_HOST = socket.getfqdn(self.REMOTE_ADDR)
# Set the path
self.PATH = PATH
Chula-0.7.0/chula/www/adapters/fcgi/adapter.py 0000644 0001750 0001750 00000001516 11370740256 022175 0 ustar jmcfarlane jmcfarlane """
Chula fastcgi adapter
"""
from chula.www.adapters import base
from chula.www.adapters.fcgi import env
def configured_app(environ, start_response, config):
adapter = base.BaseAdapter(config)
adapter.set_environment(env.Environment(environ))
# Execute the controller and store it's output
chunks = [c for c in adapter.execute()]
# Add the content type to the headers
adapter.add_header(('Content-Type', adapter.env.content_type))
# Execute the wsgi callback
start_response('%s OK' % adapter.env.status, adapter.env.headers)
# Yield the data to the client
for chunk in chunks:
yield chunk
# Clean house
adapter._gc()
def fcgi(fcn):
def wrapper(environ, start_response):
config = fcn()
return configured_app(environ, start_response, config)
return wrapper
Chula-0.7.0/chula/www/adapters/fcgi/__init__.py 0000644 0001750 0001750 00000000000 11370740256 022277 0 ustar jmcfarlane jmcfarlane Chula-0.7.0/chula/www/adapters/wsgi/ 0000755 0001750 0001750 00000000000 11412546122 020232 5 ustar jmcfarlane jmcfarlane Chula-0.7.0/chula/www/adapters/wsgi/env.py 0000644 0001750 0001750 00000005057 11370740256 021412 0 ustar jmcfarlane jmcfarlane """
Manage the environment when python is using wsgi
"""
from cgi import FieldStorage
import os
from chula.www.adapters import env
WSGI = 'WSGI'
class Environment(env.BaseEnv):
def __init__(self, environ):
super(Environment, self).__init__()
# Indicate what type of adapter this is
self.chula_adapter = WSGI
# Set the required variables from the wsgi environ object
self.fill(environ)
# Check for redirects and recover the querystring
if 'REDIRECT_QUERY_STRING' in environ:
self.QUERY_STRING = environ.get('REDIRECT_QUERY_STRING')
# Make sure REQUEST_URI is set
if not 'REQUEST_URI' in environ:
parts = []
parts.append(environ.get('PATH_INFO', ''))
self.REQUEST_URI = ''.join(parts)
# Include the querystring
if not '?' in self.REQUEST_URI:
qs = environ.get('QUERY_STRING', None)
if not qs is None and qs != '':
self.REQUEST_URI += '?' + qs
# Make sure PATH is set
self.PATH = os.environ.get('PATH', None)
# Be nice to the Python wsiref simple_server
if self.SERVER_SOFTWARE.startswith('WSGIServer/0.1 Python'):
self.DOCUMENT_ROOT = None
self.REMOTE_PORT = None
self.SCRIPT_FILENAME = None
self.SERVER_ADDR = None
self.SERVER_ADMIN = None
self.SERVER_SIGNATURE = None
# Make sure SCRIPT_NAME is set
if not self.SCRIPT_NAME:
self.SCRIPT_NAME = self.PATH_INFO
# Set http get or post variables
self.form = FieldStorage(fp=self.wsgi_input,
environ=environ,
keep_blank_values=1)
# Add additional variables provided by the base class
super(Environment, self).extras()
def __deepcopy__(self, memo={}):
"""
Currently not all wsgi.foo objects are easy to deepcopy. This
method overloads BaseEnv to return a fresh object with wsgi
input/error objects being "by reference" copies.
"""
# Make a copy of the existing objects
wsgi_errors = self.wsgi_errors
wsgi_input = self.wsgi_input
# Remove them from the collection
self.remove('wsgi_errors')
self.remove('wsgi_input')
# Put them back (by reference)
fresh = super(Environment, self).__deepcopy__(memo)
fresh.wsgi_input = wsgi_input
fresh.wsgi_errors = wsgi_errors
return fresh
Chula-0.7.0/chula/www/adapters/wsgi/adapter.py 0000644 0001750 0001750 00000001513 11370740256 022233 0 ustar jmcfarlane jmcfarlane """
Chula wsgi adapter
"""
from chula.www.adapters import base
from chula.www.adapters.wsgi import env
def configured_app(environ, start_response, config):
adapter = base.BaseAdapter(config)
adapter.set_environment(env.Environment(environ))
# Execute the controller and store it's output
chunks = [c for c in adapter.execute()]
# Add the content type to the headers
adapter.add_header(('Content-Type', adapter.env.content_type))
# Execute the wsgi callback
start_response('%s OK' % adapter.env.status, adapter.env.headers)
# Yield the data to the client
for chunk in chunks:
yield chunk
# Clean house
adapter._gc()
def wsgi(fcn):
def wrapper(environ, start_response):
config = fcn()
return configured_app(environ, start_response, config)
return wrapper
Chula-0.7.0/chula/www/adapters/wsgi/__init__.py 0000644 0001750 0001750 00000000000 11370740256 022340 0 ustar jmcfarlane jmcfarlane Chula-0.7.0/chula/www/adapters/mod_python/ 0000755 0001750 0001750 00000000000 11412546122 021441 5 ustar jmcfarlane jmcfarlane Chula-0.7.0/chula/www/adapters/mod_python/fakerequest.py 0000644 0001750 0001750 00000005656 11370740256 024355 0 ustar jmcfarlane jmcfarlane """
Classes to aid in unit testing or anything that needs to simulate a valid
Apache/Mod_python request object.
"""
import os
import sys
class FakeFieldStorage(dict):
"""
Fake FieldStorage object.
"""
def __init__(self, *args, **kwargs):
"""
Simulates the mod_python FieldStorage object, really just to
provide the list object.
@return: Pseudo mod_python FieldStorage object
"""
super(FakeFieldStorage, self).__init__()
self.list = self
class FakeRequest(dict):
"""
Fake request object
"""
def __init__(self):
"""
Simulates the req object common to mod_python development
@return: Pseudo mod_python req object
"""
environ = os.environ
self.subprocess_env = environ
self.method = 'GET'
self.proto_num = 9999
self.protocol = 'HTTP/1.1'
self.content_type = "text/plain"
self.status = 200
self.args = environ.get('QUERY_STRING', '')
self.filename = 'index.py'
self.hostname = 'localhost'
self.path_info = environ.get('PATH_INFO', '')
self.REQUEST_URI = '/'
self.uri = '/'
self.the_request = 'GET / HTTP/1.1'
self.connection = FakeRequestConnection()
self.content_length = -1
self._headed = 0
self.headers_out = self
self.headers = ""
self.read = sys.stdin.read
self.server = FakeServer()
self.headers_in = {'Referer':environ.get('HTTP_REFERER', ''),
'Cookie':environ.get('HTTP_COOKIE', ''),
'User-Agent':environ.get('USER_AGENT', '')
}
self.get = FakeFieldStorage()
self.form = FakeFieldStorage()
def _write_headers(self):
self._headed = 1
sys.stdout.write('status: %s\n' % self.status)
sys.stdout.write('Content-Type: %s\n' % self.content_type)
if self.content_length >= 0:
sys.stdout.write('Content-Length: %s\n' % self.content_length)
sys.stdout.write(self.headers)
sys.stdout.write('\n')
self.write = sys.stdout.write
def add(self, key, value):
self.headers += '%s: %s\n' % (key, value)
def document_root(self):
return ''
def get_remote_host(self):
return None
def set_content_length(self, len):
self.content_length = len
def write(self, s):
if not self._headed:
self._write_headers()
sys.stdout.write(s)
class FakeRequestConnection(object):
def __init__(self):
self.local_addr = ['', '']
self.local_host = ('127.0.0.1', 80)
self.remote_addr = ('127.0.0.1', 9999)
self.remote_host = 'localhost'
self.remote_ip = '127.0.0.1'
class FakeServer(object):
pass
# Expose drop in replacements for the real thing
FieldStorage = FakeFieldStorage
Chula-0.7.0/chula/www/adapters/mod_python/env.py 0000644 0001750 0001750 00000002470 11370740256 022615 0 ustar jmcfarlane jmcfarlane """
Manage the environment when python is using mod_python
"""
from mod_python import util
from chula.www.adapters import env
MOD_PYTHON = 'MOD_PYTHON'
class Environment(env.BaseEnv):
def __init__(self, req):
super(Environment, self).__init__()
# Indicate what type of adapter this is
self.chula_adapter = MOD_PYTHON
# Fetch additional mod_python environment variables
req.add_common_vars()
subprocess = req.subprocess_env.copy()
# Set the required variables from mod_python's req object(s)
self.fill(req.subprocess_env.copy())
# Add environment variables not available in subprocess_env
self.PATH_INFO = req.path_info
# Check for redirects and recover the querystring
if 'REDIRECT_QUERY_STRING' in subprocess:
self.QUERY_STRING = subprocess.get('REDIRECT_QUERY_STRING')
# If req.form exists and is of type util.FieldStorage use it,
# else use what mod_python publisher would use.
try:
if isinstance(self.req.form, util.FieldStorage):
self.form = self.req.form
except:
self.form = util.FieldStorage(req, keep_blank_values=1)
# Add additional variables provided by the base class
super(Environment, self).extras()
Chula-0.7.0/chula/www/adapters/mod_python/adapter.py 0000644 0001750 0001750 00000001777 11370740256 023456 0 ustar jmcfarlane jmcfarlane """
Chula mod_python adapter
"""
from mod_python import apache as APACHE
from chula.www.adapters import base
from chula.www.adapters.mod_python import env
def configured_handler(req, config):
adapter = base.BaseAdapter(config)
adapter.set_environment(env.Environment(req))
# Execute the controller and store it's output
chunks = [c for c in adapter.execute()]
# Add the headers to the mod_python req object
for header in adapter.env.headers:
req.headers_out.add(header[0], header[1])
# Set the content_type and status
req.content_type = adapter.env.content_type
req.status = adapter.env.status
# Write the data to the client
try:
for chunk in chunks:
req.write(chunk)
except IOError, ex:
if config.debug:
raise
# All is well
try:
return APACHE.OK
except:
pass
def handler(fcn):
def wrapper(req):
config = fcn()
return configured_handler(req, config)
return wrapper
Chula-0.7.0/chula/www/adapters/mod_python/__init__.py 0000644 0001750 0001750 00000000000 11370740256 023547 0 ustar jmcfarlane jmcfarlane Chula-0.7.0/chula/www/adapters/env.py 0000644 0001750 0001750 00000017130 11370740256 020434 0 ustar jmcfarlane jmcfarlane """
Chula adapter environment class
"""
from copy import deepcopy
import cgi
import re
from chula import error, collection
from chula.www import http
class BaseEnv(collection.RestrictedCollection):
"""
Provide a consistent interface all adapters must conform to
"""
@staticmethod
def __validkeys__():
"""
The minimum environment must at least adhere to the wsgi spec
"""
return ('DOCUMENT_ROOT',
'GATEWAY_INTERFACE',
'HTTP_ACCEPT',
'HTTP_ACCEPT_CHARSET',
'HTTP_ACCEPT_ENCODING',
'HTTP_ACCEPT_LANGUAGE',
'HTTP_CONNECTION',
'HTTP_COOKIE',
'HTTP_HOST',
'HTTP_KEEP_ALIVE',
'HTTP_USER_AGENT',
'PATH',
'PATH_INFO',
'QUERY_STRING',
'REMOTE_ADDR',
'REMOTE_HOST',
'REMOTE_PORT',
'REQUEST_METHOD',
'REQUEST_URI',
'SCRIPT_FILENAME',
'SCRIPT_NAME',
'SERVER_ADDR',
'SERVER_ADMIN',
'SERVER_NAME',
'SERVER_PORT',
'SERVER_PROTOCOL',
'SERVER_SIGNATURE',
'SERVER_SOFTWARE',
'chula_adapter',
'chula_class',
'chula_method',
'chula_module',
'chula_package',
'chula_version',
'wsgi_errors',
'wsgi_file_wrapper',
'wsgi_input',
'wsgi_multiprocess',
'wsgi_multithread',
'wsgi_run_once',
'wsgi_url_scheme',
'wsgi_version',
'ajax_uri',
'content_type',
'cookies',
'debug',
'form',
'form_get',
'form_post',
'headers',
'route',
'status',
'under_construction'
)
def __defaults__(self):
self.DOCUMENT_ROOT = collection.UNSET
self.GATEWAY_INTERFACE = collection.UNSET
self.HTTP_ACCEPT = None
self.HTTP_ACCEPT_CHARSET = None
self.HTTP_ACCEPT_ENCODING = None
self.HTTP_ACCEPT_LANGUAGE = None
self.HTTP_CONNECTION = None
self.HTTP_COOKIE = None
self.HTTP_HOST = None
self.HTTP_KEEP_ALIVE = None
self.HTTP_USER_AGENT = None
self.PATH = collection.UNSET
self.PATH_INFO = ''
self.QUERY_STRING = ''
self.REMOTE_ADDR = collection.UNSET
self.REMOTE_HOST = None
self.REMOTE_PORT = collection.UNSET
self.REQUEST_METHOD = collection.UNSET
self.REQUEST_URI = collection.UNSET
self.SCRIPT_FILENAME = collection.UNSET
self.SCRIPT_NAME = ''
self.SERVER_ADDR = collection.UNSET
self.SERVER_ADMIN = collection.UNSET
self.SERVER_NAME = collection.UNSET
self.SERVER_PORT = collection.UNSET
self.SERVER_PROTOCOL = collection.UNSET
self.SERVER_SIGNATURE = collection.UNSET
self.SERVER_SOFTWARE = collection.UNSET
self.chula_adapter = collection.UNSET
self.chula_class = collection.UNSET
self.chula_method = collection.UNSET
self.chula_module = collection.UNSET
self.chula_package = collection.UNSET
self.chula_version = collection.UNSET
self.route = collection.UNSET
self.wsgi_errors = None
self.wsgi_file_wrapper = None
self.wsgi_input = None
self.wsgi_multiprocess = None
self.wsgi_multithread = None
self.wsgi_run_once = None
self.wsgi_url_scheme = None
self.wsgi_version = None
self.ajax_uri = collection.UNSET
self.content_type = 'text/plain'
self.cookies = None
self.debug = True
self.headers = []
self.form = collection.UNSET
self.form_get = collection.UNSET
self.form_post = collection.UNSET
self.status = http.HTTP_OK
self.under_construction = False
def __deepcopy__(self, memo={}):
"""
Return a copy of a BaseEnv object
"""
return self.copy_into(BaseEnv())
def _ajax_uri(self):
protocol_type = re.match(r'(HTTPS?)', self.SERVER_PROTOCOL)
if not protocol_type is None:
protocol_type = protocol_type.group()
else:
msg = 'Unsupported protocol: %s' % self.SERVER_PROTOCOL
raise ValueError(msg)
# Prefer HTTP_HOST over SERVER_NAME per PEP333
domain = self.HTTP_HOST
if domain is None:
domain = self.SERVER_NAME
return protocol_type.lower() + '://' + domain
def _cookie(self):
"""
Make sure HTTP_COOKIE exists even if empty
"""
return self.get('HTTP_COOKIE', {})
def _downcast_cgi_vars(self):
"""
When mod_python.util.FieldStorage or cgi.FieldStorage
encounter array types (think html checkboxes) it winds up
being a Field() or MiniFieldStorage() object for mod_python or
cgi respectively. Both are intended to be accessed via a
"value" attribute. This method casts these objects so the
actual value is held and thus can be referenced directly. In
the event the object doesn't have a "value" attribute it's
left alone (not sure how this can happen, but it does).
"""
for key in self.form.keys():
if isinstance(self.form[key], list):
for i in xrange(len(self.form[key])):
if not getattr(self.form[key][i], 'value', None) is None:
self.form[key][i] = self.form[key][i].value
else:
# Let me know if you can make this get called :)
pass
def _clean_http_vars(self):
passed = deepcopy(dict(self.form))
# Create object to hold only HTTP GET variables
self.form_get = cgi.parse_qs(self.QUERY_STRING, keep_blank_values=1)
for key in self.form_get.keys():
if len(self.form_get[key]) == 1:
self.form_get[key] = self.form_get[key][0]
else:
self.form_get[key] = self.form_get[key]
# Create an object to hold only HTTP POST variables
self.form_post = {}
for key in passed.keys():
if not key in self.form_get:
if isinstance(passed[key], list):
self.form_post[key] = passed[key]
else:
self.form_post[key] = passed[key].value
# Make sure the form object contains both while taking
# precedence over POST when overlap exists
self.form = deepcopy(self.form_get)
self.form.update(self.form_post)
def fill(self, env):
"""
Populate the collection with values. Some keys contain "."
characters which would break attribute access on this
collection. For this reason dots will be replaced with
underbars.
"""
for key, value in env.iteritems():
key = key.replace('.', '_')
if key in self:
self[key] = value
def extras(self):
"""
Set extra environment variables, all being Chula specific
"""
self.HTTP_COOKIE = self._cookie()
self.ajax_uri = self._ajax_uri()
# Make sure get/post variables are handled correctly
self._clean_http_vars()
self._downcast_cgi_vars()
Chula-0.7.0/chula/www/adapters/base.py 0000644 0001750 0001750 00000013153 11370740256 020557 0 ustar jmcfarlane jmcfarlane """
Chula base adapter for all supported web adapters
"""
from copy import deepcopy
import re
import time
import chula
from chula import collection, error, guid, logger
from chula.www import cookie
from chula.www.mapper import ClassPathMapper
from chula.www.mapper import RegexMapper
RE_HTML = re.compile(r"