Coverage for utilities/proxy.py: 31%
21 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-10 18:35 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-10 18:35 +0000
1from urllib.parse import urlparse
3from django.conf import settings
4from django.utils.module_loading import import_string
6__all__ = (
7 'DefaultProxyRouter',
8 'resolve_proxies',
9)
12class DefaultProxyRouter:
13 """
14 Base class for a proxy router.
15 """
16 @staticmethod
17 def _get_protocol_from_url(url):
18 """
19 Determine the applicable protocol (e.g. HTTP or HTTPS) from the given URL.
20 """
21 return urlparse(url).scheme
23 def route(self, url=None, protocol=None, context=None):
24 """
25 Returns the appropriate proxy given a URL or protocol. Arbitrary context data may also be passed where
26 available.
28 Args:
29 url: The specific request URL for which the proxy will be used (if known)
30 protocol: The protocol in use (e.g. http or https) (if known)
31 context: Additional context to aid in proxy selection. May include e.g. the requesting client.
32 """
33 if url and protocol is None:
34 protocol = self._get_protocol_from_url(url)
35 if protocol and protocol in settings.HTTP_PROXIES:
36 return {
37 protocol: settings.HTTP_PROXIES[protocol]
38 }
39 return settings.HTTP_PROXIES
42def resolve_proxies(url=None, protocol=None, context=None):
43 """
44 Return a dictionary of candidate proxies (compatible with the requests module), or None.
46 Args:
47 url: The specific request URL for which the proxy will be used (optional)
48 protocol: The protocol in use (e.g. http or https) (optional)
49 context: Arbitrary additional context to aid in proxy selection (optional)
50 """
51 context = context or {}
53 for item in settings.PROXY_ROUTERS:
54 router = import_string(item) if type(item) is str else item
55 if proxies := router().route(url=url, protocol=protocol, context=context):
56 return proxies
57 return None