Pyramid framework tips : WebHelpers html tags and Paginate

WebHelpers has many useful functions. WebHelpers html tags and paginate are very useful for Pyramid Applications.Some features are not compatible with Pyramid framework, please see documentations.

WebHelpers in Pyramid Applications: install WebHelpers with easy_install:

$ easy_install WebHelpers

In Pyramid Application in __init__.py:

def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
  ...
  config.add_subscriber(add_renderer_globals, BeforeRender)
  ...

In helpers.py module:

  # your helpers imports
  from webhelpers.html.tags import *

In subscribers.py module:

def add_renderer_globals(event):
    """ add helpers """
    event['h'] = helpers

In Mako Templates:

  ## text input
  ${h.text("name", model.name, class_ = "large", maxlength="100")}

How to use WebHelpers Paginate with SQLAlchemy?
In your controller code:

@view_config(route_name="category_list", renderer="category/list.html")
def list(request):
    """categories list """
    ...
    # db query
    dbsession = DBSession()
    query = dbsession.query(Customer)

    # paginate
    page_url = paginate.PageURL_WebOb(request)
    customers = Page(query,
                     page=int(request.params.get("page", 1)),
                     items_per_page=10,
                     url=page_url)

    return {"customers": customers}

Paginate format in Mako Templates:

<div class="pager">
  <% link_attr={"class": "btn small"} %>
  <% curpage_attr={"class": "btn primary small disabled"} %>
  <% dotdot_attr={"class": "btn small disabled"} %>
  ${customers.pager(format="$link_previous ~2~ $link_next",
    symbol_previous="«",
    symbol_next="»",
    link_attr=link_attr,
    curpage_attr=curpage_attr,
    dotdot_attr=dotdot_attr)}
</div>

paginate

I am using Bootstrap from Twitter as css framework.

Pyramid framework tips : MySQL Database settings

Installing MySQL DB-API driver on Kubuntu 11.10 in Console:

  sudo apt-get install libmysqlclient-dev
  sudo apt-get install python-dev

In virtual env of your Pyramid installation:

  $ easy_install mysql-python

For MS Windows installation details see please online book: The Definitive Guide to Pylons – James Gardner.

For SQLAlchemy in Pyramid framework in development.ini and production.ini:

  # mysql
  sqlalchemy.url = mysql://DB_USER:PASSWORD@localhost:3306/DATABASE_NAME
  sqlalchemy.pool_recycle = 3600

Pyramid framework tips: Form validation

For form validation in pyramid framework there is FormEncode package. FormEncode is a validation and form generation package. pyramid_simpleform is a add-on for pyramid framework and uses FormEncode.

SimpleForm in Pyramid Applications: install with easy_install:

$ easy_install pyramid_simpleform

In your controller code FormEncode Schema:

class CategoryForm(Schema):
  filter_extra_fields = True
  allow_extra_fields = True
  # category name not empty
  name = validators.String(not_empty=True)

 # edit function with form.validate()
 @view_config(route_name="category_edit", renderer="category/edit.html")
 def edit(request):
    """category edit """
    id = request.matchdict['id']
    dbsession = DBSession()
    category = dbsession.query(Category).filter_by(id=id).one()
    if category is None:
        request.session.flash("error;Category not found!")
        return HTTPFound(location=request.route_url("category_list"))        

    form = Form(request, schema=CategoryForm, obj=category)
    if "form_submitted" in request.POST and form.validate():
        form.bind(category)
        dbsession.add(category)
        request.session.flash("warning;The Category is saved!")
        return HTTPFound(location = request.route_url("category_list"))

    action_url = request.route_url("category_edit", id=id)
    return dict(form=FormRenderer(form),
                action_url=action_url)

See please full customers app code for template details.