PageRenderTime 23ms CodeModel.GetById 17ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/jsonrpc/public/services/jsonrpc/cgihandler.py

http://pyjamas.googlecode.com/
Python | 62 lines | 37 code | 6 blank | 19 comment | 0 complexity | 3e618a0e39bb762485aab3418bfc124a MD5 | raw file
 1"""
 2  Copyright (c) 2006 Jan-Klaas Kollhof
 3
 4  This file is part of jsonrpc.
 5
 6  jsonrpc is free software; you can redistribute it and/or modify
 7  it under the terms of the GNU Lesser General Public License as published by
 8  the Free Software Foundation; either version 2.1 of the License, or
 9  (at your option) any later version.
10
11  This software is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  GNU Lesser General Public License for more details.
15
16  You should have received a copy of the GNU Lesser General Public License
17  along with this software; if not, write to the Free Software
18  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
19"""
20
21from jsonrpc import SimpleServiceHandler
22import sys,os
23
24
25class CGIHandler(SimpleServiceHandler):
26    def __init__(self, service, messageDelimiter="\n"):
27        self.sendData =[]
28        SimpleServiceHandler.__init__(self, service, messageDelimiter=messageDelimiter)
29
30    
31    def send(self, data):
32        self.sendData.append(data)
33        
34    def handle(self):
35        try:
36            contLen=int(os.environ['CONTENT_LENGTH'])
37            data = sys.stdin.read(contLen)
38        except:
39            data = ""
40        #execute the request
41        self.handlePartialData(data) 
42        self.sendReply()
43        self.close()
44    
45    def sendReply(self):
46        data = "\n".join(self.sendData)
47        response = "Content-Type: text/plain\n"
48        response += "Content-Length: %d\n\n" % len(data)
49        response += data
50        
51        #on windows all \n are converted to \r\n if stdout is a terminal and  is not set to binary mode :(
52        #this will then cause an incorrect Content-length.
53        #I have only experienced this problem with apache on Win so far.
54        if sys.platform == "win32":
55            import  msvcrt
56            msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
57        #put out the response
58        sys.stdout.write(response)
59        
60        
61def handleCGIRequest(service):
62    CGIHandler(service,messageDelimiter="\n").handle()