Fetching Django’s Model’s ‘verbose_name’ and/or Form’s ‘label’ Attribute

Problem:

You want to display some information in a database record in Django, but you also want to display the field’s verbbose name.  In other words, you want to display “What is your favorite Color?” instead of the field name, “favorite_color” or the slightly better “Favorite Color”.  This can be a particular problem if you have very cryptic field names for some reason or another.

The problem is that in Django the “pretty label” information can be defined in the Model’s fields as “verbose_name” or possibly in a related Form as “label”.  In my case I was using ModelForms to make life easier. ModelForms, among other things, take the “verbose_name” values from your Models and stuff it into the Form’s fields “label” values.  You could just create a ModelForm based on your Model, and then fetch the label, but the Label is not defined in the Form if a verbose_name was not defined for the model.  This grabs the pretty label if it exists, and falls back to the field name if its undefined.  This problem is also discussed on Stack Overflow as:.

Django – Iterate over model instance field names and values in template

I’ve provided this solution there as well.

Solution:

There should really be a built-in way to do this. I wrote this utility build_pretty_data_view that takes a model object and form instance (a form based on your model) and returns a SortedDict.

Benefits to this solution include:

  • It preserves order using Django’s built-in SortedDict.
  • When tries to get the label/verbose_name, but falls back to the field name if one is not defined.
  • It will also optionally take an exclude() list of field names to exclude certain fields.
  • If your form class includes a Meta: exclude(), but you still want to return the values, then add those fields to the optional append() list.

To use this solution, first add this file/function somewhere, then import it into your views.py.

utils.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4
from django.utils.datastructures import SortedDict

def build_pretty_data_view(form_instance, model_object, exclude=(), append=()):
    i=0
    sd=SortedDict()

    for j in append:
        try:
            sdvalue={'label':j.capitalize(),
                     'fieldvalue':model_object.__getattribute__(j)}
            sd.insert(i, j, sdvalue)
            i+=1
        except(AttributeError):
            pass

    for k,v in form_instance.fields.items():
        sdvalue={'label':"", 'fieldvalue':""}
        if not exclude.__contains__(k):
            if v.label is not None:
                sdvalue = {'label':v.label,
                           'fieldvalue': model_object.__getattribute__(k)}
            else:
                sdvalue = {'label':k,
                           'fieldvalue': model_object.__getattribute__(k)}
            sd.insert(i, k, sdvalue)
            i+=1
    return sd

So now in your views.py you might do something like this

from django.shortcuts import render_to_response
from django.template import RequestContext
from utils import build_pretty_data_view
from models import Blog
from forms import BlogForm
.
.
def my_view(request):
   b=Blog.objects.get(pk=1)
   bf=BlogForm(instance=b)
   data=build_pretty_data_view(form_instance=bf, model_object=b,
                        exclude=('number_of_comments', 'number_of_likes'),
                        append=('user',))

   return render_to_response('my-template.html',
                          RequestContext(request,
                                         {'data':data,}))

Now in your my-template.html template you can iterate over the data like so…

{% for field,value in data.items %}

    <p>{{ field }} : {{value.label}}: {{value.fieldvalue}}</p>

{% endfor %}

Good Luck. Hope this helps someone!

Solution

OMHE Microsyntax for Medical Device Interoperability: An Open-Source Alternative to the Continua Alliance

OMHE (Open Mobile Health Exchange), pronounced “ooommm” is an open-source microsyntax for medical devices, mobile text messaging, Twitter®, smart phones, and any system capable of sending a short text string. OMHE’s goal is to provide device interoperability between systems that transmit or receive fitness and wellness information. Its designed for use by both humans and machines. Unlike XML or JSON its simple enough that in most cases a person can type or read OMHE. OMHE still has enough syntactical structure to be parsed and used by machines or software. Another key design decision in OMHE is that OMHE does not define the mode of transport, but simply the data itself. This means OMHE can be blurted out by an electronic weight scale or sent from a human via mobile text message.

OMHE was developed by group of health hackers interested in making it easier to create systems that communicate health information. As an open source specification, there is no license or club to join. Unlike the Continua Alliance which costs thousands to join and who’s utility is questionable, OMHE is a grassroots project defining a practical solution to interoperability. Those interested in contributing code, content, time or funding to the OMHE project should first request to join the Google Group at http://groups.google.com/group/omhe_microsyntax. The OMHE project is hosted on Google Code at http://code.google.com/p/omhe/.

Django Production Deployment: How to Make Apache2 mod_wsgi and virtualenv for Python Play Nice

Problem:

You are a good little Python developer and you use virtualenv in your Python development.  If you aren’t using virtualenv you’re doing it wrong. You have one of the follwoing problems/desires.

  • You want/need to use a Python virtual environment in your production deployment to encapsulate your configuration
  • You have multiple Apache virtual hosts on the same machine and/or you are running serveral Python/Django applications with different or conflicting versions of Python packages.

Solution:

I will demonstrate the solution by installing a Pinax application.  Pinax is a website framework buit on top of Django.  Pinax has many dependencies (including a specific version of Django). We will use Pinax version 0.7.3 whcih requires Django 1.0. I found the the official Pinax deployment documentation very weak and it did not work for me out of the box.  Have no fear. The following steps should get you going.  You can also use this blog post as a general tutorial on production deployment of Django applications.  This solution was tested on Ubuntu 10.10 64-bit server edition.

Step 1: Install system pre-requisites:

$ sudo apt-get update
$ sudo apt-get install git-core build-essential python-setuptools python2.6-dev

Step 2: Install `pip`, `virtualenv`, and ‘virtualencwrapper’:

 $ sudo easy_install pip

Step 3: Install ‘virtualenv’ and ‘virtualenvwrapper’ with pip:

 $ sudo pip install virtualenv virtualenvwrapper

Step 5: Setup virtualenv wrapper to make dealing with Python virtual environments trivial.

This will let us use the command “workon” and say “workon ve” to switch to the “ve” virtual environment.  All wee need to do is add a couple items in our .baschrc file. You can use any text editor to do this but I will give the commands using “nano”.  Nano is a terminal based text editor pre-installed with Ubuntu.  ”vi” and “emacs” are also options.

$ cd ~ 
$ nano .bashrc

Add the following lines to the bottom of the file and then save it by typing CTL-x and then hit ‘y’ to confirm the save.

export WORKON_HOME=$HOME/.virtualenvs

source /usr/local/bin/virtualenvwrapper.sh

Now activate virtualenv wrapper by re-running the .bashrc

$ source .bashrc

Step 6: Download and install Pinax

Before we download Pinax, here is a little background. The Pinax installer will use pip to fetch other prerequisites and create the virtual environment.  This is special to Pinax. Under a non-Pinax configuration, you would download your app, create a virgin virtalenv, activate it, and then run pip to fetch prerequisites and install them to the new virtualenv.  For clarity and completeness I’m going to illustrate the these basic steps here. I’ll use an imaginary project name “foobar” (You don’t need to do this for Pinax):

$ wget http:/somewebsite/foobar.tar.gz
$ tar zxvf foobar.tar.gz
$ mkvirtualenv foobar-env --no-site-packages
$ workon foobar-env
(foobar-env)$ cd foobar
(foobar-env)$ pip install -r requirements.txt

This will install the prerequisites in the file “requirements.txt” to the virtual environment named “foobar-env”.

Okay back to the task at hand.  Let’s install Pinax. Download and untar/unzip Pinax:

$ wget http://downloads.pinaxproject.com/Pinax-0.7.3-bundle.tar.gz
$ tar zxvf Pinax-0.7.3-bundle.tar.gz
$ cd Pinax-0.7.3-bundle/

Create the virtualenv and install the prerequisites.  I’m calling my virualenv “pinax-env”.   This step could take a while.

$ python scripts/pinax-boot.py $WORKON_HOME/pinax-env

Activate (i.e. switch to) the virtualenv.

$ workon pinax-env

Next let’s create a directory called projects to hold our actual project

(pinax-env)$ cd ~
(pinax-env)$ mkdir projects
(pinax-env)$ cd projects

Now lets clone a new Pinax project based on the Pinax intranet_project base. The first line will display a list of all project types.

(pinax-env)$ pinax-admin clone_project -l
(pinax-env)$ pinax-admin clone_project intranet_project myintranet

Install Python Imaging Library (PIL) which seems to be missing from Pinax installer

(pinax-env)$ pip install PIL

Step 7 : Fire Up the Pinax Project

(pinax-env)$ cd myintranet/

(pinax-env)$ python manage.py syncdb

(pinax-env)$ python manage.py runserver

Point your browser at http://localhost:8000/ and you should see the Pinax default homepage.  If you are hosting remotely you may want to do the following:

(pinax-env)$ python manage.py runserver 0.0.0.0:8000

This will make Django serve over the Internet.  Note this is only development server.   We are just verifying things are working up to this point.  Now here is where it gets insteresting.  This blog post is about deployment on Apache!  Now we want to make install Apache 2, mod_wsgi, and tell Apache to serve the Pinax/Django project located at “~/projects/myintranet” using our virtualenv called “pinax-env.  I’m using “ubuntu” as the deault username.  So our home directory is “/home/ubuntu/”, our project directory is “/home/ubuntu/projects/myintranet” and the root of our virtalenvs is “/home/ubuntu/.virtualenvs/”.  Change this as needed to suit your system.

Step 8: Install Apache2 and mod_wsgi.

Hint don’t install mod_python too.  This can mess things up.

$ sudo apt-get install apache2 libapache2-mod-wsgi

Step 9: Configure Apache to serve our project

We need to tell Apache to server our project.  We do this by pointing Apache to a special  python-based WSGI configuration file for our project. For Pinax, a sample file is located at “deploy/pinax.wsgi” . For Apache, the main file you need to edit is “/etc/apache2/sites-available/default”.  Add the following lines in blue  to “/etc/apache2/sites-available/default”:

<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
<VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory /var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all </Directory> WSGIScriptAlias / /home/ubuntu/projects/myintranet/deploy/pinax.wsgi <Directory /home/ubuntu/projects/myintranet/deploy> Order deny,allow Allow from all </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /doc/ "/usr/share/doc/" <Directory "/usr/share/doc/"> Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 </Directory>

Now its time to complete our configuration by editing “home/ubuntu/projects/myintranet/deploy/pinax.wsgi”.  Pinax.wsgi file didnt work for me but the configuration I gleamed from mod_wsgi’s wiki on Virtual Environments will work.  Completely erase the default pinax.wsgi file and replace it with the following:

ALLDIRS = ['/home/ubuntu/.virtualenvs/pinax-env/lib/python2.6/site-packages',
'/home/ubuntu/projects',]

import os
import sys
import site

# redirect sys.stdout to sys.stderr for bad libraries like geopy that uses
# print statements for optional import exceptions.
sys.stdout = sys.stderr
prev_sys_path = list(sys.path)

for directory in ALLDIRS:
  site.addsitedir(directory)

# Reorder sys.path so new directories at the front.
new_sys_path = []
for item in list(sys.path):
    if item not in prev_sys_path:
        new_sys_path.append(item)
        sys.path.remove(item)
sys.path[:0] = new_sys_path 

activate_this = '/home/ubuntu/.virtualenvs/pinax-env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
from os.path import abspath, dirname, join
from site import addsitedir

sys.path.insert(0, abspath(join(dirname(__file__), "../../")))

from django.conf import settings
os.environ["DJANGO_SETTINGS_MODULE"] = "myintranet.settings"

sys.path.insert(0, join(settings.PINAX_ROOT, "apps"))
sys.path.insert(0, join(settings.PROJECT_ROOT, "apps"))

from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()

The key things that may change if the project path and/or virtual environment change are highlighted in blue.  Note you want to remove the following lines if you are setting up a regular Django project (one that is not based on Pinax).

sys.path.insert(0, join(settings.PINAX_ROOT, "apps"))
sys.path.insert(0, join(settings.PROJECT_ROOT, "apps"))

Step 10: Restart Apache and Cross your fingers

$ sudo apache2ctl restart

If the god s are smiling on you today you should be in business.  check by going to http://localhost/.  If not, you might want to check Apache’s error log.

$ cat /var/log/apache2/error.log

There are many other Django and Pinax specific setting you will likely want to change.  Please see the Django Project and the Pinax Project for more information. Good luck. :-)

HTTPS / SSL Configuration Checklist

I’m writing this for my own reference so I have all my notes in one place.  I hope it helps someone else out too.

The basic step to setting up certs are:

