0

I'm working on a small flask app and I keep getting an error that says the 'users' table I have created does not exist.

I am using heroku postgres URI for the database and a .env file to load the server environment variables.

I'm using kubuntu 18.04. the modules I'm using are all installed properly. I don;t understand what the issue is at all.

Could someone please help me fast.

application.py

import os

from flask import Flask, session, render_template, request
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# Check for environment variable
if not os.getenv("DATABASE_URL"):
    raise RuntimeError("DATABASE_URL is not set")
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)

"""
    The SQL table for the users registered in the application.
"""
class User(db.Model):
    __tablename__ = "users"
    username = db.Column(db.String, primary_key = True)
    password = db.Column(db.String, nullable = False)
    user_created_on = db.Column(db.DateTime, nullable = False)

    def __init__(self, username, password, user_created_on = None):
        self.username = username
        self.password = password
        self.user_created_on = datetime.now()

"""
    The SQL table for the books.
"""
class Books(db.Model):
    __tablename__ = "books"
    isbn = db.Column(db.String, primary_key = True)
    title = db.Column(db.String, nullable = False)
    author = db.Column(db.String, nullable = False)
    year = db.Column(db.Integer, nullable = False)

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Set up database
# engine = create_engine(os.getenv("DATABASE_URL"))
# db = scoped_session(sessionmaker(bind=engine))

"""
    The home page for the application.
"""
@app.route("/")
@app.route("/home")
@app.route("/index")
def index():
    return render_template("index.html")

"""
    The registration page for the application.
"""
@app.route("/registration")
def registration():
    return render_template("registration.html")

"""
    To check the registration eligibility and status
"""
@app.route("/registration_process", methods = ["POST", "GET"])
def registering():
    if request.method == "GET":
        return render_template("index.html")
    username = request.form["username"]
    password = request.form.get("password")
    if (User.query.get(username) == None):
        user = User(username, password)
        db.session.add(user)
        db.session.commit()
        return render_template("success.html", message = "Registered Successfully")
    else:
        return render_template("login.html", message = "You have already registered, please login")

@app.route("/tologin")
def tologin():
    return render_template("login.html")

@app.route("/login", methods = ["POST", "GET"])
def login():
    if request.method == "GET":
        return render_template("index.html")
    username = request.form.get("username")
    password = request.form.get("password")
    if (User.query.get(username) != None):
        user = User.query.get(username)
        if (user.password != password):
            return render_template("login.html", mesage = "Incorrect Password!")
        else:
            return render_template("success.html", message = "Loged in successfully", user = username)
    else:
        return render_template("registration.html", message = "You have not yet registered")

@app.route("/admin")
def admin():
    all_users = User.query.all()
    return render_template("adminpage.html", users = all_users)

def main():
    db.create_all()
    print("Database tables created")

if __name__ == "__main__":
    with app.app_context():
        main()

And this is the error I keep getting

sqlalchemy.exc.ProgrammingError

ProgrammingError: (psycopg2.errors.UndefinedTable) relation "users" does not exist
LINE 2: FROM users 
             ^

[SQL: SELECT users.username AS users_username, users.password AS users_password, users.user_created_on AS users_user_created_on 
FROM users 
WHERE users.username = %(param_1)s]
[parameters: {'param_1': u'piyush'}]
(Background on this error at: http://sqlalche.me/e/f405)

registration.html

{% extends "layout.html" %}
{% block content %}
<h1>Hello There!</h1>
<form action="/registration_process" method="post">
  <p>Username</p><input type="text" name="username">
  <p>Password</p><input type="password" name="password"><br><br>
  <input type="submit" name="submit" value="Submit">
</form>
{% endblock %}
  • Are you launching the app with `flask run ` at the command line? – SuperShoot Apr 26 '20 at 13:15
  • @SuperShoot yes – Piyush Jain Apr 26 '20 at 15:50
  • I think that means that the code in your `if __name__ == “__main__”:` guard isn’t executing. – SuperShoot Apr 26 '20 at 19:47
  • @SuperShoot then should I run the code with python compiler before flask run ? – Piyush Jain Apr 27 '20 at 01:37
  • If you don't execute a module directly, its name isn't `"__main__"` and so the code within that guard won't execute. Just put the call to `db.create_all()` at the module scope. – SuperShoot Apr 29 '20 at 00:21
  • @SuperShoot I moved the db.create_all() to module scope and it works now! Why do you think the main() is not executing? – Piyush Jain Apr 29 '20 at 05:03
  • @SuperShoot I changed the "__main__" to "application" and it was working then. What do you think might be the reason. – Piyush Jain Apr 29 '20 at 20:28
  • When you run a module directly it is called "__main__" within the interpreter. When a module is imported and executed by another module it is named per its filename within the interpreter, in your case : "application". See this: https://stackoverflow.com/questions/419163/what-does-if-name-main-do – SuperShoot Apr 30 '20 at 00:35
  • @SuperShoot Thank you for your help – Piyush Jain May 03 '20 at 17:04

0 Answers0