Flask & SQL Alchemy Not Working ((OperationalError) no such table:)
Python parses your file and executes every line (it's more complex I guess but whatever). So it gets to the following line (which is executed before if __name__ == "__main__": ...
:
db.session.commit()
It tries to add User x
to the database. But the database/table does not exist yet because you try to create it a couple of lines later by calling init.db()
, which is wrong by the way. What is init
? It's nowhere defined in your code.
Please read this carefully again
Here is what your code should look like:
from flask import Flaskfrom flask.ext.sqlalchemy import SQLAlchemyapp = Flask(__name__)app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"db = SQLAlchemy(app)class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return "<User %r>" % self.username@app.route("/")def index(): return User.query.all() # I don't think this will workif __name__ == "__main__": db.create_all() x = User("test", "test@gmail.com") db.session.add(x) db.session.commit() app.run(debug=True)
Note that db.create_all()
will fail and crash if the database already exists. Have a look at Flask-Script. It can help you building a setup script for your app.