Skip to content
Advertisement

django db with ssh tunnel

Is there a python native way to connect django to a database through an ssh tunnel? I have seen people using ssh port forwarding in the host machine but I would prefer a solution that can be easily containerized.

Advertisement

Answer

It is pretty seamless.

Requirements: The sshtunnel package https://github.com/pahaz/sshtunnel

  1. In the django settings.py create an ssh tunnel before the django DB settings block:
JavaScript
  1. Then add the DB info block in the settings.py. Here I am adding a default local DB and the remote DB that we connect to using the ssh tunnel
JavaScript

That is it. Now one can make migratations to the remote db using commands like $ python manage.py migrate --database=shhtunnel_db or make calls to the db from within the python code using lines like Models.objects.all().using('shhtunnel_db')

Extra: In my case the remote db was created by someone else and I only wanted to read it. In order to avoid writing the models and deactivating the model manager I used the following django command to get the models from the database [src]:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement