0
votes

I am learning how to use SQLalchemy and databases in general with flask. I am following a tutorial and it uses the below classes and files.

https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database

To show an inserted row in the database, the tutorial uses the following:

from app.models import User
>>> u = User(username='susan', email='[email protected]')
>>> u
<User susan>

My problem is that I can not display the same output. I mean when I code the the statement, I get an error

from app.models import User
ImportError: No module named app.models

Please let me know how to adapt the posted code so I can retrieve data from database

Folder Structure:

d:\xxx\xxx\db1\app\models
d:\xxx\xxx\db1\__init__
d:\xxx\xxx\db1\config

** init **:

from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)

from app import routes, models

config:

import os
basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
# ...
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
    'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False

models:

from app import db
from app.models import User

class User(db.Model):
    id = db.Column(db.Integer, primaty_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))

def __repr__(self):
    return '<User {}>'.format(self.username)    
1
add your folder/files structure to the question.waynetech
@waynetech I have not thought that the folder structure matters..I will do itLetsamrIt
@waynetech i added the folder structureLetsamrIt
move __init__.py in `d:\xxx\xxx\db1\app` folderwaynetech

1 Answers

1
votes

You cannot import User on the same module where models is declared, so I don't think If you need that second line in models.py, Try commenting and see what happens

from app import db
from app.models import User ## I think the problems is 

class User(db.Model):
    id = db.Column(db.Integer, primaty_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))

def __repr__(self):
    return '<User {}>'.format(self.username)