Skip to content

Added documentation for connecting the Flask-app to MySQL on the server from home

Oscar Brink requested to merge 39_mysql_port into Sprint3

This guide will be available in documentation/how-to.md when this merge request is merged into master.

Connecting to MySQL in Flask from Home

Since the MySQL port 3306 is behind the almighty LUDD firewall we will need to forward the connection to MySQL through SSH, we do this by setting up a SSH tunnel.

First install sshtunnel in your virtual environment:

pip install sshtunnel

This is what your config.py file should look like. Edit the variables as necessary (IMPORTANT: note localhost in the first HOST variable):

HOST     = 'localhost'
USER     = 'db_user'
PASSWORD = 'db_pass'
DB       = 'db_name'

import signal
from sshtunnel import SSHTunnelForwarder

server = SSHTunnelForwarder(
    ssh_address_or_host="remote_hostname",      # EDIT
    ssh_username="server_user",                 # EDIT
    ssh_password="server_pass",                 # EDIT
    local_bind_address=("0.0.0.0", 3306),   # Local connections to 3306 are to be forwarded
    remote_bind_address=("localhost", 3306) # Connections are forwarded to here
)

server.start()

# Shutdown hook to turn ssh-tunnel server off
def hook(self, *args):
    print("\nStopping ssh-tunnel server...")
    server.stop()
    print("Done, have a nice day!")
    raise KeyboardInterrupt # This is to allow werkzeug to stop execution naturally.
signal.signal(signal.SIGINT, hook)
Edited by Oscar Brink

Merge request reports