http.py 6.0 KB

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