Skip to content

Instantly share code, notes, and snippets.

@raymyers
Created July 5, 2010 22:09
Show Gist options
  • Save raymyers/464745 to your computer and use it in GitHub Desktop.
Save raymyers/464745 to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
import sys
import httplib
from urlparse import urlparse
from time import time
try:
# Python 2.6
import json
except:
# Prior to 2.6 requires simplejson
import simplejson as json
def requests():
# 'for line in sys.stdin' won't work here
line = sys.stdin.readline()
while line:
data = json.loads(line)
yield data
line = sys.stdin.readline()
def respond(code=200, data={}, headers={}):
sys.stdout.write("%s\n" % json.dumps({"code": code, "json": data, "headers": headers}))
sys.stdout.flush()
def process(query):
request_body = ""
if "body" in query: request_body = query["body"]
request_headers = {}
if "headers" in query: request_headers = query["headers"]
method = query["method"]
url = query["url"]
u = urlparse(url)
# assume u.scheme = 'http'
if ':' in u.netloc:
host, port = u.netloc.split(':', 2)
port = int(port)
else: host, port = u.netloc, 80
path = u.path
if query: path += "?" + u.query
start = time()
conn = httplib.HTTPConnection(host,port)
conn.request(method, path, request_body, request_headers)
response = conn.getresponse()
elapsed = time() - start
return {
"request":{"url":url,"method":method,"headers":request_headers,"data":request_body},
"response":{"status":response.status,"reason":response.reason,"version":response.version,"elapsedMillis":round(1000*elapsed,2),"headers":response.getheaders(),"data":response.read()}
}
def main():
log("main")
for req in requests():
result = process(req["query"])
respond(data=result)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment