Home

  Documentation

  Download

  News

  Examples

Lemon Manual

This documentation is far from complete and many of the functions may have changed since the manual was updated. For correct information read the referenece and look at the examples.

Contents

About Lemon

If you are new to Lemon you may want to read the Getting Started guide first.

Introduction

Purpose of This Document

The purpose of this document is to give someone who is new to the Lemon modules an overview of the design philosophy and software components of Lemon and to get them up and running with their first scripts with a tutorial.

More information is available in the user guides for each of the comonents and the howto guides which cover specific areas of programming. There is also a full function reference and plenty of examples. If you are still stuck after all that please contact the authour for help.

Philosophy

Developing web applications can be difficult. Many programmers have developed complicated systems to massively simplify the process. These systems work very well if your indended purpose closely matches the intention of the authour. The cost of using these systems is the steep learning curve required to understand the system properly and the lack of flexibility if the system doesn't quite match your intended purpose.

LEMON takes the opposite approach called "Extreme Programming". By making the really simple functions available easily in a modular form you can quickly build your own system without having to recreate the wheel or learn a new framework every time you want to write a new system. LEMON is designed to be an extremely thin layer to allow you to program any way you want as easily as possible whilst still giving you the functionality you require to get the job done.

Lemon is pure Python which means it will run on any platform with a Python interpreter without needing configuration or compilation. You don't even need administrator priveldges to use it.

Design Principles

Lemon is built on a number of popular design patterns including MVC. It addresses the following problems typically encountered in the development of complex sites:

  • Separating design from logic
  • Lemon includes a number of templating systems including Cheetah, XYAPTU and others, which allow for a clean divide between the HTML page design and the program data. Lemon fits into and encourages a Model / Controller / View (MVC) approach to systems design.
  • Extreme Programming
  • The Lemon modules are built on the methadology of Extreme Programming. By writing simple clean modules we avoid unncecesary features and offer a very flexible toolkit for the development of advanced applications
  • Getting database fields on and off web pages
  • Lemon has a forms module which simplifies greatly the process of creating HTML forms for presentation of database information for updating. The module also includes classes to allow the reading / sorting /adding of data to a table without complex coding. Data is passed to and from a Form object in the form of a dictionary. This makes it very obvious for the programmer to see what is going on within the internals of the modules.
  • Managing users and their access permissions
  • Lemon includes an auth module which uses md5 encryption to store users' usernames and passwords in a database. It also offers a very simple interface for user management and permision checking as well as a persistance mechanism.
  • Database independence

Lemon includes functions to generate SQL. This allows the same call to be implemented differently by different database backends creating database independance in the code.

Alternatives

The LEMON modules are an extremely simple and flexible set of tools but they may not be exactly what you are after for your purpose.

If you don't want to program in Python you should have a good look at PHP and the PEAR modules distributed with PHP 4.

If you do want to program in Python you might want to look at the following:

Zope - Complete web server and application framework. Twisted - Complete set of web modules implementing everything web-related. Webware - Suite for developing web-based applications Alternatively search Google or have a look at this comparison.

Little Web Modules
http://lwtools.sourceforge.net/

General

Description

Lemon is a suite of pure Python modules for rapidly developing web applications. Includes: database, webserver, auth & session management, form and templating tools, docs and examples. Flexible enough to use on its own or with other solutions like Apache.

Registration Description: Lemon is an attempt to write a series of modules which web application developers require but are not distributed with the Python distribution.

The idea is not to write a programming framework like Webware but rather offer useful tools which enable the programmer to use which ever components they prefer in their applicaitons. One of the key design goals of Lemon is to write a system that requires no installation. Just drop the lemon directory into the same directory as your script and everything will work. As such it is written in pure Python. Python 2.2 is the only requirement to get full web applications running on any PC using the modules that come with Lemon.

Where possible Lemon uses existing solutions. It includes Gadfly as a database, Cheetah as a templating tool and epydoc as a documentation system. All of which have had simple wrappers written for them to make them even easier for developers to use.

One of the principles of Lemon was to offer simple ways of doing things but not prevent users easily getting to the heart of the code if they want to do something slightly out of the ordinary. There is no point in making things simple if you limit the flexibility of your program as a result. This is a mistake some web frameworks make. They are ideal for their intended purpose but useless for anything slightly out of the ordinary. Many of the functions are moddled on PHP Pear style ways of doing things as these have prooved to be the most intuiutve.

Where existing solutoins don't meet what we wanted we have developed more software. Here is a description of some of the modules we have programmed to be distributed with Lemon:

DILL

(Database Interface Layer for Lemon). This may be distributed as a separate package as well.

It is a simple database abstraction layer built on top of DB-API 2.0 Cursors, which in addition to providing all the Cursor functions and methods, offers a series of methods to generate the SQL automatically and convert the values to and from values compatible with a particular database. DILL provides complete database independence and offers the possibility of adding certain funcitons to databases, for example the DILL Gadfly cursor implements Date types and the ALter command by doing some clever things even though the database doesn't natively support it. Currently MySQL and Gadfly are properly supported.

DB Builder

This is an object relation manager similar to SQL Object where after defining a table in a Python class, the database can be manipulated as if it was a Python object with automatic type and SQL conversion transparent to the user. The table implementation also offers an automatic form generation function allowing data to be validated and added to the table through an HTML interface. All these features are a doddle to use becuase all the complications are taken care of in the modules.

DB Builder is built on top of DILL providing database independance for DILL supported databases.

Query Builder

Code which allows WHERE clauses etc to be generated in natural Python language through the use of query objects which have overloaded operators. eg:

>>> (person.name == person.address) & (person.name <> 'James')
Name=Address AND Name<>'James'

Very useful for generation of queries.

Session Management

Cookie and URL based session management tools implemented in an interface/driver model making different back-ends for the session storage very simple. Currently only a database backend is written but if you choose Gadfly as the database you don't even need a database installed so the modules can be use on any system.

