Reputation: 207
I am creating a Flask app, and I have a page with a form to register new users. But when I type some data, I get the error sqlalchemy.exc.OperationalError: (OperationalError) no such table: user
. In the file config.py I have this line
SQLALCHEMY_DATABASE_URI = "sqlite:///example.sqlite"
and this is the rest of my code:
flask_start.py
import os
from flask import Flask
from config import Config
from flask_utils import page_bp
from db_creation import db
def create_app():
appname = "IOT - PROJECT NASTIS"
app = Flask(appname)
myconfig = Config
app.config.from_object(myconfig)
app.register_blueprint(page_bp, url_prefix='')
db.init_app(app)
return app
def setup_database(app):
with app.app_context():
db.create_all()
if __name__ == "__main__":
app = create_app()
if not os.path.isfile('/tmp/test.sqlite'):
setup_database(app)
port = 8000
interface = '0.0.0.0'
app.run(host=interface, port=port, debug=True)
db_creation.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
flask_utils.py
db_creation import db
from User import User
page_bp = Blueprint("page_bp", __name__)
@page_bp.route('/mainPage/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm(request.form)
if request.method == 'POST' and form.validate():
user = User(form.username.data, form.email.data,
sha256_crypt.encrypt(str(form.password.data)))
db.session.add(user)
db.session.commit()
flash('Thanks for registering, you can now log in!!', 'success')
return redirect(url_for('page_bp.register'))
return render_template('register.html', form=form)
User.py
from db_creation import db
class User(db.Model):
username = db.Column(db.String(100), primary_key=True)
email = db.Column(db.String(100))
password = db.Column(db.String(100))
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = password
What am I doing wrong? I can't figure out what is the mistake
Upvotes: 0
Views: 1077
Reputation: 9450
When you run db.create_all()
it needs to know which tables to create-- it can tell that by which models it currently can see.
User
isn't imported in your start_flask.py
file-- so when db.create_all()
is run it pretty much goes 'huh, I'm not aware of any models, I guess I'll just create an empty database with no tables' it doesn't know to go and look in other files, so you just need to introduce them :)
Adding from User import User
to the imports in the start_flask.py
file should solve that.
Also-- you're checking for a file in /tmp/...
to trigger your 'no database file yet' check, but your SQLALCHEMY_DATABASE_URI
isn't matching that.
Upvotes: 2