Import mysql python function to a different directory (ModuleNotFoundError)

Question:

SOS. I’m in the process of migrating my SQLite database to MySQL and I’d like to share my MySQL connection using a function in /db/connect.py with my app at /app/app.py. I’m using a temp file to test the connection at /app/test.py which contains the function import. The connection from /db/connect.py runs successfully by itself. However, even after following other guides to the letter, my function in /db/connect.py isn’t importing correctly. Even after adding an empty __init__.py file in the /db/ directory.

What I’ve tried

Here’s a small sampling of what I’ve tried here, here, here, and here (as well as all other questions in stack overflow on the topic, e.g., here, here, here, here, etc).

/db/test.py (temp file with function import)

Imports /db/connect.py > sql_db_connection().

from db.connect import sql_db_connection
import db

def get_all():
    conn = sql_db_connection()
    cursor = conn.cursor()
    cursor.execute("select * from posts")
    result = cursor.fetchall()
    for x in result:
        print(x)
Error (error from running test.py)
Traceback (most recent call last):
  File "/Users/<uname>/<my-long-app-name>/app/test.py", line 1, in <module>
    from db.connect import sql_db_connection
ModuleNotFoundError: No module named 'db'
/db/connect.py (function for mysql connection)
import sshtunnel
import MySQLdb
import os
from dotenv import load_dotenv

# Load all env vars
load_dotenv()

def sql_db_connection():
    sshtunnel.SSH_TIMEOUT = 5.0
    sshtunnel.TUNNEL_TIMEOUT = 5.0

    with sshtunnel.SSHTunnelForwarder(
        ('ssh.pythonanywhere.com'),
        ssh_username=os.getenv("REMOTE_DB_SSH_USERNAME"), ssh_password=os.getenv("REMOTE_SSH_PASSWORD"),
        remote_bind_address=(
            os.getenv("REMOTE_BIND_ADDRESS"), 3306)
    ) as tunnel:
        conn = MySQLdb.connect(
            user=os.getenv("REMOTE_DB_SSH_USERNAME"),
            passwd=os.getenv("REMOTE_DB_PASSWORD"),
            host='0.0.0.0', port=tunnel.local_bind_port,
            db=os.getenv("REMOTE_DB_NAME"),
        )
        print('Connected!')
        
        return conn

sql_db_connection()
Tree
.
├── Dockerfile
├── README.md
├── __pycache__
│   ├── app.cpython-310.pyc
│   ├── app.cpython-39.pyc
│   ├── config.cpython-39.pyc
│   ├── wsgi.cpython-38.pyc
│   └── wsgi.cpython-39.pyc
├── app
│   ├── Dockerfile
│   ├── __init__.py
│   ├── __pycache__
│   ├── app.py
│   ├── config.py
│   ├── public
│   ├── requirements.txt
│   ├── templates
│   ├── test.py
│   └── wsgi.py
├── db
│   ├── Dockerfile
│   ├── README.md
│   ├── __init__.py
│   ├── __pycache__
│   ├── connect.py
│   ├── database.db
│   ├── dump.sql
│   ├── init_db.py
│   ├── mysql_dump.sql
│   ├── schema.sql
│   └── schema_mysql.sql
├── docker-compose.yml
├── features.md
├── images
├── requirements.txt
├── setup.py
├── venv
│   ├── bin
│   ├── include
│   ├── lib
│   ├── man
│   └── pyvenv.cfg
└── wsgi.py
Asked By: Tucker

||

Answers:

add these two lines as the first two lines in test.py

import sys
sys.path.append('/Users/<uname>/<my-long-app-name>')
Answered By: Ahmed AEK
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.