0

My life with python is just started. I am clueless about how to organize folders in python(flask)

My intention is to organize my application in following directory/file structure

srcenter image description here

server.py is the main file

database.py holding DB related sharable resources

customer.py is a simple python class which need DB instance from database.py

from ....shared.database import DB # How to solve this

class Customer():
    def __init__(self):
        self._first_name="John"

but I am getting an error Attempted relative import beyond top-level package

How do I make this works?!.

folder strucure representation

src
  app
    /modules
         /customers
              /models
                 customer.py
    /shared
       /database.py
  /server.py
Binson Eldhose
  • 993
  • 3
  • 14
  • 35
  • There are loads of tutorials online, SO isn’t the best place for this question. Perhaps [start here](https://www.fullstackpython.com/flask.html). Regarding relative imports, have a look [here](https://stackoverflow.com/q/72852/6340496). – S3DEV Aug 05 '20 at 06:03
  • Does this answer your question? [How to do relative imports in Python?](https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python) – S3DEV Aug 05 '20 at 06:06

2 Answers2

1

Your directories need to contain an __init__.py file in order to be recognized as packages and thus work with imports. The file can be empty.

More info on __init__.py here: What is __init__.py for?

jobrachem
  • 105
  • 7
0

To declare your folder as the package you should add blank init.py files in each folder which contains any code that you want to call from other subfolders.

And if you are still not able to do it then, please see this other alternative.

You can try doing this as a quick way to access other source codes from other subfolders within the same module: Add this before doing your import if name == 'main': import os import sys sys.path.append(os.getcwd()) from app.shared.database import DB

RITESH DUBEY
  • 55
  • 1
  • 7