2

I have the following folder structure:

.
├── GET
├── Pipfile
├── Pipfile.lock
├── database.py
├── main.py
├── models
│   ├── BaseModel.py
│   ├── __init__.py
│   └── contact.py
└── routers
    ├── __init__.py
    └── contact.py

database.py looks like below:

from peewee import *

user = 'root'
password = 'root'
db_name = 'fastapi_contact'

conn = MySQLDatabase(
    db_name, user=user,
    password=password,
    host='localhost'
)

def get_connection():
    return conn

In the file BaseModel.py I am doing this:

from peewee import *
import os, sys
print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import database

connection = get_connection()
class BaseModel(Model):
    class Meta:
        database = connection

But I am getting the error:

  File "./main.py", line 9, in <module>
    from routers import contact
  File "./routers/contact.py", line 2, in <module>
    from models.contact import Contact
  File "./models/contact.py", line 2, in <module>
    from . import BaseModel
  File "./models/BaseModel.py", line 7, in <module>
    connection = get_connection()
NameError: name 'get_connection' is not defined

how do I get the get_connection in BaseModel.py file?

Thanks

Volatil3
  • 14,253
  • 38
  • 134
  • 263

2 Answers2

3

Either use

database.get_connection

or

from database import get_connection

Assuming that you have added the Root dir to the PYTHONPATH

lllrnr101
  • 2,288
  • 2
  • 4
  • 15
0

The answer from here might help. The follow might also do the trick:

from ... import database
thehand0
  • 1,123
  • 4
  • 14