Past month I presented my work on PythonSharp at Argentina PyCon 2012 (see Spanish post), a Python interpreter that I am writing in C#. As in other of my interpreter implementations, it can access native types. As a proof of concept, I wrote a minimal web server example:
from System import Array, Byte from System.Net import HttpListener from System.IO import Path, FileStream, FileMode, File root = "c:/apache-tomcat-6.0.18/webapps/docs" bytes = Array.CreateInstance(Byte,1024) listener = HttpListener() listener.Prefixes.Add("http://*:8000/") def process(context): filename = context.Request.Url.AbsolutePath if not filename or filename == '/': filename = "index.html" if filename[0] == '/': filename = filename[1:] print(filename) filename = Path.Combine(root, filename) print(filename) if not File.Exists(filename): context.Response.Abort() return input = FileStream(filename, FileMode.Open) bytes = Array.CreateInstance(Byte, 1024 * 16) nbytes = input.Read(bytes, 0, bytes.Length) while nbytes>0: context.Response.OutputStream.Write(bytes, 0, nbytes) nbytes = input.Read(bytes, 0, bytes.Length) input.Close() context.Response.OutputStream.Close() listener.Start() while True: context = listener.GetContext() print("new request") process(context)
The file at repo:
https://github.com/ajlopez/PythonSharp/blob/master/Src/PythonSharp.Console/examples/httpserver.py
To run the example, you should compile the solution. PythonSharp.Console project compiles to pysh.exe console program. You can change the root variable value, now it points to a set of static files in my disk, with Tomcat docs 😉 :
The code is based on my previous examples:
I can import .NET namespaces and manage them as modules. I’m working with .NET 3.5 (I like to use the minimal requirements) so I could not use other approaches to copy a file to the output response stream, see:
Best way to copy between two Stream instances
Now, I’m working on having the same implementation for my AjTalk Smalltalk virtual machine. But that’s a topic for another post.
Keep tuned!
Angel “Java” Lopez
http://www.ajlopez.com