简体   繁体   中英

Python Module not found, relative folder. Can't figure it out

There are a million answers for this on Google but I can't seem to apply any of the fixes and get the expected result! Hopefully someone can help me here?

I have used Python in the past but it's been a while, I am re-writing an old project from last year using SQLAlchemy and SQLite3.

Problem is, I can't seem to get my tests to play nice. I am trying to separate my test database from production database, so I have the following file structure:

    .
├── fleet_manager
│   ├── controller
│   │   └── customer_controller.py
│   ├── database.db
│   ├── fleet_manager.py
│   ├── model
│   │   ├── __init__.py
│   │   ├── models.py
│   └── view
├── Pipfile
├── Pipfile.lock
└── tests
    ├── context.py
    ├── __init__.py
    ├── test_customer_controller.py
    ├── test.db
    └── test_models.py

So I have created a context.py file and in here I have my SQLAlchemy engine/session factory. It is this file that my test files can't find.

# test_models.py

from mamba import description, context, it, before
from expects import expect, equal, be_a, be_none
from sqlalchemy import create_engine, Table
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker


from context import Session # < this mofo here
from fleet_manager.model.models import (
    Equipment,
    EquipmentType,
    Discipline,
    Size,
    Make,
    Model,
    Customer,
    Base)

So basically the above file is not finding context at all

# context.py

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

engine = create_engine('sqlite:///tests/test.db', echo=True)
Session = sessionmaker(bind=engine)

This is the error I get (omitted the excess trace):

ModuleNotFoundError: No module named 'tests/test_models'

I have tried a bunch of stuff so far. I have tried modifying the path using os.path, as well as using .context as opposed to context but still nothing. Originally I had this problem when trying to access my models.py but that's because I forgot to put init .py in the folder!

Can anyone help me here? Ripping my hair out.

one quick way tosave you from ripping hair out

import sys
sys.path.append("/path/to/your/package_or_module")

The problem is that your tests directory is not in your python path. And it wont be by default. You are trying to import from that directory using

from context import Session

and it fails. As you would be executing from your base directory, you can do absolute import from that directory using

from tests.context import Session

Or use relative imports like this.

from .context import Session

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM