Connecting Django to the database behind the proxy server

I would like to associate Django with my MySQL (read-only) production base so that I can use it to test an analytics application using real data.

Is there a way to indicate that django should connect to db through an ssh proxy in the same way that, say, Sequel Pro allows you to specify a connection through a specific SSH proxy with a username and password?

If so, what would a DATABASES record look like?

+4
source share
2 answers

Just use SSH tunneling. To make your work easier, you can install autossh , which automatically checks if the ssh connection is alive and restores it if it drops.

Then you can open the tunnel using the following command:

 autossh -f -N -L LocalPort:MySQLAddress:MySQLPort your_login@your _server 

Where:

  • your_server - the server you are connecting to through ssh
  • your_login - your username in your_server
  • LocalPort - any unused port on the computer running Django. This port will be used for the tunnel.
  • MySQLAddress is the address of your MySQL server, since it is accessible from your_server (that is, if MySQL is running on your_server , it will be 127.0.0.1 )
  • MySQLPort - MySQL port is listening

Then in Django settings you specify MySQL IP as 127.0.0.1 and port as LocalPort , which you installed above.

Example:

 autossh -f -N -L 10000:127.0.0.1:3306 a_user@192.168.1.3 

When you run this command, you will listen for the SSH tunnel on local port 10000. Therefore, if you connect to localhost: 10000, your connection will be tunneled to localhost: 3306 on server 192.168.1.3.

+13
source

You can also use the SSH tunnel directly in Python using sshtunnel and a variant of the following:

 import mysql.connector import sshtunnel sshtunnel.SSH_TIMEOUT = 5.0 sshtunnel.TUNNEL_TIMEOUT = 5.0 with sshtunnel.SSHTunnelForwarder( ('ssh.yourserver.com'), ssh_username='your SSH server username', ssh_password='secret1', remote_bind_address=('your database hostname', 3306) ) as tunnel: connection = mysql.connector.connect( user='your database username', password='secret2', host='127.0.0.1', port=tunnel.local_bind_port, database='your database name, eg yourusername$mydatabase', ) # Do stuff connection.close() 

Source: PythonAnywhere

+1
source

Source: https://habr.com/ru/post/1480960/


All Articles