Using Python with IIS: how and common mistakes

Is it possible to use Python to write small ASP-like scripts. In this post we will see how to use it, and the common mistakes you can enconter in your road to the snake…
First of all, Microsoft has an article about it:

Python is an interpreted scripting language similar in concept to Microsoft Visual Basic Script (VBScript), Microsoft JScript, Perl, or other scripting languages. While Internet Information Server (IIS) uses the Windows Scripting Host for its VBScript and JScript needs, IIS can use other script interpreters for Active Server Pages (ASP) as well as simple Common Gateway Interface (CGI) scripts. This article describes how to use Python as your scripting language of choice for both CGI and ASP.

Using Python Scripts with IIS.

To use python you can also install the python 2.5 standard interpreter (we used it).Here we report a small example:

<%@LANGUAGE=Python%>
<HTML>
<head></head>
<body>
<h1>Python Test</h1>

<%
#do some python stuff here

Response.Write('Python Test<br>')
Response.write('<h3>Smaller heading</hr>')
%>

</body>
</html>

We have played on Windows Server 2003SP2 with IIS 6.0.
The first thing to know is that the python interpreter is booted only once by IIS.

So, once imported a module, you cannot easily “reload” it.

For instance if you create the module “foo” and you use it on an asp script, if you change foo the new changes will not be visible unless you restart IIS.

You can solve this problem using the python reload() function.

Anyway it is a bit tircky, because we read on documentation about the built-in reload function:

If a module imports objects from another module using fromimport …, calling reload() for the other module does not redefine the objects imported from it

An example code to do a successful reloading is the following:
[python]import sys
# Import Constants and client library call
try:
import mymodule
except ImportError:
# Add Configuration path:
sys.path.append("D:/lib/pathtomylib/.")
import mymodule
# Force reload of my module:
reload(mymodule)[/python]
Keep in mind you must know a bit about ASP objects (like Response and Request) to live in this world.

Conclusions

Programming ASP in Python is it possible, and there is also a persistent interpreter: it is an ace for small integration, a bit more risky for big project.
A deeper discussion about reloading python modules can be found here, in another  context.

By the way, Mercurial has a very smart import mechanics, but this is another story and will have a post on its own…

Resources: