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

http://pyjamas.googlecode.com/ · Python · 62 lines · 28 code · 10 blank · 24 comment · 2 complexity · 3e618a0e39bb762485aab3418bfc124a MD5 · raw file

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