0

I created a flask app with virtualenv and it has the structure shown below. I'm trying to import an object from PackageDirectory/fileA.py into FlaskDirectory/app/models.py.

The errors:

In models.py I use the following statement: from ...PackageDirectory.fileA import MyObject, but it gives the error:ValueError: attempted relative import beyond top-level package. So then I declared PackageDirectory as a sources root, and used from PackageDirectory.fileA import MyObject, for which it gave the error: ImportError: No module named 'PackageDirectory'

The directory structure

           ├── FlaskDirectory
           │    ├── app
           │    │   ├── __init__.py
           │    │   ├── models.py
           │    │   └── views.py
           │    ├── flask
           │    │   ├── Include
           │    │   ├── Lib
           │    │   ├── Scripts
           │    │   ├── tcl
           │    │   └── pip-selfcheck.json
           │    ├── config.py
           │    ├── run.py
           │    └── app.py
           │
           ├── PackageDirectory (a python package)
           │    ├── ipynb (also a package)
           │    ├── utils (also a package)
           │    ├── __init__.py
           │    ├── fileA.py  

FlaskDirectory/run.py:

from app import app

if __name__ == '__main__':
    app.run()

FlaskDirectory/app/__init__.py:

from flask import Flask
app = Flask(__name__, instance_relative_config=True)
from . import views
app.config.from_object('config')

FlaskDirectory/config.py:

DEBUG=True

The FlaskDirectory/app.py file you see there is empty, but I'm unsure if I could delete that or if flask uses it in the background

omrakhur
  • 1,362
  • 2
  • 24
  • 48
  • I hope below link will help you to solve your problem. https://stackoverflow.com/questions/20075884/python-import-module-from-another-directory-at-the-same-level-in-project-hierar – Kantharaju Aug 11 '17 at 10:52
  • I already read that, not helpful in my case – omrakhur Aug 11 '17 at 10:52

2 Answers2

0

After adding PackageDirectory to PYTHONPATH change import to

from fileA import MyObject
phd
  • 82,685
  • 13
  • 120
  • 165
0

Concretely, you can do what @phd says as follows.

import sys,os

path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'PackageDirectory')
sys.path.append(path)

from fileA import obj
Yujiro
  • 351
  • 1
  • 6