Following this tutorial of using SQLAlchemy and Postgresql, I based myself for creating a file structure of models, views, templates etc..
requirements.txt
run.py
website/
__init__.py
views/
models/
users.py
static/
templates/
As you can see, inside models I have users.py
from app import db
class Users(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
user = db.Column(db.String(), index=True, unique=True)
password = db.Column(db.String(128))
def __init__(self, user, password):
self.user = user
self.password= password
def __repr__(self):
return f"<User {self.user}>"
My init.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://postgres:postgres@localhost:5432/project"
db = SQLAlchemy(app)
migrate = Migrate(app, db)
#Routes
@app.route("/")
def index():
return render_template('index.html')
Now, I used these commands to create user table flask db init
, flask db migrate
, flask db upgrade
. OK, after this, was created a table named public.alembic_version
, but as you see, Users didnt.
My last tried, was insert this import from models import users
between:
migrate = Migrate(app, db)
from models import users
@app.route("/")
def index():
return render_template('index.html')
But the message is ModuleNotFoundError: No module named 'models'
I thought that I'm using a reserved word, even changing folder, page name, the error keeps, just change module name.
Update:
Final result, this example work to me
run.py
from website import app
from website.models.users import User
app.run(host="0.0.0.0",debug=True,port=5000)
Update
requirements.txt
run.py
website/
__init__.py
views/
models.py
static/
templates/
What I changed is remove Models Folder e create a file models.py and adding the class Users, Purchase, anything that I want...
I took these imports and include in top of my models.py
...
from website import app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import psycopg2
app.config['SQLALCHEMY_DATABASE_URI'] = "postgres://postgres:password@ipaddress:5432/databasename"
db = SQLAlchemy(app)
migrate = Migrate(app, db)
In __init__.py
added in end of line, after blueprints imports, if I wanted do it, from website.models import Users
from flask import Flask, render_template
app = Flask(__name__)
from website.models import Usuario