Skip to content

Instantly share code, notes, and snippets.

@dunkfordyce
Created April 4, 2010 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dunkfordyce/355364 to your computer and use it in GitHub Desktop.
Save dunkfordyce/355364 to your computer and use it in GitHub Desktop.
from spidermonkey import Runtime
import sys
rt = Runtime()
def jsprint(*args):
print " ".join(str(a) for a in args)
def _require(source):
cx = newcontext()
exports = {}
cx.add_global('exports', exports)
cx.execute(source)
return exports
def require(name):
return _require(open(name+'.js').read())
def newcontext():
cx = rt.new_context()
cx.add_global("print", jsprint)
cx.add_global("require", require)
return cx
cx = newcontext()
if len(sys.argv) == 2:
main = require(sys.argv[1])
else:
main = _require("""
exports.app = function(env) {
print(env.REMOTE_HOST);
return {
status: '200 OK',
body: ["I'm content from javascript.. or is it python..?!"],
headers: {
'content-type': 'text/plain'
}
};
};
""")
from wsgiref.simple_server import make_server
def simple_app(environ, start_response):
ret = main['app'](environ)
headers = [(str(k), str(ret['headers'][k])) for k in ret['headers']]
start_response(str(ret['status']), headers)
return [str(s) for s in ret['body']]
httpd = make_server('', 8000, simple_app)
print "Serving on port 8000..."
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment