Thursday, July 02, 2009

NWSGI: Configuration and Dispatching

NWSGI, as I may have mentioned before, is the creation of Jeff Hardy and is "a .NET implementation of the Python WSGI specification for IronPython. It is implemented as an ASP.NET HttpHandler for use with IIS 6 and 7". The goal is to be able to run Python applications like Django, Trac and Pylons on IronPython. It can also be used on the Microsoft Azure (cloud computing) platform.

Version 2 is now in beta, and with it come several important changes. In a series of blog entries Jeff has been explaining these changes; and these four entries focus on configuring and dispatching.
For the most part, NWSGI can be used without any configuration. All you have to do is create a .wsgi file, throw it in a directory, let IIS know what’s going on, and you’re good to go! Of course, if it was always that easy, configuration wouldn’t exist. To really work with NWSGI, you need to understand its configuration. It helps if you’re already familiar with web.config files; if not, check this out (but hurry back!).

NWSGI uses .NET’s built-in configuration system (System.Configuration), so the first thing that needs to be done is to let the .NET Framework know about the custom NWSGI configuration section.
NWSGI has a fairly simple task: given a URL, call some Python code that produces some output. The devil, as always, is in the details.

What is WSGI?

NWSGI is an implementation of the Python WSGI specification (PEP 333). WSGI is the Web Server Gateway Interface, “a simple and universal interface between web servers and web applications or frameworks”, as defined in PEP 333.

OK, so what does that mean?
Let’s say we’re dealing with a much larger Python application, coolapp, that is installed at C:\coolapp-1.1\. Unfortunately, coolapp doesn’t provide a ready-made .wsgi file for us, but it does provide a function (coolapp.dispatchers.wsgi_application) that we can use by writing a little wrapper that looks something like:

import sys
import coolapp.dispatchers.wsgi_application
application = coolapp.dispatchers.wsgi_application

We could save this as coolapp.wsgi and follow either of two methods from last time, but since we’re not doing anything fancy in the wrapper, NWSGI provides a shortcut.
The normal procedure for configuring NWSGI leaves an unsightly URL wart: the URL must contain the .wsgi file. There are two ways to get rid of that wart: URL rewriting and wildcards.

When using URL rewriting, the web server changes ("rewrites") the incoming URL into something NWSGI can understand. IIS 7 has a URL rewriting extension to do just that. It's quite easy to use, too.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.