Skip to content

Commit 6daa3cd

Browse files
committed
skip ssl import if not available
`utils.py` has support for detecting whether the `ssl` module is available, and we can use this to omit SSL-specific funcionality while still providing other features (e.g. unencrypted connections). Prior to this patch, the `connection.py` modules both triggered an `ImportError` due to unconditional imports of the `ssl` module. Now, we check `utils.SSL_AVAILABLE` prior to attempting the import and only raise an error later if (and only if) the application requests an encrypted connection. This helps support platforms such as `wasm32-wasi` where the `ssl` module is not built by default. Signed-off-by: Joel Dice <[email protected]>
1 parent f6a4b49 commit 6daa3cd

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

redis/asyncio/connection.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import enum
44
import inspect
55
import socket
6-
import ssl
76
import sys
87
import warnings
98
import weakref
@@ -25,6 +24,15 @@
2524
)
2625
from urllib.parse import ParseResult, parse_qs, unquote, urlparse
2726

27+
from ..utils import SSL_AVAILABLE
28+
29+
if SSL_AVAILABLE:
30+
import ssl
31+
32+
else:
33+
ssl = None
34+
SSLContext = None
35+
2836
# the functionality is available in 3.11.x but has a major issue before
2937
# 3.11.3. See https://github.com/redis/redis-py/issues/2633
3038
if sys.version_info >= (3, 11, 3):
@@ -740,6 +748,9 @@ def __init__(
740748
ssl_check_hostname: bool = False,
741749
**kwargs,
742750
):
751+
if not SSL_AVAILABLE:
752+
raise RedisError("Python wasn't built with SSL support")
753+
743754
self.ssl_context: RedisSSLContext = RedisSSLContext(
744755
keyfile=ssl_keyfile,
745756
certfile=ssl_certfile,
@@ -800,6 +811,9 @@ def __init__(
800811
ca_data: Optional[str] = None,
801812
check_hostname: bool = False,
802813
):
814+
if not SSL_AVAILABLE:
815+
raise RedisError("Python wasn't built with SSL support")
816+
803817
self.keyfile = keyfile
804818
self.certfile = certfile
805819
if cert_reqs is None:
@@ -820,7 +834,7 @@ def __init__(
820834
self.check_hostname = check_hostname
821835
self.context: Optional[ssl.SSLContext] = None
822836

823-
def get(self) -> ssl.SSLContext:
837+
def get(self) -> SSLContext:
824838
if not self.context:
825839
context = ssl.create_default_context()
826840
context.check_hostname = self.check_hostname

redis/connection.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import copy
22
import os
33
import socket
4-
import ssl
54
import sys
65
import threading
76
import weakref
@@ -35,6 +34,12 @@
3534
str_if_bytes,
3635
)
3736

37+
if SSL_AVAILABLE:
38+
import ssl
39+
40+
else:
41+
ssl = None
42+
3843
if HIREDIS_AVAILABLE:
3944
import hiredis
4045

0 commit comments

Comments
 (0)