sudo -i
openssl genrsa 1024 > www.mysite.com.key
openssl req -new -key www.mysite.com.key > www.mysite.com.csr

Make sure the “Common Name” is your host name.  In this example its “www.mysite.com”

You can then give your CSR file to rapidssl, register.com, or other certificate provider.

To create a self-signed certificate “”a.k.a. snake oil” you can do the following:

sudo openssl x509 -req -days 365 -in www.mysite.com.csr -signkey www.mysite.com.key -out www.mysite.com.crt

In /etc/apache2/sites-available/default-ssl, make sure you put the IP Address in for _default_, make sure you add the ServerName directive, and make sure your SSL certs point to real files that exist.  See example:

<IfModule mod_ssl.c>
<VirtualHost _default_:443>
 ServerAdmin webmaster@localhost
 ServerName hive.communityeducationgroup.org
 DocumentRoot /var/www
 <Directory />
 ..
 ..
 #   SSL Engine Switch:
 #   Enable/Disable SSL for this virtual host.
 SSLEngine on
 SSLCertificateFile /etc/apache2/ssl/www.mysite.com.crt
 SSLCertificateKeyFile /etc/apache2/ssl/www.mysite.com.key
 SSLCACertificateFile /etc/apache2/ssl/intermediate.crt
 ..
 ..
</VirtualHost>
</IfModule>

Also make sure you enable the default-ssl site configuration!

a2ensite default-ssl
/etc/init.d/apache2 reload

How to Encrypt an EBS Volume (Disk) on Amazon EC2

Problem:

You are using Amazon EC2 cloud computer and you want to create an
encrypted EBS volume to store sensitive data.For example, you may have a requirement to
protect ‘data at rest’ if you are dealing with personal health information (PHI)
in the United States.

These instructions have been tested on Ubuntu 10.10 64-bit Server Edition.

Solution:

1.) Create an EBS disk and attach it to your instance in the AWS management console.

2.) Attach the device to an open /dev device.  In this example we will use ‘/dev/sdc’.

3.) On your EC2 instance perform the following steps.

sudo apt-get install -y cryptsetup
sudo modprobe sha256
sudo modprobe dm_crypt
sudo modprobe dm_mod
sudo modprobe aes
sudo cryptsetup luksFormat -c aes -h sha256 /dev/sdc
   #type YES and return enter a strong passphrase
sudo cryptsetup luksOpen /dev/sdc encrypted_disk
   #re-enter your passphrase
sudo mkfs.ext4 /dev/mapper/encrypted_disk
sudo mkdir /myencryptdisk
sudo mount -t ext4 /dev/mapper/encrypted_disk /myencryptdisk

And that’s it!  Remember you will need to re-enter the passphrase when remounting the EBS volume.  Good luck!

-Alan @aviars

How to Create a Geospatial Query with maxDistance in MongoDB using Python

My company (Videntity) has been providing support to the Earth Institute (Columbia University). One of the tasks is to build a geospatial web service for tracking health facilities in the developing world. Its called Georegistry.org. You can think of it like a back-end database for displaying information in GoogleMaps and other mapping software. You can say things like, “Show me all the religious primary schools in Miga (Nigeria)” or “Show me all the water points in Ghana”. It returns data in GeoJSON format which is easy for many different Geographic Information Systems (GIS) to use as input.

Its a bit like simplegeo.com, but its completely open source. Georegistry.org is still a work in progress but coming together nicely. You can download the source code here.  Anyhow I needed to support a geospatial search query with a maximum distance parameter.  After hours of trial and error and a few Internet hints here and there, I finally got it working.  Apparently, the trick is you need an ordered dictionary. This fact is not (as of this writing) in the MongoDB or pymongo documentation. This may seem simple enough but, alas you cannot order a dictionary (in Python) because a Python dictionary is just a mapping!  So we need to use the pymongo.son.SON package.  SON is a subclass of dict and preserves ordering. You can pass a SON object into pymongo’s find() method just like you would a standard Python dictionary.   Anyhow, here is a little example. I hope this helps someone else who stumbles on this problem. I was pulling my hair out for a few hours.

from pymongo import Connection
from pymongo.son import SON

def near_geoquery_with_max_distance(lat, lon, max_distance):
   """ Build the $near dict with your lat/lon values """
   near_dict = {'$near':[float(lat), float( lon)]}

   """ build the maxdistance dict with your max distance value """
   max_dist_dict={'$maxDistance': int(max_distance)}

   """ Create a SON object from our near_dict.
       ORDER IS IMPORTANT. THIS MUST BE FIRST!
   """
   q=SON(near_dict)

   """ Now add the 2nd item (max_dist_dict) to the ordered SON dict """
   q.update(max_dist_dict)

   """ Now put all of the above into a dict with using the key for your
       geospatial data
   """
   gq={'location': q}

   """ Connect to the DB, use you local settings """
   mconnection =  Connection("MONGO_HOST", "MONGO_PORT")
   db =        mconnection["MONGO_DB_NAME"]
   transactions = db["COLLECTION_NAME"]
   """perform the search.  all should work now."""
   mysearchresult=transactions.find(gq)
   .
   .
   .

Good Luck!

Postgresql Setup on Ubuntu 10.10

Here is a little cheat sheet for getting Postgress setup on Ubuntu and creating an initial database and dtabase user.  this will work if you are wanting to use Postgres with Django.

Install postgres and the python libraries:

sudo apt-get install postgresql-8.4 postgresql-client-8.4 python-psycopg2

Modify the config file to allow local connections:

sudo nano /etc/postgresql/8.4/main/pg_hba.conf

Add the line:

local     all         all     md5

Save the changes to the file and restart the server.

sudo /etc/init.d/postgresql restart

Set the password for the postgres user:

sudo passwd postgres

Change to the postgres user:

su - postgres

Create a new Database:

createdb mydb

Login to the postgres shell and point to our new database:

psql mydb

Now from the postgress shell create a user and give him access to the database:

mydb=> CREATE USER myuser WITH PASSWORD 'myPassword';
mydb=> GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;
mydb=\q

Done!

Serving Django Admin Static Media Files with Apache WSGI on Ubuntu

Here is a quick and simple configuration code recipe to serve the admin static files in a production environment using modWSGI and Apache 2.

Modify your apache2 configuration file. By default that would be:

/etc/apache2/sites-available/default

Just add the line:

Alias /media/ /var/www/media/

..under your VirtualHost setting, like so:

<VirtualHost *:80>
   ServerAdmin webmaster@localhost
   Alias /media/ /var/www/media/
   DocumentRoot /var/www

   <Directory />

      Options FollowSymLinks

      AllowOverride None

   </Directory>

   <Directory /var/www/>

      Options Indexes FollowSymLinks MultiViews

      AllowOverride None

      Order allow,deny

      allow from all

   </Directory>

WSGIScriptAlias /  /home/ubuntu/RESTCat/apache/django.wsgi
.
.
</VirtualHost>

Note that the WSGIScriptAlias points to your Django application configuration file. I keep it along side my project in a folder called ‘apache’ in a file called ‘django.wsgi’.

Now add a symbolic link to point apache to the admin static content like so:

sudo ln -s /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media /var/www/media

Now simply restart apache.

sudo apache2ctl restart

Your admin static files should now be served!

Enter to Win the West Wireless Veterans’ Health Innovation Challenge

The West Wireless Health Institute has issued a new $10,000 developer challenge targeting veteran’s health.  $10K is a decent chunk of change so I do encourage all you entrepreneurs and innovators out there to submit.  Here are the submission details.  Videntity won the last one, so we will not be responding to this one, however I’m willing to help and advise any entrepreneur who has a decent idea.  @reply me on Twitter if interested.  My Twitter handle is @aviars.

http://s3.amazonaws.com/wwhi.org/documents/VAi2_WWHI-Challenge_Submission_Guidelines.pdf

-Alan

Turn Your Wii Balance Board into an Internet Device for Weight Upload

So if anyone is looking for a fun, geek-out project on a Sunday afternoon, this one will do nicely. You do not need to know how to write code to get this working.  You only need a computer (or virtual machine) with Ubuntu Linux with a working Bluetooth adapter, a Wii Balance Board, and the ability input the instructions below into a terminal.

1. Setting Up Your Computer to Talk with a Wii Balance Board:

Open up a command line terminal on your Linux machine. These instructions are for Ubuntu 9.x/10.x. Other Linux distributions instructions will vary. First install the prerequisites through your distribution’s package manager.

