Flask & SQL Alchemy does not work ((OperationalError) no such table :)

I am trying to tune an SQL database using Flask using SQLAlchemy. I am modeling my code after the examples on this github page , but I cannot get it to work.

I keep getting the following error:

sqlalchemy.exc.OperationalError: (OperationalError) no such table: user u'INSERT INTO user (username, email) VALUES (?, ?)' ('test', ' test@gmail.com ') 

Here is my code:

 from flask import Flask, render_template, request, url_for, request, redirect from flask.ext.sqlalchemy import SQLAlchemy import sqlite3 import os app = Flask(__name__) sqlite3.connect(os.path.abspath("test.db")) 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 x = User("test", " test@gmail.com ") db.session.add(x) db.session.commit() @app.route("/") def index(): return User.query.all() if __name__ == "__main__": init.db() app.run(debug=True) 

I know that the error is related to something that is associated with each session, but I'm a bit confused, as the above example never initializes the session explicitly.

+4
source share
1 answer

Python parses your file and executes each line (this is harder, I think, but whatever). So it goes to the next line (which runs until if __name__ == "__main__": ... :

 db.session.commit() 

He is trying 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, by the way, is incorrect. What is init ? This is not defined anywhere in your code.

Read this carefully again.

Here is what your code looks like:

 from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = 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 work if __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 crash and crash if the database already exists. Take a look at Flask-Script . This can help you create a customization script for your application.

+4
source

Source: https://habr.com/ru/post/1491303/


All Articles