0

This is how my folder and files looks like:

/app
    __init__.py
    /admin
        __init__.py
        models.py

and app/__init__.py file:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from app.admin.models import *


app = Flask('app')  

@app.route('/users', methods=['GET'])
def show_users():
    return "list of all Users:\n" + User.query.limit(5).all()

and app/admin/models.py :

from datetime import datetime
from sqlalchemy.orm import relationship
from flask_sqlalchemy import SQLAlchemy
from app import app


db = SQLAlchemy(app)

class User(db.Model):
    pass

I want have access to my User model in init file,from Import from parent directory and import script from a parenet directory I have tried from app import * or from .. import app or also put db = SQLAlchemy(app) in __init__ file and import it in models.py with from app import db or from .. import db but I'm keep getting app and db are not defined and also I think it's weird that I should import both file in each other.

Community
  • 1
  • 1
ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57

1 Answers1

1

The error is about Flask extensions, while your app created sqlalchemy extension didn't initialize, therefore it cause error. The best practice is to keep extensions initializes in same place:

#app/__init__.py
...
db = SQLAlchemy(app)
from app.admin.models import *

#app/admin/models.py
...
from app import db

If you do this changes, it will work.

metmirr
  • 4,234
  • 2
  • 21
  • 34