0

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
Shinomoto Asakura
  • 1,473
  • 7
  • 25
  • 45

1 Answers1

1

The only problem I can find is that you add an import statement (from models import users) in your last attached part of the code. However, you have not created an __init__.py inside your models folder, to declare it as a module. So, that you can import it later as a module like you have created an __init__.py file in your main directory ("website/"). But how you import the models.py file in your run.py file? In your run.py file you should import the models like from website.models.users import Users.

I have two working projects, where I also use FlaskSQLAlchemy & PostgreSQL, but I have set as the SQLALCHEMY_DATABASE_URI = 'postgres://postgres:[password]@localhost:5432/[database_name]'. It works perfectly fine by putting postgres instead of postgresql for the engine configuration.

Reference: Flask-SQLAlchemy import/context issue


UPDATE

Well, you have put your business login (routes, ...) in the init.py file. If you want it to run, I think you should probably put it in the run.py file. Leave the __init__.py files empty.

Furthermore, in your app.py file import your models like this: from .website.models import Users. This requires that you have three __init__.py files. One in your main directory where app.py is located, one in the website folder, and one in the models folder.

*I hope that helps. Please let me know if this works, and if there is anything else I can help you with.

georgekrax
  • 1,065
  • 1
  • 11
  • 22
  • Thank you for answering @georgekrax. I have just created a `__init__.py` inside `Models` folder, even so, `ModuleNotFoundError: No module named 'models'`. About DATBASE_URI, I changed as you suggested – Shinomoto Asakura Apr 23 '20 at 01:53
  • Let me see if I got it! I'm importing `models` in my `run.py` as `website.models.users import Users`, or inside `__init__`, I Got a message `ModuleNotFoundError: No module named 'app'` about `from app import db`, inside models users – Shinomoto Asakura Apr 23 '20 at 11:07
  • You import it in `run.py`, YES. I edited again, go check it out! – georgekrax Apr 23 '20 at 11:18
  • What do you think? Did it, I receive the `ModuleNotFoundError: No module named 'app'` from users models. – Shinomoto Asakura Apr 23 '20 at 11:26
  • Yes, but I noticed also that you have your code (routes) in the `init.py` file. In the `__init__.py` file we put extra information and declare modules, and not our code's logic (views). – georgekrax Apr 23 '20 at 12:29
  • I have habit to write just index page route in __init__ rather than create a view only for this. For example, anothers logics, like users I'd have a views/user and templates/users (index, add, view ,..,etc). – Shinomoto Asakura Apr 23 '20 at 13:19
  • Ok, but do not put the code in the `__init__.py` file. It is different if it is named only `init.py` though, without the underscores. It is not the place for this part of your code. Hope that helps – georgekrax Apr 23 '20 at 19:00
  • Should I change `__init__.py` to `app.py`, all I did, didn't work – Shinomoto Asakura Apr 23 '20 at 22:54
  • No just add your code (routes) from the `__init__.py` file to a newly created file. You can name the new file `app.py`. – georgekrax Apr 24 '20 at 06:42
  • Thanks @georgekrax, with your advices I got it to make this work! – Shinomoto Asakura Apr 28 '20 at 15:08
  • 1
    @TMoraes, I am so pleased and happy to hear that you got this to work! Thank you so much, and I appreciate your help, by giving me the corresponding reputation. Please contact me if you want help with anything else in the future. – georgekrax Apr 28 '20 at 17:59