0

I have read every tutorial I can find on importing files in Python, and even after following them, my imports don't work. I am getting the error ModuleNotFoundError: No module named 'app.' I have read about absolute imports vs. relative imports, but I can't get either to work. I have attached my Python project structure and the code I'm using to import from the services/user.py file. Can someone let me know what I'm doing wrong? I'm still learning Python and am trying to create a back-end that uses Python, alembic, and sqlalchemy. Now that I'm more familiar with how to code in Python and how to use alembic and sqlalchemy to interact with a database, I want to set a complete project up so I can call it form a front-end. I'm struggling with setting up the project and being able to import files.

Something to note is that if I'm in a file in the database/versions folder, from api.setup import * works.

enter image description here

# services/user.py file
from app.setup import *
from app.models.user import User


def get_user(user_id):
    user = session.scalars(select(User).where(User.id == user_id))
    # textSql = text('SELECT * FROM users WHERE first_name = :name')
    # sql = select(User).from_statement(textSql)
    # users = session.execute(sql, {'name': firstName}).scalars()
    print('First Name: ' + user.first_name + '; Last Name: ' + user.last_name + '; Email: ' + user.email +
          '; User Id: ' + user.user_id)
    for account in user.accounts:
        print('Name: ' + account.name + '; Account Number: ' + account.account_number)


def get_users():
    users = session.scalars(select(User))
    for user in users:
        print('First Name: ' + user.first_name + '; Last Name: ' + user.last_name + '; Email: ' + user.email +
              '; User Id: ' + user.user_id)
        for account in user.accounts:
            print('Name: ' + account.name + '; Account Number: ' + account.account_number)
Just Me
  • 91
  • 4
  • 12
  • You are already in the directory "app".```from setup import * ``` ```from models.user import User``` – thamuppet Jun 06 '22 at 19:43
  • @thamuppet I'm in a directory inside the directory 'app;' I'm not immediately under the 'app' directory. – Just Me Jun 06 '22 at 19:45

1 Answers1

0

It's possible that your environment variable PYTHONPATH is not set appropriately something like: PYTHONPATH="/.../app"

Don't know which system you are on, but if your are on Linux you can check env variables by typing in terminal:

env

or if there is PYTHONPATH variable it will show up when you type:

env | grep PYTHONPATH

output should be something like:

PYTHONPATH="/...<pwd_to_you_app_folder>.../app"

if not you could set it by typing:

export PYTHONPATH="/...<pwd_to_you_app_folder>.../app"

mmway
  • 93
  • 1
  • 10