Auth Management

Similar to PHP Pear Auth mangement code. Coded in a similar style to session with functions for the manegement of the users, creation of tables etc separated from the actual code you place in an application. Both sections have an interface/driver model so new back-ends are easy to write. Lemon has been programmed to make writing web applications as simple as possible for end users.

HTML Templates

Including Cheetah and XYAPTU and a custom Dreameaver MX module

HTML Forms

Code for the simple generation of HTML forms with built in error checking of the values. Allows extra constraints to be applied to each field. Different interfaces are offered to generate the form including using a template or just accepting a deafult form. Quite a powerful module.

I think I've covered the most important bits now but there are also functions for sending mail through SMTP/Sendmail Date and Time classes for database interactions etc etc.. All the code can interact or be used on its own. The modules are supposed to be complete but flexible and require no installation. One of my main motivations for writing it all was to be able to use advanced features on a shared hosting account and be able to run the same code on any platform/server & database configuration without needing to make any modifications.

The modules are designed to make it easy for a new developer to build web applications with little prior knowledge after just reading the User guides. The key phrase for the modules is:

"It is better to have a flexible module that can be used intuitively than an all-singing, all-dancing framework that no-one can be bothered to learn."

Components

Not written yet.

Rival Software

Not written yet.

Installation

General Considerations

Not written yet.

Instructions

Not written yet.

Runtime Configuration

Not written yet.

Support

Not written yet.

Getting Started

Introduction

What Is Python?

Here is a description taken from the Python page for newbies, http://www.python.org/topics/learn

Python is a clear and powerful object-oriented programming language, comparable to Perl, Tcl, Scheme, or Java.

Some of Python's notable features:

  • Python uses an elegant syntax for readable programs.
  • Python is an agile language that makes it easy to get your program working. This makes Python an ideal language for prototype development and other ad-hoc programming tasks, without compromising maintainability.
  • A variety of basic data types are available: numbers (integers, floating point, complex, and unlimited-length long integers), strings (both ASCII and Unicode), lists, dictionaries.
  • Python supports object-oriented programming with classes and multiple inheritance.
  • Code can be grouped into modules and packages.
  • The language supports raising and catching exceptions, resulting in cleaner error handling.
  • Data types are strongly but dynamically typed. Mixing incompatible types (e.g. attempting to add a string and a number) causes an exception to be raised.
  • Python contains advanced programming features such as generators and list comprehensions.
  • Automatic garbage collection frees you from the hassles of memory management.
  • The large standard library supports many common programming tasks such as connecting to web servers, regular expressions, and file handling.
  • Python's interactive mode makes it easy to test short snippets of code. There's also a bundled development environment called IDLE.
  • The Python interpreter is easily extended by adding new modules implemented in a compiled language such as C or C++.
  • The interpreter can also be embedded into an application to provide a programmable interface.
  • Python runs on many different computers and operating systems: Windows, MacOS, many brands of Unix, OS/2, ...
  • Python is open source software, copyrighted but freely usable and distributable, even for commercial use.

To begin learning the Python language, you should download the Python interpreter and read a tutorial.

What Can Python Do?

Not written yet.

What Is Lemon?

Lemon is a set of open source, Python modules for the rapid and convenient development of web-based database applications.

What Can Lemon Do?

Lemon only aids you in doing other things. It doesn't actually do anything! That was the fundamental point of Lemon.. the Python programming language provides the tools to do the 'anything' part, Lemon provides a load of very helpful functions and classes to make doing the 'anything' very simple.

Lemon is desinged to be pure Python. It is possible to optimise some of the 3rd party software bundled with Lemon but it will all work without any form of compilation. This means that you don't even need to install the modules to get them to work which means you can use Lemon without adminstrator or root access on your server. It also makes them totally cross-platform.

Here is an outline of Lemon's main features:

Tutorials

What Do I Need?

You will need to download and install Python as described in the Installation guide.

You will need some sort of web server on which to run your application. Apache is the reference web server for Lemon and it is available for many platforms including Windows.

If you don't have a web server you can easily write one in Python. The code below is a simple threaded CGI server which will allow you to test the samples. When you run the script the directory in which you run it will become the root directory. You should create a folder called cgi-bin in this directory and this will become the directory where you can run .py files.

import SocketServer
import BaseHTTPServer
import CGIHTTPServer
import sys, os


class ThreadingCGIServer(SocketServer.ThreadingMixIn,
                         BaseHTTPServer.HTTPServer):
    pass


server = ThreadingCGIServer(('', port), 
                            CGIHTTPServer.CGIHTTPRequestHandler)
print "Started serving on port %s."%(port)
try:
    while 1:
        sys.stdout.flush()
        server.handle_request()
except KeyboardInterrupt:
    print "Finished"
Note:TO USE THIS PYHTON WEB SERVER UNDER WINDOWS THE CGI SCRIPTS MUST END IN .py NOT .cgi

Once the server is running you should be able to access it at http://localhost:8080/

You will need to install the Lemon modules as described in the Installation guide. Once you have done all that you should be ready to start testing the samples.

Simple Tutorial

What is CGI?

CGI stands for Common Gateway Interface and is all about creating CGI scripts to run on web servers. At the core, CGI scripts are simply computer programs which run on a web server and output HTML in a standard format back to the web browser. CGI scripts can be written in virtually any language including Python. CGI scripts can be used for creating dynamic web pages, responding to user actions, accessing databases, creating shopping carts, etc.

CGI Basics

CGI scripts can be written in any language the web server supports.

CGI programs have to have special permission to run on a server. This is to prevent people uploading files to a server and then running potentially harmful programs. Many ISP's do not let people run CGI scripts so you may have to change your ISP.

Rather than printing to the screen, CGI programs print to the web browser so that a standard print command produces text which will be seen on a web browser.

Hello World!

The best way to demonstrate the basics is to create a "hello world!" program. This tutorial uses Python and we will assume you are using the Apache Web Server. In a text editor type the following into a file called hello.cgi:

