http.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. from __future__ import absolute_import
  2. import urllib2
  3. from urllib import urlencode
  4. from urlparse import urlparse
  5. try:
  6. from urlparse import parse_qsl
  7. except ImportError: # pragma: no cover
  8. from cgi import parse_qsl # noqa
  9. from anyjson import deserialize
  10. from .. import __version__ as celery_version
  11. from .base import Task as BaseTask
  12. GET_METHODS = frozenset(["GET", "HEAD"])
  13. class InvalidResponseError(Exception):
  14. """The remote server gave an invalid response."""
  15. class RemoteExecuteError(Exception):
  16. """The remote task gave a custom error."""
  17. class UnknownStatusError(InvalidResponseError):
  18. """The remote server gave an unknown status."""
  19. def maybe_utf8(value):
  20. """Encode to utf-8, only if the value is Unicode."""
  21. if isinstance(value, unicode):
  22. return value.encode("utf-8")
  23. return value
  24. def utf8dict(tup):
  25. """With a dict's items() tuple return a new dict with any utf-8
  26. keys/values encoded."""
  27. return dict((key.encode("utf-8"), maybe_utf8(value))
  28. for key, value in tup)
  29. def extract_response(raw_response):
  30. """Extract the response text from a raw JSON response."""
  31. if not raw_response:
  32. raise InvalidResponseError("Empty response")
  33. try:
  34. payload = deserialize(raw_response)
  35. except ValueError, exc:
  36. raise InvalidResponseError(str(exc))
  37. status = payload["status"]
  38. if status == "success":
  39. return payload["retval"]
  40. elif status == "failure":
  41. raise RemoteExecuteError(payload.get("reason"))
  42. else:
  43. raise UnknownStatusError(str(status))
  44. class MutableURL(object):
  45. """Object wrapping a Uniform Resource Locator.
  46. Supports editing the query parameter list.
  47. You can convert the object back to a string, the query will be
  48. properly urlencoded.
  49. Examples
  50. >>> url = URL("http://www.google.com:6580/foo/bar?x=3&y=4#foo")
  51. >>> url.query
  52. {'x': '3', 'y': '4'}
  53. >>> str(url)
  54. 'http://www.google.com:6580/foo/bar?y=4&x=3#foo'
  55. >>> url.query["x"] = 10
  56. >>> url.query.update({"George": "Costanza"})
  57. >>> str(url)
  58. 'http://www.google.com:6580/foo/bar?y=4&x=10&George=Costanza#foo'
  59. """
  60. def __init__(self, url):
  61. self.parts = urlparse(url)
  62. self.query = dict(parse_qsl(self.parts[4]))
  63. def __str__(self):
  64. scheme, netloc, path, params, query, fragment = self.parts
  65. query = urlencode(utf8dict(self.query.items()))
  66. components = ["%s://" % scheme,
  67. "%s" % netloc,
  68. path and "%s" % path or "/",
  69. params and ";%s" % params or None,
  70. query and "?%s" % query or None,
  71. fragment and "#%s" % fragment or None]
  72. return "".join(filter(None, components))
  73. def __repr__(self):
  74. return "<%s: %s>" % (self.__class__.__name__, str(self))
  75. class HttpDispatch(object):
  76. """Make task HTTP request and collect the task result.
  77. :param url: The URL to request.
  78. :param method: HTTP method used. Currently supported methods are `GET`
  79. and `POST`.
  80. :param task_kwargs: Task keyword arguments.
  81. :param logger: Logger used for user/system feedback.
  82. """
  83. user_agent = "celery/%s" % celery_version
  84. timeout = 5
  85. def __init__(self, url, method, task_kwargs, logger):
  86. self.url = url
  87. self.method = method
  88. self.task_kwargs = task_kwargs
  89. self.logger = logger
  90. def make_request(self, url, method, params):
  91. """Makes an HTTP request and returns the response."""
  92. request = urllib2.Request(url, params, headers=self.http_headers)
  93. request.headers.update(self.http_headers)
  94. response = urllib2.urlopen(request) # user catches errors.
  95. return response.read()
  96. def dispatch(self):
  97. """Dispatch callback and return result."""
  98. url = MutableURL(self.url)
  99. params = None
  100. if self.method in GET_METHODS:
  101. url.query.update(self.task_kwargs)
  102. else:
  103. params = urlencode(utf8dict(self.task_kwargs.items()))
  104. raw_response = self.make_request(str(url), self.method, params)
  105. return extract_response(raw_response)
  106. @property
  107. def http_headers(self):
  108. headers = {"Content-Type": "application/json",
  109. "User-Agent": self.user_agent}
  110. return headers
  111. class HttpDispatchTask(BaseTask):
  112. """Task dispatching to an URL.
  113. :keyword url: The URL location of the HTTP callback task.
  114. :keyword method: Method to use when dispatching the callback. Usually
  115. `GET` or `POST`.
  116. :keyword \*\*kwargs: Keyword arguments to pass on to the HTTP callback.
  117. .. attribute:: url
  118. If this is set, this is used as the default URL for requests.
  119. Default is to require the user of the task to supply the url as an
  120. argument, as this attribute is intended for subclasses.
  121. .. attribute:: method
  122. If this is set, this is the default method used for requests.
  123. Default is to require the user of the task to supply the method as an
  124. argument, as this attribute is intended for subclasses.
  125. """
  126. url = None
  127. method = None
  128. def run(self, url=None, method="GET", **kwargs):
  129. url = url or self.url
  130. method = method or self.method
  131. logger = self.get_logger(**kwargs)
  132. return HttpDispatch(url, method, kwargs, logger).dispatch()
  133. class URL(MutableURL):
  134. """HTTP Callback URL
  135. Supports requesting an URL asynchronously.
  136. :param url: URL to request.
  137. :keyword dispatcher: Class used to dispatch the request.
  138. By default this is :class:`HttpDispatchTask`.
  139. """
  140. dispatcher = HttpDispatchTask
  141. def __init__(self, url, dispatcher=None):
  142. super(URL, self).__init__(url)
  143. self.dispatcher = dispatcher or self.dispatcher
  144. def get_async(self, **kwargs):
  145. return self.dispatcher.delay(str(self), "GET", **kwargs)
  146. def post_async(self, **kwargs):
  147. return self.dispatcher.delay(str(self), "POST", **kwargs)