$ sudo apt-get install autoconf autogen automake gcc bluetooth libbluetooth3-dev libgtk2.0-dev pkg-config python2.6-dev flex bison git-core libbluetooth-dev python-pygame python-tk

Check out the CWiid (get it? CWiid? Seaweed?) library using Git:

$ mkdir bin
$ cd bin
$ git clone http://github.com/abstrakraft/cwiid.git
$ cd cwiid

Compile the Cwiid library. At the command line execute the following

$ aclocal
$ autoconf
$ ./configure
$ make
$ sudo make install

You can test things with a Wii Remote by running the GUI (This GUI will not work on a headless server)

$ wmgui

Lets now install the python bindings:

$ cd python
$ sudo python setup.py install

If this works, then your computer is now read to connect to the balance board. If you have problems please see the cwiid documentaion. These instructions were tested on Ubuntu 10.

2. Using the Wii Balance Board Application:

Run the weightdemo.py application and immedatly press the red button on the bottom of your balance board to sync the bluetooth connection. If all goes well you will see a GUI display on your computer.

If you haven’t already done so, download and install the python-omhe library.

$ git clone git://github.com/aviars/python-omhe.git

Change into the python-omhe directory:

$ cd python-omhe

Install the python-omhe library.

$ sudo python setup.py install

Change into the directory containing the Wii Balance server code.

$ cd omhe/hardware/wiibalance

Run th ewiibalance_weight.py application.  This applications sends an HTTP POST callback of the weight and a user ID each time you present a user ID from standard input.

$ python ./wiibalance_weight.py

If you get an error message, r/w error or a bluetooth connection timeout just run the application again. check to make sure you don’t have another python process running and trying to access the board. Press ‘q’ to exit the application. Anything else is interpreted as the user’s identifier. So this is designed to work well with a card reader, number pad, or any other standard input that helps identify the user. This is how we are binding the user to his or her weight. There is no format for user ID here. You can use whatever makes sense for you, but if you are using a RESTCat server in a standard configuration, then an email address might make the most sense.  Other tokens could include a user’s mobile phone number or  master patient index (MPI).

This applicating will do 3 things each time you press enter: * Send your weight (via callback) along with some other information * Write your weight to a JSON file (filename defined in settings.py) * Print the JSON file to standard output (Most often the screen).  This is the preferred method for serving your weight because it is more efficient, but just for an academic exercise, the following section will demonstrate how we can make the weight available via a web server.

3. Serve Your Weight through a Simple Web Server:

There are two ways to do this; a push and a pull. The tools found in python-omhe illustrate both methods.

3.1 Pushing Your Weight with an HTTP Callback:

wiibalance_weight.py will push your information with an HTTP callback at the address defined in your settings.py file. This means that we will perform an HTTP client POST containing the weight information. You must write and make avalaible your own callback handler at the URL specified in your settings.py.

3.2 Pulling (Polling) Weight from a Webserver:

There are many tools you could use to do what I’m doing here.  This includes Django, Pylons, PHP, you name it.  Using wiibalance_server.py you can make your weight avalaible via a webserver. wiibalance_server.py is a simple web server written in pure Python that simply serves the file containing the weight information. This file is generated by wiibalance_weight.py and its filepath is defined in settings.py. By default this file’s name is wiiweightout.json. So lets have an example shall we? Use this command to start the server:

$ python wiibalance_server.py

You should see the message:

Serve forever

Make sure you are using a port not used by another process (such as Apache, etc.) Change this in settings.py.

Now your serving your weight. Use your browser or open another terminal and use Curl to point to the URL. By default, the webserver is serving on port 8002 and will bind to any IP (0.0.0.0). The following command:

$ curl http://127.0.0.1:8002

Will yield a JSON file result counting the user’s ID and weight.  The weight is expressed in OMHE Microsyntax: http://code.google.com/p/omhe

I’ll point out that you can connect your output to a RESTCat server and hence have a very easy means for storage and retrieval via a RESTful API.

You can find RESTCat at: http://github.com/aviars/RESTCat

Have fun! If you find and errors or gotchas in this post please @reply me on Twitter.  My username is @aviars

-Alan

References:

Some of these instructions were modified from Matt Cutt’s blog article:
http://www.mattcutts.com/blog/linux-wii-balanceboard/