SQLARadialGraph in a Pyramid app

Mar 07, 2011 | categories: python, toscawidgets, pyramid View Comments

tw2.jit.SQLARadialGraph is a python class that encapsulates the awesome RGraph widget from the Javascript InfoVis Toolkit and automatically sets it up with JSON data from a sqlalchemy-mapped database. This post is a tutorial on how to make use of it in an application built on the Pyramid web framework.

1. Create a fresh pyramid app from the pyramid_alchemy paster template (instructions).

2. Create some sqlalchemy models with one-to-many and/or many-to-many relationships and populate the DB along the lines described in my SQLARadialGraph in a Turbogears 2.1 app tutorial.

3. Include tw2.jit and formencode in the requires list in your setup.py file and re-run python setup.py develop with your virtualenv active.

4. Include the Toscawidgets 2 middleware in the Pyramid WSGI stack by specifying egg:tw2.core#middleware just before your application's line in the pipeline setting inside development.ini.

5. Create a module /widgets.py with the following contents:

from tw2jitpyramiddemo import models
from tw2.jit import SQLARadialGraph

class UserGraph(SQLARadialGraph):
    id = 'whatever'
    base_url = '/jit_data'
    entities = [models.MyModel, models.MyGroup]
    width = '750'
    height = '533'

6. Expose the UserGraph widget in one of your views.

Specifically, modify /views.py and change the view_model(context, request) view to look something like:

from widgets import UserGraph

def view_model(context, request):
    return {'item':context, 'project':'tw2.jit-pyramid-demo',

7. Render the widget in the corresponding template.

If you're using Chameleon templates (/templates/model.pt) this looks like:

<div tal:content="structure jitwidget.display()"></div>

If you're using Mako templates (/templates/model.mak) this looks like:

${jitwidget.display() | n}

8. Open a route to the widget's own controller.

Add the following three lines to /__init__.py just before the return config.make_wsgi_app() line:

from widgets import UserGraph
jit_view = lambda c, r : UserGraph.request(r)
config.add_route('jit_data', '/jit_data', view=jit_view, xhr=True)

And we're done. Restart the app and checkout http://localhost:6543/1 and it might look something like this.

tw2.jit.SQLARadialGraph in the default pyramid_alchemy app

You can, of course, tweak all kinds of style and functional parameters on SQLARadialGraph like those outlined near the end of my post on using SQLARadialGraph in a Turbogears 2.1 app.

Maybe you disagree, but the Pyramid implementation above went much more smoothly than the TG 2.1 setup. I think I like it.

View Comments
blog comments powered by Disqus