Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

http.py 6.7KB

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