PageRenderTime 18ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/jsonrpc/public/services/simplejson/jsonfilter.py

http://pyjamas.googlecode.com/
Python | 40 lines | 37 code | 2 blank | 1 comment | 1 complexity | a387f4159a95afa50a435a95f1e1e195 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0
  1. import simplejson
  2. import cgi
  3. class JSONFilter(object):
  4. def __init__(self, app, mime_type='text/x-json'):
  5. self.app = app
  6. self.mime_type = mime_type
  7. def __call__(self, environ, start_response):
  8. # Read JSON POST input to jsonfilter.json if matching mime type
  9. response = {'status': '200 OK', 'headers': []}
  10. def json_start_response(status, headers):
  11. response['status'] = status
  12. response['headers'].extend(headers)
  13. environ['jsonfilter.mime_type'] = self.mime_type
  14. if environ.get('REQUEST_METHOD', '') == 'POST':
  15. if environ.get('CONTENT_TYPE', '') == self.mime_type:
  16. args = [_ for _ in [environ.get('CONTENT_LENGTH')] if _]
  17. data = environ['wsgi.input'].read(*map(int, args))
  18. environ['jsonfilter.json'] = simplejson.loads(data)
  19. res = simplejson.dumps(self.app(environ, json_start_response))
  20. jsonp = cgi.parse_qs(environ.get('QUERY_STRING', '')).get('jsonp')
  21. if jsonp:
  22. content_type = 'text/javascript'
  23. res = ''.join(jsonp + ['(', res, ')'])
  24. elif 'Opera' in environ.get('HTTP_USER_AGENT', ''):
  25. # Opera has bunk XMLHttpRequest support for most mime types
  26. content_type = 'text/plain'
  27. else:
  28. content_type = self.mime_type
  29. headers = [
  30. ('Content-type', content_type),
  31. ('Content-length', len(res)),
  32. ]
  33. headers.extend(response['headers'])
  34. start_response(response['status'], headers)
  35. return [res]
  36. def factory(app, global_conf, **kw):
  37. return JSONFilter(app, **kw)