#!/usr/bin/python

print "Content-type: text-htmlnn" print "<html>Hello world!</html>" The first line tells the web server where the Python program is on the server. It is usually in /usr/bin/python or /usr/local/bin/python so you must change the first line to suit your server but you must remember the #! at the start, the slashs are forward slashes, and that you must have a least one completely blank line before you start anything else.

The print "Content-type: text-html " command tells the web browser what type of information is about to be sent. If your CGI script sent a GIF image, for example, you would use print "Content-type: image-gif ".

The last line prints the HTML code to the web browser.

Once you have written your script you will then need to upload it to a directory which supports execution of scripts using FTP software. This directory will normally be called cgi-bin or cgi. Next you will need to change the file permissions of your script using the UNIX command chmod 755 hello.cgi or using your FTP software to change the file settings so that everyone can read and execute your file but only you, the owner, can write it. Now, using your web browser visit the hello.cgi script by typing http://www.yourservername.com/cgi-bin/hello.cgi or something equivalent for where your file is on the internet.

If all goes well you should see the text:

Hello world

If not, check you have followed the instructions correctly. If you get an error message saying something like Error 500 there was an error in the script it means you have mis-typed something or the server cannot find the Python program. Error 404 means that you have typed the wrong address and that is not where the hello.cgi script is. Error 403 means you do not have permission to execute the file and you need to change the file permissions.

If you have problems you can often access your script using telnet. Load telnet and type open yourserver.com enter your username and password and navigate to your cgi script using ls to give a list of directories, cd cgi-bin to change directory to cgi-bin and cd .. to go up a level. You can then type python hello.cgi and if there are errors in your script, the Python interpreter will find them. Also you can type which python to find out about the Python version you are using.

It can be a complicated business to start with but once you have done it once you should be able to do it again with ease!

Dealing With Forms

Not written yet.

Contact Form Tutorial

In this tutorial we are going to develop a simple contact form application. Users are going to be able to choose who they want to send a message to but they must specify their name, email and a messgae for the messgage to send and they are displayed a summary once it is sent.

The tutorial covers:

  • Using templates
  • Creating and validating forms
  • Sending email

A future version of the tutorial might also cover:

  • User administration.
  • Online updating through the DB interface.

Source Code:

#!/usr/bin/python2.2

import cgitb; cgitb.enable()
import cgi, os, re
import lemon, lemon.html.form, lemon.html.template



# Configuration
selected=0  # The array index of the selected index
subject = '[non-zero] Website Enquiry'
names=[
    ("General Enquires", "enquiries@nonzerodigital.co.uk"),
    ("Darwin Peltan", "darwin@nonzerodigital.co.uk"),
    ("James Gardner", "james@jimmyg.org"),
    ("Sarah Medina", "sarah@nonzerodigital.co.uk"),
]
tplFile = "../../template.html"

to=[]
counter=-1
for tuple in  names:
    counter+=1
    to.append((tuple[0],counter))
    
class contactForm(lemon.html.form.Form):
    def setup(self):
        self.addField( lemon.html.form.Menu('to',to,default=selected,description='To', size=1))
        self.addField( lemon.html.form.Input('name',description='Your Name', size=38))
        self.addField( lemon.html.form.Input('email',description='Your Email', size=38))
        self.addField( lemon.html.form.TextArea('message',description='Message',cols=30, rows=10 ))
        self.addAction('Send Message')
        
    def isValid(self): # XXX not done yet.
        validates = True
            
        # email
        m = re.search('^.+@.+\..+$',self.get('email').value)
        if not m:
            self.get('email').error = "Please enter a valid email address."   
            validates = False
            
        # to
        if not self.get('to').isValid():
            self.get('to').error = "Please choose an entry from the options."
            validates=False
            
        # name
        if not self.get('name').value:
            self.get('name').error = "Please include your name so we can reply to your message."
            validates=False
            
        # message           
        if not self.get('message').value:
            self.get('message').error = "Please include your message."
            validates=False
        
        return validates

# Main script
tmplDict = {'Content':'','Title':'Contact Form'}    
form = contactForm('contact', 'contact.py', 'get')

print lemon.getHTTPHeader('text/html')

if len(lemon.cgi) > 0: # If form submitted
    form.populate(lemon.cgi)
    if form.isValid():
        try:
            lemon.mail  (
                            msg=form.get('message').value, 
                            to=names[int(form.get('to').value)][1], 
                            sender=form.get('name').value, 
                            reply=form.get('email').value,
                            subject=subject, 
                            sendmail='/usr/lib/sendmail',
                        )
        except lemon.LemonError, e:
            tmplDict['Content'] += '<p>There was an error sending the email.</p>'+ e.message
            print lemon.html.template.parse(file=tplFile, dict=tmplDict, type="xyaptu")
        except:
            tmplDict['Content'] += '<p>There was an error sending the email.</p>'
            print lemon.html.template.parse(file=tplFile, dict=tmplDict, type="xyaptu")
        else:
            tmplDict['Content'] += "<p>Message sent successfully.</p>" + form.asFrozen()
            print lemon.html.template.parse(file=tplFile, dict=tmplDict, type="xyaptu")
    else:
        tmplDict['Content'] +=  form.asHTML()
        print lemon.html.template.parse(file=tplFile, dict=tmplDict, type="xyaptu")
else:
    tmplDict['Content'] +=  form.asHTML()
    print lemon.html.template.parse(file=tplFile, dict=tmplDict, type="xyaptu")

First we import all the required modules then we set up the list used to store the names and addresses of the contacts.

lemon.cgi is a dictionary of cgi fields. Emtpy fields are included as Null strings.

lemon.html.template.parse(file=tplFile, dict=tmplDict, type="xyaptu") parses the XYAPTU template tplfile with the data from tmplDict and returns the HTML as a string.

In Lemon you create forms by deriving your own form from a lemon.html.form.Form object. You then implement the setup() method to add new fields and use addAction('action_name') to add a submit button named action with the value action_name.

Forms can contain hidden data by passing a dictionary of name value pairs as the attribute stickyData in the constructor. eg form = contactForm('contact', 'contact.py', 'get', stickyData={'name':'value'})

Overview Of Features

Documentation is also available in the form of:

See the documentation for the Lemon package for an overview.

Documentation for previous versions of Lemon is available online.

Name Status Module Description
Auth Beta auth Auth provides for the management of applications and users including their access rights, usernames and passwords. Provides a very simple and powerful API
DILL Beta db DILL is perhaps the most useful Lemon component. It is resposible for the datastore and middle tier of applications. It provides a number of components including a database-independant abstraction layer, natural language query builder and an object data relation mapper. These components make it possible to write portable back-end code with very little effort on the part of the developer. DILL is interfaced with Form allowing the automatic generation of validating HTML forms for updating information in the datastore.
Form Beta html.form Provides field and form classes to simplify the generation of HTML forms. Simple API for field validation.
Session Beta session Session provides an easy API for the mangement of session information via cookies or url session ids.
Template Beta html.template The template module contains a variety of template parsers to enable you to separate your code from the appearance of your HTML to generate dynamic content.
Misc Beta   Many other modules and scripts provide useful features such as a webserver, documentation generation etc.

All the Lemon components are designed to be extremely flexible so that you can use whichever components you need in your own code or easily modify an existing driver to suit your needs.

Included Software

Lemon also include software developed by other developers.

Session Management

Not written yet.

User Authentication

Take a look at the example below and we will work through it:

import lemonimport lemon.authimport lemon.dbimport lemon.session

import os

cursor = lemon.db.cursor(type='mysql', database='test')
session = lemon.session.start(storage='db', cursor=cursor, name='LemonTests')
auth    = lemon.auth.AuthDB(session)                

if auth.isValid() > 0:       
    print lemon.getHTTPHeader('text/html')
    if lemon.get.has_key('logout'):
        auth.logout()
        print "Logged Out Now"
    else:                           
        print "<html><h1>Logged In</h1><p>Username: "
        print auth.getUser()['username'], "</p>"
        print auth.getStatus()
        print '<a href="' + os.environ['SCRIPT_NAME'] + '?logout=True"' + ">Logout</a>"
        print "</html>"

Cookies

Not written yet.

File Uploads

Not written yet.

Database Connections

Lemon provides a very simple interface to the common SQL commands. It has a thin wrapper which inspects the field types of the data returned from the database and converts the results to a standard format. Lemon also provides access to the standard cursors menaing that even if you create a lemon.db cursor you can still use it exactly as a normal cursor. This offers you flexibility and the best of both worlds.

This means you can guarantee that no matter which database you use, your Python code will not need changing. It also means that results are typed so that you actually get an integer from an integer field and a float from a float field without having to convert them from strings.

The database layer also provides classes for managing dates and times in a logical way.

Cookies

Not written yet.

Get, Post

There currently is no post variable but there is a lemon.get dictionary containing all the information from the GET environmental variable. Empty variables are kept as keys with null strings as the values.

http://www.example.com/cgi-bin/script.py?mode=now&test=&all=True

In the URL above the script script.py would be able to access the lemon.get dictionary and it would be populated like this:

{
  'mode':'now',
  'test':'',  
  'all':'True'
}

and can be accessed like this:

import lemon
print lemon.get['mode']

File Upload

Not written yet.

Session Management

Lemon has built-in session management. You simply specify an application name and cursor and you can read and write from the session object as if it were a dictionary. Values are pickled so you can store complex data structures in the templates.

Example:

import lemon.session
session = lemon.session.start()
if session.created(): # New Session
    session['var1'] = (1,2,3)
else:
    print session['var1']

Database Connections

Not written yet.

Templating Functions

Lemon provides a numbe of templating modules all accessed through the same interface. These allow you to separate your code logic from your page desing.

Note:More information can be found by reading the user guides of the modules mentioned.

Templating is performed using either Cheetah or XYAPTU. Please see the examples directory for simple examples of how to use the templates.

Forms

Not written yet.

Mail

Not written yet.

Where Next

You should read the Python Documentation.

Overview of the rest of the manual.

Common Problems

Please email james at jimmyg.org if you have any problems and I will add your problem and the answer here.

User Guides

Gadfly

For Version:0.2.4

Introduction

Lemon includes a lemon.db interface to Gadfly so that you can use Gadfly exactly the same way as you would use any other Lemon supported database. This means that, using Lemon, you can access Gadfly through a normal DB-API 2.0 Cursor, a Lemon DILL Connection or a Lemon DILL Builder connection. Gadfly does have a few quirks and these are outlined in this document.

YOU SHOULD READ THE DILL USER GUIDE BEFORE READING THIS DOCUMENT AS IT MAY NOT MAKE MUCH SENSE OTHERWISE.

Warning

Gadfly is not a full SQL database. Sadly it lacks many of the features that datbases such as MySQL have. It is also less stable and should only be used for testing and not deployed as a full solution unless you are very aware of its shortcomings. See "Problems With Gadfly" for an introduction to the issues and how they are dealt with in Lemon.

Problems With Gadfly

  • Gadfly is not as stable as databases like MySQL.
  • Gadfly doesn't support NULL
  • Gadfly only supports VARCHAR, INTEGER and FLOAT field types.
  • Gadfly doesn't support the ALTER SQL command.
  • Gadfly doesn't have a tool to quickly create databases.

The first two of these issues cannot be easily dealt with, although in time we hope Gadfly to become more mature. The other issues have been dealt with in the Lemon DILL layer.

Field Types

The lemon DILL interface to Gadfly automatically makes a note of what field type you are using every time you create or drop a table. This information is stored in a table in your Gadfly database called ColTypes. When you set information in the database or retrieve information from the database, the DILL layer looks up what type of data you are expecting and converts it accordingly. This means that as long as you use the DILL functions to access the database, you can treat Gadfly as supporting the full range of fields described in the DILL user guide.

Note:As a consequence of the field conversions the ColTypes table is reserved and you may not access it for any other purpose.

ALTER

The ALTER command has also been implemented by the DILL layer but should not be treated as totally stable. The command works by manually transferring all the information from the table into memory, deleting the table, recreating it with the new options and then putting all the information back in. The developers have noticed that Gadfly tends to like being disconnected from and reconnected to before any further commands are made.

Warning:If an error occurs during this process than information may be lost. It is recommended you make a complete backup of the database first.

The ALTER function in Gadfly has a slightly different syntax to the ALTER function used by other DILL components if you are adding a column. This is because Gadfly doesn't suppot NULL so you must specify a default value of the correct type for the column you want to add. In the other databases the default is taken to be None.

FTP Transfer

Gadfly databases are are stored in files. If you are transferring these files using FTP software remember to transfer them in Binary mode rather than Text or Auto modes as the types of the files can sometimes be detected incorrectly by the FTP software. If you get strange errors with the values of certain field types this may be your problem.

Creating a Database

Databases are normally created by the database program you are using. In MySQL you load the command prompt to create a database, in Access you create a database through the menu options. You should normally read the documentation for the database you are using to find out how to create a database.

Gadfly is a Python database so you create a database using Python code. To do this with Lemon you need to connect to Gadfly in a special mode to create the database and then you can add and remove tables in the normal way using the Lemon DILL interface.

Here is a simple program to create a database called Test in the directory C:\Gadfly:

>>> import lemon.db.drivers.gc
>>> import gadfly
>>> connection = gadfly.gadfly()
>>> connection.startup("Test", "C:\Gadfly")
>>> database = lemon.db.drivers.gc.gadflyCursor(conn=connection)
>>> database.createColTypesTable()
>>> database.commit()

We will go through this example line by line to explain what it does. These lines import the Lemon DILL Gadfly interface and Gadfly itself:

>>> import lemon.db.drivers.gc
>>> import gadfly

The next lines create a special Gadfly connection for creating a database and setup a database called Test in the directory C:\Gadfly:

>>> connection = gadfly.gadfly()
>>> connection.startup("Test", "C:\Gadfly")

At the moment no files have been produced and the database hasn't been written to the disk. In order to actually create the database a table has to be added to it. This is a quirk of Gadfly but it isn't a major problem. The next line creates a Lemon DILL connection to our newly formed database using a syntax specially designed for Gadfly:

>>> database = lemon.db.drivers.gc.gadflyCursor(conn=connection)

Finally a special method of the Gadfly DILL interface is called to create a table named ColTypes and the changes are committed (see the section "Problems With Gadfly" for information about why this table is needed):

>>> database.createColTypesTable()
>>> database.commit()

This results in the creation of the following files:

  • COLTYPES.grl - The ColTypes table.
  • Test.gfd - The Test database.
  • Test.gfl
  • Test.glb

Now that your database is created you can access it through the Lemon DILL interface as described in the DILL user guide. The database can be treated in exactly the same way other databases as long as you use the DILL interface.

Reconnecting to an Existing Database

Once you have created a database you do not need to use the special startup commands you used above. Instead you connect to the database using the normal DILL syntax, specifying the directory the database is in as well as the database name. You can create and drop tables as you like.

Below is a simple example where we connect to the database we created in the section above and create a new table:

>>> import lemon.db
>>> database = lemon.db.connect(type="gadfly", database="Test", dir="C:\Gadfly")
>>> database.CREATE('new_table', (
...                                 ('TestCHAR', cursor.CHAR),
...                                 ('TestSTRING', cursor.STRING),
...                                 ('TestBINARY', cursor.BINARY),
...                                 ('TestINTEGER', cursor.INTEGER),
...                                 ('TestFLOAT', cursor.FLOAT),
...                                 ('TestDATE', cursor.DATE),
...                                 ('TestTIME', cursor.TIME),
...                                 ('TestDATETIME', cursor.DATETIME),
...                              ) 
...                 )
>>> database.commit()
>>> database.close()

The first line imports the Lemon DILL interface, lemon.db:

>>> import lemon.db

The second line connects to our database:

>>> database = lemon.db.connect(type="gadfly", database="Test", dir="C:\Gadfly")

The next line creates a table named new_table with eight fields of different types. These field types are handled by the DILL interface because Gadfly doesn't nativly support them:

>>> database.CREATE('new_table', (
...                                 ('TestCHAR', cursor.CHAR),
...                                 ('TestSTRING', cursor.STRING),
...                                 ('TestBINARY', cursor.BINARY),
...                                 ('TestINTEGER', cursor.INTEGER),
...                                 ('TestFLOAT', cursor.FLOAT),
...                                 ('TestDATE', cursor.DATE),
...                                 ('TestTIME', cursor.TIME),
...                                 ('TestDATETIME', cursor.DATETIME),
...                              ) 
...                 )

Finally, the changes are committes and the connection is closed:

>>> database.commit()
>>> database.close()

Examples

There are a number of examples explaining various aspects of Lemon included in the user guides. There are also some simple tutorials.

The exmaples can be found in the examples directory of the distribution and the documentation in the doc/examples directory.

The paths in the examples are set up to be tested the Gadfly database and the webserver distributed with Lemon. If you wish to use a different different database or webserver the scripts may require some simple modifications to the paths.

WARNING: You should not use the Gadfly database used in the examples for any purpose other than testing the examples. To create your own database look at the scripts/dbCreateTables.py code and the Gadfly documentation and write your own version.

Commercial Examples

A number of commercial programs are being based on parts of Lemon. These include:

Test Webserver

The Lemon distribution comes with a simple Python webserver designed to allow you to test the examples on your own machine. To use it download and install Lemon and then issue the following command in the Lemon directory:

