8000 Add bind_address option (#529) · uwydoc/PyMySQL@755dfdc · GitHub
[go: up one dir, main page]

Skip to content

Commit 755dfdc

Browse files
dciabrinmethane
authored andcommitted
Add bind_address option (PyMySQL#529)
Allow connecting to the DB from a specific network interface
1 parent 6c9d31a commit 755dfdc

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

pymysql/connections.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -534,7 +534,8 @@ def __init__(self, host=None, user=None, password="",
534534
compress=None, named_pipe=None, no_delay=None,
535535
autocommit=False, db=None, passwd=None, local_infile=False,
536536
max_allowed_packet=16*1024*1024, defer_connect=False,
537-
auth_plugin_map={}, read_timeout=None, write_timeout=None):
537+
auth_plugin_map={}, read_timeout=None, write_timeout=None,
538+
bind_address=None):
538539
"""
539540
Establish a connection to the MySQL database. Accepts several
540541
arguments:
@@ -544,6 +545,9 @@ def __init__(self, host=None, user=None, password="",
544545
password: Password to use.
545546
database: Database to use, None to not use a particular one.
546547
port: MySQL port to use, default is usually OK. (default: 3306)
548+
bind_address: When the client has multiple network interfaces, specify
549+
the interface from which to connect to the host. Argument can be
550+
a hostname or an IP address.
547551
unix_socket: Optionally, you can use a unix socket rather than TCP/IP.
548552
charset: Charset you want to use.
549553
sql_mode: Default SQL_MODE to use.
@@ -632,6 +636,7 @@ def _config(key, arg):
632636
database = _config("database", database)
633637
unix_socket = _config("socket", unix_socket)
634638
port = int(_config("port", port))
639+
bind_address = _config("bind-address", bind_address)
635640
charset = _config("default-character-set", charset)
636641

637642
self.host = host or "localhost"
@@ -640,6 +645,7 @@ def _config(key, arg):
640645
self.password = password or ""
641646
self.db = database
642647
self.unix_socket = unix_socket
648+
self.bind_address = bind_address
643649
if read_timeout is not None and read_timeout <= 0:
644650
raise ValueError("read_timeout should be >= 0")
645651
self._read_timeout = read_timeout
@@ -884,10 +890,14 @@ def connect(self, sock=None):
884890
self.host_info = "Localhost via UNIX socket"
885891
if DEBUG: print('connected using unix_socket')
886892
else:
893+
kwargs = {}
894+
if self.bind_address is not None:
895+
kwargs['source_address'] = (self.bind_address, 0)
887896
while True:
888897
try:
889898
sock = socket.create_connection(
890-
(self.host, self.port), self.connect_timeout)
899+
(self.host, self.port), self.connect_timeout,
900+
**kwargs)
891901
break
892902
except (OSError, IOError) as e:
893903
if e.errno == errno.EINTR:

0 commit comments

Comments
 (0)
0