What's the correct way to detect whether SOCKS proxies are supported with Python requests?

1.2k Views Asked by At

Modern versions of requests support HTTP(S) proxies out-of-the-box, and also SOCKS proxies. However the latter are “an optional feature that requires that additional third-party libraries be installed before use.” PySocks is the appropriate third-party library on all POSIX-like platforms that I am familiar with.

I'm building an application that uses requests with a user-configurable proxy, and trying to figure out how to test for whether SOCKS proxies will be supported by the local installation of requests.

As far as I can tell, the requests API does not contain a built-in function to check for this support, but when the library attempts to actually use a SOCKS5 proxy, it will raise the exception InvalidSchema("Missing dependencies for SOCKS support.").

I've come up with the following incantation to try to test for whether requests supports SOCKS proxies ahead of using them…

try:
    requests.adapters.SOCKSProxyManager('socks5://')
    have_socks = True
except requests.exceptions.InvalidSchema:
    have_socks = False

This appears to work correctly (tested with requests 2.22.0) but doesn't seem particularly future-proof.

Is there a better (simpler, safer, more future-proof) way to test for SOCKS support in requests, before using it?

0

There are 0 best solutions below