python webserver.py
Note:For the webserver to work, the path to the webserver.py file must contain no spaces.

If you visit http://localhost:8080/doc/manual.html#examples on your local machine you should see the this file. If this is the case you can follow the links above and test the examples on your own computer.

Auth Example

The auth example is a simple demonstration of how user authentication works in Lemon. The example uses the database in the doc/examples/data/gadfly directory of the source distribution. You can generate the database by running the scripts/dbCreateTables.py file of the source distribution.

To test the auth example an application named test and a user named test have been added to the database. Use the login details below:

Username:test
Password:123

Please note the line:

auth    = lemon.auth.start(session, storage='db', database=database, autoRedirect=False)

the variable autoRedirect has been set to False becuase the Python webserver has problems with the "Location" HTTP header.

Ordinarily you would want the page redirected as soon as someone logs in so that their username and password aren't visible on the screen and so that if they push the refresh button they aren't logged in again.

Builder Example

The Builder example demonstrates the power of the Lemon database interface by automatically generating an HTML form for the addition of a row of data to the database. The example uses the database in the doc/examples/data/gadfly directory of the source distribution. You can generate the database by running the scripts/dbCreateTables.py file of the source distribution.

Note for the author:
 This example deserves more explaination.

Environmental Variables Example

This script prints out a list of all the environmental variables available. It does not use Lemon but is still useful because:

Forms Example

The forms exmaple demonstrates how to create various HTML fields and specify certain constraints on what values are allowed for a particular field. It also demonstrates how to create, validate and then use the data from a form.

Session Example

The session example is a simple demonstration of how sessions work with Lemon. The example uses the database in the doc/examples/data/gadfly directory of the source distribution. You can generate the database by running the scripts/dbCreateTables.py file of the source distribution.

Template Examples

The cheetah.py, xyaptu.py and dreamweaverMX.py files all demonstrate the parsing of a different HTML template files. The templates themseleves are in the doc/examples/data/templates directory of the source distribution.

Error Example

Demonstrates lemon's custom error handling module.

Module Reference

The module reference is API documentation generated when you ran the generate.py file when you first installed Lemon. You can read the Module Reference here or find it in the doc/reference directory of the source distribution.

HOWTO Guides

Config Files, Default Variables, Lemon.ini

Lemon provides a simple method to store your preferred configuration. The conf.py file in the lemon module directory contains a single string named options this string is the default configuration file.

The Lemon.ini file is a file compatible with the ConfigParser module distributed with Python. You shoulde read the documentation fot that module if it isn't instantly clear how to set variables or look at the section below.

Overriding the Default Lemon.ini

You can modify the conf.py file directly to change various options but it is usually better to create your own config file called Lemon.ini somewhere on your PYTHONPATH. If Python can find a Lemon.ini file the values in the conf.py file will be automatically overridden.

The easiest places to put your Lemon.ini are in the same directory as you installed your lemon directory to or the same directory as the script you are running is in.

Warning:DO NOT REMOVE VARIABLES FROM THE conf.py CONFIG FILE. You must make sure that all the options are available even if they are set to nothing otherwise the Lemon modules may not function correctly.

How the file is structured

Have a look at the snippit below:

[session]

;----------------;
; Cookie Options ; 
;----------------;

; Lifetime in seconds of cookie or, if 0, until browser is restarted.
cookie.lifetime = 0


; The path for which the cookie is valid.
cookie.path = /

The main section is called session and the variable names are just strings. Any line which is blank or starts with ; or # is ignored.

When the lemon/__init__.py file is intialised when the lemon module is imported the sys.path variable is searched for the Lemon.ini file. The first match is parse using the ConfigParser module and the results are left in the object lemon.config

To access the variables use code similar to this:

import lemon
print lemon.config.get('session','cookie.path')

See the ConfigParser module for full details.

You can include your own variables in the code and access them in a similar way.

Default Values Mechanism

Lemon doesn't always load default values from the Lemon.ini file. Many Lemon functions take their own arguments and only use the values from the Lemon.ini file if no arguments are specified or the argument useDefaults is set to True.

The four cases are best illustrated in code:

# Start a session with the defaults
lemon.session.start()
# Same as 
lemon.session.start(useDefaults=True)


# Do NOT load default settings but set type to 'db'
lemon.session.start(type='db') 
# Load default settings then set type to 'db'
lemon.session.start(useDefaults=True, type='db') 
Bugs:It is not implemented in code like this at the moment in Lemon 0.2.4.

Choosing Which Bundled Software To Use

Lemon comes bundled with a number of pieces of software including Cheetah and Gadfly. By default Lemon uses these versions of the software rather than any others which are installed. It does this by putting the path to the external directory of the lemon folder earlier in the sys.path list than the default directroy for modules. This means that when a module is imported the one that came with Lemon will be imported first.

If you wish to use a different version you should simply delete the version in the external directory of the lemon folder. Python will then find your version instead.

WARNING: YOU SHOULD NOT ALTER THE PATHS AS THIS MAY RESULT IN LEMON NOT FINDING OTHER MODULES IT NEEDS.

Be aware that the wrapper functions that come with Lemon are designed to work with a particular version of the included software and it is possible they may not work with the version you are using.

Coding Methadologies

Not written yet.

Extreme Programming

Not written yet.

Middle Kit

Not written yet.

Developer Guide

Documentation Conventions

Documentation for Lemon modules should be written as a reStructuredText ASCII file named README.txt.

It should include the variables... # XXX ToDo

and the sections:

DocStrings

Docstrings should be written in reStructuredText.

General Lemon Development

Not written yet.

Coding Standards

Not written yet.

Contributing

Not written yet.

Releasing a Package

Not written yet.

Appendicies

Lemon README

Lemon is a suite of pure Python modules for rapidly developing web applications. Includes: database, webserver, auth & session management, form and templating tools, docs and examples. Flexible enough to use on its own or with other solutions like Apache.

