JSONRPCServlet.py :  » Web-Frameworks » Webware » Webware-1.0.2 » WebKit » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Web Frameworks » Webware 
Webware » Webware 1.0.2 » WebKit » JSONRPCServlet.py
"""JSON-RPC servlet base class

Written by Jean-Francois Pieronne

"""

import traceback
from MiscUtils import StringIO
try:
  import simplejson
except ImportError:
  print "ERROR: simplejson is not installed."
  print "Get it from http://cheeseshop.python.org/pypi/simplejson"

from HTTPContent import HTTPContent


class JSONRPCServlet(HTTPContent):
  """A superclass for Webware servlets using JSON-RPC techniques.

  JSONRPCServlet can be used to make coding JSON-RPC applications easier.

  Subclasses should override the method json_methods() which returns a list
  of method names. These method names refer to Webware Servlet methods that
  are able to be called by an JSON-RPC-enabled web page. This is very similar
  in functionality to Webware's actions.

  Some basic security measures against JavaScript hijacking are taken  by
  default which can be deactivated if you're not dealing with sensitive data.
  You can further increase security by adding shared secret mechanisms.

  """

  # Class level variables that can be overridden by servlet instances:
  _debug = 0 # set to True if you want to see debugging output
  # The following variables control security precautions concerning
  # a vulnerability known as "JavaScript hijacking". See also:
  # http://www.fortifysoftware.com/servlet/downloads/public/JavaScript_Hijacking.pdf
  # http://ajaxian.com/archives/protecting-a-javascript-service
  _allowGet = 0 # set to True if you want to allow GET requests
  _allowEval = 0 # set to True to allow direct evaluation of the response

  def __init__(self):
    HTTPContent.__init__(self)

  def respondToGet(self, transaction):
    if self._allowGet:
      self.writeError("GET method not allowed")
    HTTPContent.respondToGet(self, transaction)

  def defaultAction(self):
    self.jsonCall()

  def actions(self):
    actions = HTTPContent.actions(self)
    actions.append('jsonCall')
    return actions

  def exposedMethods(self):
    return []

  def writeError(self, msg):
    self.write(simplejson.dumps({'id': self._id, 'code': -1, 'error': msg}))

  def writeResult(self, data):
    data = simplejson.dumps({'id': self._id, 'result': data})
    if not self._allowEval:
      data = 'throw new Error' \
        '("Direct evaluation not allowed");\n/*%s*/' % (data,)
    self.write(data)

  def jsonCall(self):
    """Execute method with arguments on the server side.

    Returns Javascript function to be executed by the client immediately.

    """
    request = self.request()
    data = simplejson.loads(request.rawInput().read())
    self._id, call, params = data["id"], data["method"], data["params"]
    if call == 'system.listMethods':
      self.writeResult(self.exposedMethods())
    elif call in self.exposedMethods():
      try:
        method = getattr(self, call)
      except AttributeError:
        self.writeError('%s, although an approved method, '
          'was not found' % call)
      else:
        try:
          if self._debug:
            self.log("json call %s(%s)" % (call, params))
          self.writeResult(method(*params))
        except Exception:
          err = StringIO()
          traceback.print_exc(file=err)
          e = err.getvalue()
          self.writeError('%s was called, '
            'but encountered an error: %s' % (call, e))
          err.close()
    else:
      self.writeError('%s is not an approved method' % call)
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.