@@ -534,7 +534,8 @@ def __init__(self, host=None, user=None, password="",
534
534
compress = None , named_pipe = None , no_delay = None ,
535
535
autocommit = False , db = None , passwd = None , local_infile = False ,
536
536
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 ):
538
539
"""
539
540
Establish a connection to the MySQL database. Accepts several
540
541
arguments:
@@ -544,6 +545,9 @@ def __init__(self, host=None, user=None, password="",
544
545
password: Password to use.
545
546
database: Database to use, None to not use a particular one.
546
547
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.
547
551
unix_socket: Optionally, you can use a unix socket rather than TCP/IP.
548
552
charset: Charset you want to use.
549
553
sql_mode: Default SQL_MODE to use.
@@ -632,6 +636,7 @@ def _config(key, arg):
632
636
database = _config ("database" , database )
633
637
unix_socket = _config ("socket" , unix_socket )
634
638
port = int (_config ("port" , port ))
639
+ bind_address = _config ("bind-address" , bind_address )
635
640
charset = _config ("default-character-set" , charset )
636
641
637
642
self .host = host or "localhost"
@@ -640,6 +645,7 @@ def _config(key, arg):
640
645
self .password = password or ""
641
646
self .db = database
642
647
self .unix_socket = unix_socket
648
+ self .bind_address = bind_address
643
649
if read_timeout is not None and read_timeout <= 0 :
644
650
raise ValueError ("read_timeout should be >= 0" )
645
651
self ._read_timeout = read_timeout
@@ -884,10 +890,14 @@ def connect(self, sock=None):
884
890
self .host_info = "Localhost via UNIX socket"
885
891
if DEBUG : print ('connected using unix_socket' )
886
892
else :
893
+ kwargs = {}
894
+ if self .bind_address is not None :
895
+ kwargs ['source_address' ] = (self .bind_address , 0 )
887
896
while True :
888
897
try :
889
898
sock = socket .create_connection (
890
- (self .host , self .port ), self .connect_timeout )
899
+ (self .host , self .port ), self .connect_timeout ,
900
+ ** kwargs )
891
901
break
892
902
except (OSError , IOError ) as e :
893
903
if e .errno == errno .EINTR :
0 commit comments