ajax.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # -*- coding: utf-8 -*-
  2. from .pyquery import PyQuery as Base
  3. from .pyquery import no_default
  4. from webob import Request
  5. from webob import Response
  6. try:
  7. from restkit.contrib.wsgi_proxy import HostProxy
  8. except ImportError:
  9. HostProxy = no_default # NOQA
  10. class PyQuery(Base):
  11. def __init__(self, *args, **kwargs):
  12. if 'response' in kwargs:
  13. self.response = kwargs.pop('response')
  14. else:
  15. self.response = Response()
  16. if 'app' in kwargs:
  17. self.app = kwargs.pop('app')
  18. if len(args) == 0:
  19. args = [[]]
  20. else:
  21. self.app = no_default
  22. Base.__init__(self, *args, **kwargs)
  23. if self._parent is not no_default:
  24. self.app = self._parent.app
  25. def _wsgi_get(self, path_info, **kwargs):
  26. if path_info.startswith('/'):
  27. if 'app' in kwargs:
  28. app = kwargs.pop('app')
  29. elif self.app is not no_default:
  30. app = self.app
  31. else:
  32. raise ValueError('There is no app available')
  33. else:
  34. if HostProxy is not no_default:
  35. app = HostProxy(path_info)
  36. path_info = '/'
  37. else:
  38. raise ImportError('restkit is not installed')
  39. environ = kwargs.pop('environ').copy()
  40. environ.update(kwargs)
  41. # unsuported (came from Deliverance)
  42. for key in ['HTTP_ACCEPT_ENCODING', 'HTTP_IF_MATCH',
  43. 'HTTP_IF_UNMODIFIED_SINCE', 'HTTP_RANGE', 'HTTP_IF_RANGE']:
  44. if key in environ:
  45. del environ[key]
  46. req = Request.blank(path_info)
  47. req.environ.update(environ)
  48. resp = req.get_response(app)
  49. status = resp.status.split()
  50. ctype = resp.content_type.split(';')[0]
  51. if status[0] not in '45' and ctype == 'text/html':
  52. body = resp.body
  53. else:
  54. body = []
  55. result = self.__class__(body,
  56. parent=self._parent,
  57. app=self.app, # always return self.app
  58. response=resp)
  59. return result
  60. def get(self, path_info, **kwargs):
  61. """GET a path from wsgi app or url
  62. """
  63. environ = kwargs.setdefault('environ', {})
  64. environ['REQUEST_METHOD'] = 'GET'
  65. environ['CONTENT_LENGTH'] = '0'
  66. return self._wsgi_get(path_info, **kwargs)
  67. def post(self, path_info, **kwargs):
  68. """POST a path from wsgi app or url
  69. """
  70. environ = kwargs.setdefault('environ', {})
  71. environ['REQUEST_METHOD'] = 'POST'
  72. return self._wsgi_get(path_info, **kwargs)