123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import requests
  2. from itertools import cycle
  3. from searx import settings
  4. class HTTPAdapterWithConnParams(requests.adapters.HTTPAdapter):
  5. def __init__(self, pool_connections=requests.adapters.DEFAULT_POOLSIZE,
  6. pool_maxsize=requests.adapters.DEFAULT_POOLSIZE,
  7. max_retries=requests.adapters.DEFAULT_RETRIES,
  8. pool_block=requests.adapters.DEFAULT_POOLBLOCK,
  9. **conn_params):
  10. if max_retries == requests.adapters.DEFAULT_RETRIES:
  11. self.max_retries = requests.adapters.Retry(0, read=False)
  12. else:
  13. self.max_retries = requests.adapters.Retry.from_int(max_retries)
  14. self.config = {}
  15. self.proxy_manager = {}
  16. super(requests.adapters.HTTPAdapter, self).__init__()
  17. self._pool_connections = pool_connections
  18. self._pool_maxsize = pool_maxsize
  19. self._pool_block = pool_block
  20. self._conn_params = conn_params
  21. self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block, **conn_params)
  22. def __setstate__(self, state):
  23. # Can't handle by adding 'proxy_manager' to self.__attrs__ because
  24. # because self.poolmanager uses a lambda function, which isn't pickleable.
  25. self.proxy_manager = {}
  26. self.config = {}
  27. for attr, value in state.items():
  28. setattr(self, attr, value)
  29. self.init_poolmanager(self._pool_connections, self._pool_maxsize,
  30. block=self._pool_block, **self._conn_params)
  31. if settings['outgoing'].get('source_ips'):
  32. http_adapters = cycle(HTTPAdapterWithConnParams(pool_connections=100, source_address=(source_ip, 0))
  33. for source_ip in settings['outgoing']['source_ips'])
  34. https_adapters = cycle(HTTPAdapterWithConnParams(pool_connections=100, source_address=(source_ip, 0))
  35. for source_ip in settings['outgoing']['source_ips'])
  36. else:
  37. http_adapters = cycle((HTTPAdapterWithConnParams(pool_connections=100), ))
  38. https_adapters = cycle((HTTPAdapterWithConnParams(pool_connections=100), ))
  39. class SessionSinglePool(requests.Session):
  40. def __init__(self):
  41. super(SessionSinglePool, self).__init__()
  42. # reuse the same adapters
  43. self.adapters.clear()
  44. self.mount('https://', next(https_adapters))
  45. self.mount('http://', next(http_adapters))
  46. def close(self):
  47. """Call super, but clear adapters since there are managed globaly"""
  48. self.adapters.clear()
  49. super(SessionSinglePool, self).close()
  50. def request(method, url, **kwargs):
  51. """same as requests/requests/api.py request(...) except it use SessionSinglePool and force proxies"""
  52. global settings
  53. session = SessionSinglePool()
  54. kwargs['proxies'] = settings['outgoing'].get('proxies', None)
  55. response = session.request(method=method, url=url, **kwargs)
  56. session.close()
  57. return response
  58. def get(url, **kwargs):
  59. kwargs.setdefault('allow_redirects', True)
  60. return request('get', url, **kwargs)
  61. def options(url, **kwargs):
  62. kwargs.setdefault('allow_redirects', True)
  63. return request('options', url, **kwargs)
  64. def head(url, **kwargs):
  65. kwargs.setdefault('allow_redirects', False)
  66. return request('head', url, **kwargs)
  67. def post(url, data=None, **kwargs):
  68. return request('post', url, data=data, **kwargs)
  69. def put(url, data=None, **kwargs):
  70. return request('put', url, data=data, **kwargs)
  71. def patch(url, data=None, **kwargs):
  72. return request('patch', url, data=data, **kwargs)
  73. def delete(url, **kwargs):
  74. return request('delete', url, **kwargs)