Since it’s been a while from my last post on this subject, let me recap what we’ve covered:
- Defined a minimal command line interface as a means of exercising the basic Python-PostgreSQL interface.
- Following Toon Koppelaars’ Helsinki (IT) Declaration, split the business logic into a separate module.
- Created a minimal WSGI interface as a template for the web interface.
- Added templating, first with Mako and then with Jinja2.
- Made the Psycopg2 interface more robust by paying more attention to error handling.
- Evaluated CherryPy and Flask as contenders for serving the database applications, but ended up choosing Werkzeug1.
- Added unit tests for the business logic and web interfaces.
- Explored optimistic locking over a four-part series and added a PostgreSQL specific-implementation.
I also took a detour to explore Python web frameworks. One of the first comments inquired about Tornado. I recently had the opportunity to experiment with it. There’s much to admire, particularly in terms of speed. However, the use of one-or-two-method handler classes essentially for each action (see the blog demo, for example) struck me as counterproductive. It reminded me of Jack Diederich’s “Stop Writing Classes” presentation.
Getting back to database UIs, I have added basic pagination to the listing of films. Here is an example of what it looks like:
The number of lines per page is currently hard-coded (see maxlines in FilmHandler.index), but eventually it should be configurable. The principal additions are the count() and slice() methods in the bl/film.py module. The first does a SELECT COUNT(*) FROM films, so that we can determine how many pages will be needed (the upcoming PostgreSQL 9.2 should improve performance of that query). The slice() method does a SELECT like the all() method but uses LIMIT and OFFSET to retrieve the subset of rows needed for the requested page number.
There are further refinements possible. For example, the list of page numbers/links at the bottom could get very long given enough data in the table. For now, correcting this is left as an exercise for the reader.
1 I’m glad to hear that Kenneth Reitz, Armin Ronacher and others are working on “merging” Werkzeug with Requests.