MikeTeo.net

A Software Developer’s Blog (Wanna Email Me?)

Pylons

January 13, 2008 By miketeo

Introduction

Pylons is a lightweight web framework emphasizing flexibility and rapid development
This page is an attempt to put together a list of common classes and functions that a Pylons developer will often need to access.

Documentation Links

Global Variables for Controllers

The following list is taken from Pylons Official Docs - Getting Started.

object description
session Acts as a dict to store session data.
request The request object
response The response object, headers, cookies and status code can be set on this which will be used for the response
abort Function to abort the request immediately by raising an HTTPException according to the specified status code
redirect_to Function to redirect the browser to a different location via the HTTP 302 status code (by raising an HTTPException)
render Function to render a template and return a string
h Your project’s lib/helpers.py module. By default, this module exposes all functions available from the WebHelpers package. Keep in mind when reading the WebHelpers docs that all the functions listed should be prefixed by h. when used under Pylons.
c (described in Passing Variables to Templates)
g (described in Application Globals and Persistent Objects)
config Dictionary-like object for accessing .ini file directives and other Pylons configuration options.
cache, etag_cache Caching objects and functions. (described in the Caching in Templates and Controllers doc)
jsonify Action decorator to format output as JavaScript Object Notation.
validate Decorator for convenient form validation with FormEncode. (further described in the Form Handling document)
_, N_, ungettext Internationalization / localization functions. (described in the Internationalization and Localization doc)
model Access to your model package, however you choose to define it.

Mako Templates Syntax

The code formatting in the examples are a bit off. The dumb wordpress editor doesn’t seem to save <code> and <pre> correctly in <table>.

Name Example
Expression Substitution this is x: ${x}
pythagorean theorem: ${pow(x,2)+pow(y,2)}
Expression Escaping

${ "This is some text " | u,trim }

  • u : URL escaping, provided by urllib.quote_plus(string.encode('utf-8'))
  • h : HTML escaping, provided by cgi.escape(string, True)
  • x : XML escaping
  • trim : whitespace trimming, provided by string.strip()
  • entity : produces HTML entity references for applicable strings, derived from htmlentitydefs
  • unicode : produces a Python unicode string (this function is applied by default).
  • decode.<some encoding> : decode input into a Python unicode with the specified encoding
  • n : disable all default filtering; only filters specified in the local expression tag will be applied.

More details

Control Structure

% if x==5:
this is some output
% endif

% for a in ['one', 'two', 'three', 'four', 'five']:
% if a[0] == ‘t’:
its two or three
% elif a[0] == ‘f’:
four/five
% else:
one
%endif
% endfor

Comments

## this is a comment....text ...

<%doc>
these are comments more comments
</%doc>

Python Blocks this is a template
<%
x = db.get_resource(’foo’)
y = [z.element for z in x if x.frobnizzle==5]
%>
% for elem in y:
element: ${y}
% endfor
Module-level Blocks <%!
import mylib
import re
def filter(text):
return re.sub(r’^@’, ”, text)
%>
Page Tag

<%page args="x, y, z='default'"/>

<%page cached="True" cache_type="memory"/>

Include Tag

<%include file="header.html"/>
hello world

<%include file="footer.html"/>

Def Tag

<%def name="myfunc(x)">
this is myfunc, x is ${x}
</%def>

${myfunc(7)}

Namespace Tag <%namespace file="functions.html" import="*"/>
Inherit Tag <%inherit file="base.html"/>
Call Tag

<%def name="buildtable()">
<table>
<tr><td>
${caller.body()}
</td></tr>
</table>
</%def>

<%call expr="buildtable">
I am the table body.
</%call>

More Details.

Text Tag <%text filter="h">
heres some fake mako ${syntax}
<%def name="x()">${x}</%def>
</%text>

WorkingEnv Commands

Only 2 commands that are important:

  • To start the environment: source <working-env>/bin/activate
  • To stop the environment: deactivate

Add A Comment