Author:James Gardner
License:Various open source licences.
Version:0.2.4
Status:Beta

Documentation

README
Including the LICENCE, CHANGES, BUGS, TODO etc..
User Guide
Complete guide to how to use the module.
Developer Guide
How to develop new drivers for the module.
Author:James Gardner
Organisation:Xecos Information Soluitons http://www.xecos.com/
Copyright:Copyright James Gardner 2002 - 2003. All Rights Reserved.
License:Various open source licences.
Contact:james@jimmyg.org
Summary:Lemon is a suite of pure Python modules for rapidly developing web applications. Includes: database, webserver, auth & session management, form and templating tools, docs and examples. Flexible enough to use on its own or with other solutions like Apache.
Version:0.2.4
Requires:Python 2.2 or above. Optionally MySQL DB Cursor.
Since:2002-12-25
Status:Beta
Todo:A planned change to an object. If the optional argument ver is given, then it specifies the version for which the change will be made. Multiple todo fields may be used if multiple changes are planned.

Contents

Licence

The components of the Lemon modules are released under various open source licences. The portions written by James Gardner are covered by the GNU GPL below. See the documentation for the relevant module for the licence of each component.

            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.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    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.

  <signature of Ty Coon>, 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.

Changes

0.0 - James Gardner's Modules

  • Many useful pieces of web code from various projects gathered in a directory.

0.1 - Xecos Web Modules

  • Much more robust structuring of code, broad range of modules coverd.

0.2 - Lemon modules

0.2.0

  • Total re-write of all code.
  • Complete DB interface rather than a few functions, DB-API 2.0 compatible.
  • Custom date classes written
  • Gadfly, Cheetah bundled with code.
  • Session management implementation separated from interface allowing development of storage drivers.
  • Code re-modelled in the light of the PHP way of doing things.
  • Auth management features.
  • Implementation of configuration file for default variable setting.
  • All known bugs fixed.
  • Renamed from Xecos to Lemon.
  • Propriotary code removed.
  • Simpler techniques discarded in favour of ones which Python programmers already use.
  • Attribute style access to variables removed in favour of the more compatible dict-style access.

0.2.1

  • Implementation of db.builder layer
  • Re-write of form generation code and fields code to be compatible with the db.builder layer.
  • Documentation started
  • Code structured properly, distutils script working correctly

0.2.2

  • Re-structuring of modules into interface/driver implementation
  • Module documentation generated with EPyDoc

0.2.3

  • Create a new auth driver which doesn't use Alter.. some databases don't support it hence avoid Gadfly Cursor Problem.
  • Rename the old alter-based db driver dbalter.py
  • Modify Gadfly Create Tables code to separate internal from normal db calls
  • Implemenation of Gadfly ALTER code to allow ALTER. Must specify a default value.
  • Completion of db.builder layer with many field options for each type.

0.2.4

  • Complete module restructuring

  • Basic documentation written

  • generate.py script to perform common tasks including:
    • Generate documentation.
    • Create examples and gadfly databases.
    • Create a module zip file.
    • Precompile all modules.
    • Generate a module reference.
  • Inclusion of epydoc, docutils, reStructuredText, py2html, pyFontify

  • Re-write of tools to give a python as well as command line interface.

  • Removal of dependance on an external config file by implementing as a dictionary

  • Alter SQL command

  • Full and robust support for Gadfly

  • Addition of BOOL Type to db and db.buider

  • Separation of lemon into lemon.common

0.2.6

  • Complete re-write of the database layer - now much more robust.
    • Types engine to convert Python->SQL and SQL->Python using cursor.description information or by maintaing a types table.
    • Autoconvert options available in the function calls for SQL statements
    • Different fetchmodes: dict, tuple, attribute/dict/tuple accessed via a functional interface
    • Debuging mode logs SQL and types information
    • mx.ODBC.windows cursor written for MS Access useage
  • Major additions to the auth module including automatic ability to send password reminders via email.

  • All modules re-written for Python 2.3 date classes
    • Features for standard date formatting.
    • Basic implementation of Python 2.3 date classes for use with Python < 2.3
  • html.form module totally re-written using a much more defined structure

0.2.8 a,b

  • Important tidying up of the 0.2.6 release.

0.2.9

  • Re-write of the database layer again -> split it up into connection and cursor objects.. more intuitive for the Python programmer and also compatible with the thinking behind the DB 2.0 API making the db layer a possible candiate for a future release of the DB API.
  • Gadfly, ODBC and MySQL support now fully working.
  • Re-write of code to enable different formats for the conversions etc.
  • Re-write of the connect() method so that the classes stop faffing around with dictionaries.
  • Removal of dependance on the lemon.conf module from session, db and auth modules.
  • Re-write of the session module. Now uses two tables one for expiry information and one for the actual session store. It actually does clean up unwanted sessions and has a clearly defined role and interface. Also has the documentation written.

0.2.10

  • Implementation of a traceback system entirely backwards compatible with cgitb but allowing custom error handling as well.
  • Examples now all work.
  • Minor bug fixes with the dbCreateTables and dbDroptables scripts.
  • Fuller documentation in the autogenerated reference.

Credits

The Lemon modules and documentation have been programmed by James Gardner - http://www.jimmyg.org

TODO

db

  • RENAME sql
  • Write a Python PEP using DB as a recommendation
  • Write a Postgresl drivers
  • Write a proper unit test
  • Make sure Gadfly works with builder. Fix the max issues for empty tables.

date

  • Fix the issues with mx modules.

auth

  • Restructure functions so that custom User tables can be easily written
  • Auth Encryption type: password etc

html.form

  • RENAME form
  • Implement fields for each of the types.

html.template

  • RENAME template
  • Implement a new dreamweaverMX style template for statically creating files.
  • Implement a PHP style version <%python %>

db.builder

  • RENAME data
  • Re-implement columns based on html.forms
  • Re-implement notNULL as required
  • Implement a way of recursively getting more SQL information from joined fields.
  • Implement foreign key fields.
  • Fix the datetime issues.

session

  • Implement a file based PHP storage method

Benefits of Lemon

Will run on a shared hosting account. Is a set of useful modules. Put External in root directory. Create basic forms automatically Make errors more descriptive, less instructive remove raise errors in dodgy code use dictionary insetead of config

Bugs

  • webserver.py - Location doesn't work - find out why.
  • Builder doesn't work with Gadfly
  • Builder datetime fields don't work

Gadfly README

Version:1.0.0 for Lemon 0.2.4
Status:Stable if used correctly.

Gadfly is a simple relational database system implemented in Python based on the SQL Structured Query Language. It is distributed with Lemon so that users without access to a database such as MySQL or PostgreSQL can still use the Lemon modules. The Gadfly homepage is http://gadfly.sf.net/.

Author:Aaron Watters
Maintainers:http://gadfly.sf.net/
Copyright:Aaron Robert Watters, 1994
README
Including the LICENCE
User Guide
Information on how to use Gadfly with DILL.

Purpose of This Document

The purpose of this document is not to exlpain the details of the GadflyB5 relational detabase. Those details are explained in the Gadfly documentation at http://gadfly.sf.net/.

Instead the purpose is twofold:

  1. To explain how to use Gadfly with the Database Interface Layer for Lemon, (DILL), which is the lemon.db module.
  2. To outline the problems with Gadfly that prevent it being an ideal Python database and the work-arounds that have been written into Lemon to make Gadfly more useful.

Licence

The gadfly and kjbuckets source is copyrighted, but you can freely use and copy it as long as you don't change or remove the copyright:

Copyright Aaron Robert Watters, 1994

All Rights Reserved

Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appears in all copies and that both that copyright notice and this permission notice appear in supporting documentation.

AARON ROBERT WATTERS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL AARON ROBERT WATTERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Cheetah README

Cheetah is a Python-powered template engine and code generator. It can be used as a standalone utility or it can be combined with other tools. Cheetah has many potential uses, but web developers looking for a viable alternative to ASP, JSP, PHP and PSP are expected to be its principle user group.

Maintainers:http://cheetahtemplate.org
README
Including the LICENCE

Cheetah has its own documentaion which can be read online at http://cheetahtemplate.org/docs/users_guide_html_multipage/

lemon.html.template includes a wrapper for Cheetah do it can be use in the same way as other Lemon templates.

Status:Marked Beta but actually very stable.

Contents

Cheetah

Copyright ©2001, The Cheetah Development Team: Tavis Rudd, Mike Orr, Ian Bicking, Chuck Esterbrook. Permission to use, copy, modify, and distribute this software for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the names of the authors not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission.

THE AUTHORS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Optik README

Licence

The optik package (Cheetah.Utils.optik) is based on Optik 1.3, http://optik.sourceforge.net/, ©2001 Gregory P Ward gward@python.net. It's unmodified from the original version except the import statements, which have been adjusted to make them work in this location. The following license applies to optik:

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

py2html README

Licence

(c) Copyright by Marc-Andre Lemburg, 1998 (mailto:mal@lemburg.com)

    Permission to use, copy, modify, and distribute this software and its
    documentation for any purpose and without fee or royalty is hereby granted,
    provided that the above copyright notice appear in all copies and that
    both that copyright notice and this permission notice appear in
    supporting documentation or portions thereof, including modifications,
    that you make.

    THE AUTHOR MARC-ANDRE LEMBURG DISCLAIMS ALL WARRANTIES WITH REGARD TO
    THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
    FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
    INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
    FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
    NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
    WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !

docutils README

Licence

Author:David Goodger
Contact:goodger@users.sourceforge.net
Revision:1.1
Date:2003/08/12 09:17:12
Copyright:This module has been placed in the public domain.

epydoc README

Version:2.0
Author:Edward Loper <edloper@gradient.cis.upenn.edu>
Url:http://epydoc.sourceforge.net

Licence

IBM Open Source License

dtuple README

Description:Database Tuple handling
Author:Greg Stein
Licence:Public Domain.
Copyright:No Copyright, no Rights Reserved, and no Warranties.
URL:http://www.lyra.org/greg/python/dtuple.py

PyFontify README

# Based on FontText.py by Mitchell S. Chapman,
# which was modified by Zachary Roadhouse,
# then un-Tk'd by Just van Rossum.
# Many thanks for regular expression debugging & authoring are due to:
#    Tim (the-incredib-ly y'rs) Peters and Cristian Tismer
# So, who owns the copyright? ;-) How about this:
# Copyright 1996-1997: 
#    Mitchell S. Chapman,
#    Zachary Roadhouse,
#    Tim Peters,
#    Just van Rossum
#
# Version 0.4 - changes copyright (C) 2001 Mark Pilgrim (f8dy@diveintopython.org)
#   2001/02/05 - MAP - distinguish between class and function identifiers
#   2001/03/21 - MAP - get keywords from keyword module (instead of hard-coded list)
#   2001/03/22 - MAP - use re module instead of deprecated regex module

roman README

This program is free software; you can redistribute it and/or modify
it under the terms of the Python 2.1.1 license, available at
http://www.python.org/2.1.1/license.html

XYAPTU README

"XYAPTU: Lightweight XML/HTML Document Template Engine for Python"

__version__ = '1.0.0'
__author__= [
  'Alex Martelli (aleax@aleax.it)', 
  'Mario Ruggier (mario@ruggier.org)'
]
__copyright__ = '(c) Python Style Copyright. All Rights Reserved. No Warranty.'
__dependencies__ = ['YAPTU 1.2, http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52305']
__history__= {
  '1.0.0' : '2002/11/13: First Released Version',
}

YAPTU

Presumed public domain or Python-style copyright.

"Yet Another Python Templating Utility, Version 1.2"

© 2002-2003 James Gardner