first commit
[bitcoin:spesmilo.git] / jsonrpc / .svn / text-base / cgiwrapper.py.svn-base
1 import sys, os
2 from jsonrpc import ServiceHandler
3
4 class CGIServiceHandler(ServiceHandler):
5     def __init__(self, service):
6         if service == None:
7             import __main__ as service
8
9         ServiceHandler.__init__(self, service)
10
11     def handleRequest(self, fin=None, fout=None, env=None):
12         if fin==None:
13             fin = sys.stdin
14         if fout==None:
15             fout = sys.stdout
16         if env == None:
17             env = os.environ
18         
19         try:
20             contLen=int(env['CONTENT_LENGTH'])
21             data = fin.read(contLen)
22         except Exception, e:
23             data = ""
24
25         resultData = ServiceHandler.handleRequest(self, data)
26         
27         response = "Content-Type: text/plain\n"
28         response += "Content-Length: %d\n\n" % len(resultData)
29         response += resultData
30         
31         #on windows all \n are converted to \r\n if stdout is a terminal and  is not set to binary mode :(
32         #this will then cause an incorrect Content-length.
33         #I have only experienced this problem with apache on Win so far.
34         if sys.platform == "win32":
35             try:
36                 import  msvcrt
37                 msvcrt.setmode(fout.fileno(), os.O_BINARY)
38             except:
39                 pass
40         #put out the response
41         fout.write(response)
42         fout.flush()
43
44 def handleCGI(service=None, fin=None, fout=None, env=None):
45     CGIServiceHandler(service).handleRequest(fin, fout, env)