Skip to content

Commit ae2e1bd

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 ae2e1bd

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

redis/asyncio/connection.py

Lines changed: 17 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,16 @@
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+
from ssl import SSLContext
32+
33+
else:
34+
ssl = None
35+
SSLContext = None
36+
2837
# the functionality is available in 3.11.x but has a major issue before
2938
# 3.11.3. See https://github.com/redis/redis-py/issues/2633
3039
if sys.version_info >= (3, 11, 3):
@@ -740,6 +749,9 @@ def __init__(
740749
ssl_check_hostname: bool = False,
741750
**kwargs,
742751
):
752+
if not SSL_AVAILABLE:
753+
raise RedisError("Python wasn't built with SSL support")
754+
743755
self.ssl_context: RedisSSLContext = RedisSSLContext(
744756
keyfile=ssl_keyfile,
745757
certfile=ssl_certfile,
@@ -800,6 +812,9 @@ def __init__(
800812
ca_data: Optional[str] = None,
801813
check_hostname: bool = False,
802814
):
815+
if not SSL_AVAILABLE:
816+
raise RedisError("Python wasn't built with SSL support")
817+
803818
self.keyfile = keyfile
804819
self.certfile = certfile
805820
if cert_reqs is None:
@@ -820,7 +835,7 @@ def __init__(
820835
self.check_hostname = check_hostname
821836
self.context: Optional[ssl.SSLContext] = None
822837

823-
def get(self) -> ssl.SSLContext:
838+
def get(self) -> SSLContext:
824839
if not self.context:
825840
context = ssl.create_default_context()
826841
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)