Flask SQL Alchemy,showing Operational Error on Commit Sessions - python

The Problem is related to Flask SqlAlchemy where i am not abel to commit my Data into DataBase i have tried many ways but getting Same error ,i have uploaded all my files for that
I am making simple model by following tutorial,these are my all files
init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app=Flask(__name__)
app.config['SECRET_KEY']='123456'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////temp/test.db'
db = SQLAlchemy(app)
from BlogSite import routes
routes.py
from flask import render_template,flash,redirect, url_for
from BlogSite import app
from BlogSite.forms import RegistrationForm,SignInForm
login=False
#app.route("/home/",methods=['GET','POST'])
def home():
global login
form=SignInForm()
if form.validate_on_submit():
flash(f'Logged in successfully for ','success')
login=True
return redirect(url_for('home'))
return render_template('home.html',login=login,form=form)
#app.route("/Create_Account/",methods=['GET','POST'])
def Create_Acc():
form=RegistrationForm()
if form.validate_on_submit():
flash(f'Account Created successfully for {form.username.data}','success')
return redirect(url_for('home'))
return render_template('Create_account.html',form=form)
modals.py
from BlogSite import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
Here in repr_ method i also tried the below given code but same error is there
return f"User('{self.username}')"
run.py
from BlogSite import app
if __name__=="__main__":
app.run(debug=True)
My Tree Structure for this is as
Tree view of my File System
list of errors
and also While i was performing This At that instant Database was not Created on calling of db.create all() function and also when i just have simply named it as site.db at first at that instant Database was created but on commit error was same only
Errors i am getting as
>>> from BlogSite import db
C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\flask_sqlalchemy\__init__.py:872: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds
significant overhead and will be disabled by default in the future. Set it to True or False to
suppress this warning.
warnings.warn(FSADeprecationWarning(
>>> db.create_all()
>>> from BlogSite.modals import User
>>> admin = User(username='admin', email='admin#example.com')
>>> db.session.add(admin)
>>> db.session.commit()
Traceback (most recent call last):
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\base.py", line 1705, in _execute_context
self.dialect.do_execute(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\default.py", line 681, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: user
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 2, in commit
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\session.py", line 1415, in commit
self._transaction.commit(_to_root=self.future)
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\session.py", line 829, in commit
self._prepare_impl()
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
self.session.flush()
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\session.py", line 3233, in flush
self._flush(objects)
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\session.py", line 3373, in _flush
transaction.rollback(_capture_exception=True)
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
compat.raise_(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\util\compat.py", line 198, in raise_
raise exception
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\session.py", line 3333, in _flush
flush_context.execute()
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\unitofwork.py", line 453, in execute
rec.execute(self)
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\unitofwork.py", line 627, in execute
util.preloaded.orm_persistence.save_obj(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\persistence.py", line 242, in save_obj
_emit_insert_statements(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\persistence.py", line 1219, in _emit_insert_statements
result = connection._execute_20(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\base.py", line 1520, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\sql\elements.py", line 313, in _execute_on_connection
return connection._execute_clauseelement(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\base.py", line 1389, in _execute_clauseelement
ret = self._execute_context(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\base.py", line 1748, in _execute_context
self._handle_dbapi_exception(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\base.py", line 1929, in _handle_dbapi_exception
util.raise_(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\util\compat.py", line 198, in raise_
raise exception
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\base.py", line 1705, in _execute_context
self.dialect.do_execute(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\default.py", line 681, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user
[SQL: INSERT INTO user (username, email) VALUES (?, ?)]
[parameters: ('admin', 'admin#example.com')]
(Background on this error at: http://sqlalche.me/e/14/e3q8)
>>>
For Trying to solve My Problem,Thank You in Advance

Create a flask-migrate object in your application instance:
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
# ...
Run your migrations:
(venv)$ flask db init
(venv)$ flask db migrate -m 'user table'
(venv)$ flask db upgrage
You should have user table after this

Related

Flask SQLAlquemy db.commit breaks stuff

I am learning about Rest APIs and Flask. Following a simple tutorial, something doesn't work and I can't get it fixed. I create a database and I want to add something to it. My file is called "API.py" and I am using PyCharm. After running the file, I type into the Python Console in Python:
from API import db
from API import Drink
Drink.query.all() (returns an empty list, all good)
drink = Drink(name="x", description="y")
Drink.query.all() (returns an empty list, all good)
db.session.add(drink)
Drink.query.all() (returns the drink, all good)
db.session.commit()
Drink.query.all() - ERROR
I tried several things, but I can't figure it out. In the tutorial, everything is working just fine. Would you please help me fix this? Below you will find the error message and the code:
Error message:
Traceback (most recent call last):
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\base.py", line 1800, in _execute_context
context = constructor(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\default.py", line 1015, in _init_compiled
self.cursor = self.create_cursor()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\default.py", line 1386, in create_cursor
return self.create_default_cursor()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\default.py", line 1389, in create_default_cursor
return self._dbapi_connection.cursor()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\pool\base.py", line 1083, in cursor
return self.dbapi_connection.cursor(*args, **kwargs)
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 5244 and this is thread id 9008.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\IPython\core\interactiveshell.py", line 3397, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-7-87e83f2944ed>", line 1, in <cell line: 1>
Drink.query.all()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\orm\query.py", line 2772, in all
return self._iter().all()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\orm\query.py", line 2907, in _iter
result = self.session.execute(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\orm\session.py", line 1712, in execute
result = conn._execute_20(statement, params or {}, execution_options)
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\base.py", line 1705, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\sql\elements.py", line 333, in _execute_on_connection
return connection._execute_clauseelement(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\base.py", line 1572, in _execute_clauseelement
ret = self._execute_context(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\base.py", line 1806, in _execute_context
self._handle_dbapi_exception(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\base.py", line 2124, in _handle_dbapi_exception
util.raise_(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
raise exception
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\base.py", line 1800, in _execute_context
context = constructor(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\default.py", line 1015, in _init_compiled
self.cursor = self.create_cursor()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\default.py", line 1386, in create_cursor
return self.create_default_cursor()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\default.py", line 1389, in create_default_cursor
return self._dbapi_connection.cursor()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\pool\base.py", line 1083, in cursor
return self.dbapi_connection.cursor(*args, **kwargs)
sqlalchemy.exc.ProgrammingError: (sqlite3.ProgrammingError) SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 5244 and this is thread id 9008.
[SQL: SELECT drink.iden AS drink_iden, drink.name AS drink_name, drink.description AS drink_description
FROM drink]
[parameters: [{}]]
(Background on this error at: https://sqlalche.me/e/14/f405)
Code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data.db"
db = SQLAlchemy(app)
class Drink(db.Model):
iden = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
description = db.Column(db.String(120))
def __repr__(self):
return f"{self.name} - {self.description}"
db.create_all()
#app.route('/')
def index():
return "Hey"
#app.route('/drinks')
def get_drinks():
return {"drinks": "drink data"}
if __name__ == "__main__":
app.run(debug=True, port=8000)
Thanks to snakecharmerb's comment, I replaced
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data.db"
by
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data.db?check_same_thread=False"
and it works just fine now.

Unsure why I get a thread id error when using SQLAlchemy

I'm trying to create a database for a flask market website using models (User and Item).
When I go into my python terminal and execute the following commands:
from market import db
from market.models import User,Item
u1 = User(username='Hay', password_hash = '123', email_address='ahus#gmail.com')
db.session.add(u1)
db.session.commit()
User.query.all()
i1 = Item(name='Iphone X', description='New iphone', barcode='123456789101', price=760)
db.session.add(i1)
db.session.commit()
i2 = Item(name='Macbook', description='New macbook', barcode='123456789102', price=1000)
db.session.add(i2)
db.session.commit()
As soon as I enter db.session.commit() for the second time I get this error:
Traceback (most recent call last):
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1702, in _execute_context
context = constructor(
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 1013, in _init_compiled
self.cursor = self.create_cursor()
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 1361, in create_cursor
return self.create_default_cursor()
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 1364, in create_default_cursor
return self._dbapi_connection.cursor()
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\pool\base.py", line 1083, in cursor
return self.dbapi_connection.cursor(*args, **kwargs)
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 24304 and this is thread id 12744.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3448, in _flush
flush_context.execute()
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 456, in execute
rec.execute(self)
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 630, in execute
util.preloaded.orm_persistence.save_obj(
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 244, in save_obj
_emit_insert_statements(
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 1221, in _emit_insert_statements
result = connection._execute_20(
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1614, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 325, in _execute_on_connection
return connection._execute_clauseelement(
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1481, in _execute_clauseelement
ret = self._execute_context(
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1708, in _execute_context
self._handle_dbapi_exception(
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2026, in _handle_dbapi_exception
util.raise_(
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1702, in _execute_context
context = constructor(
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 1013, in _init_compiled
self.cursor = self.create_cursor()
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 1361, in create_cursor
return self.create_default_cursor()
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 1364, in create_default_cursor
return self._dbapi_connection.cursor()
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\pool\base.py", line 1083, in cursor
return self.dbapi_connection.cursor(*args, **kwargs)
sqlalchemy.exc.ProgrammingError: (sqlite3.ProgrammingError) SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 24304 and this is thread id 12744.
[SQL: INSERT INTO item (name, price, barcode, description, owner) VALUES (?, ?, ?, ?, ?)]
[parameters: [{'barcode': '123456789102', 'price': 760, 'description': 'New laptop', 'name': 'Laptop', 'owner': None}]]
(Background on this error at: https://sqlalche.me/e/14/f405)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 966, in _rollback_impl
self.engine.dialect.do_rollback(self.connection)
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 682, in do_rollback
dbapi_connection.rollback()
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 24304 and this is thread id 12744.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<string>", line 2, in commit
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1431, in commit
self._transaction.commit(_to_root=self.future)
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
self._prepare_impl()
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
self.session.flush()
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3348, in flush
self._flush(objects)
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3488, in _flush
transaction.rollback(_capture_exception=True)
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 84, in __exit__
compat.raise_(value, with_traceback=traceback)
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3488, in _flush
transaction.rollback(_capture_exception=True)
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 900, in rollback
util.raise_(rollback_err[1], with_traceback=rollback_err[2])
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 865, in rollback
t[1].rollback()
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2340, in rollback
self._do_rollback()
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2544, in _do_rollback
self._close_impl(try_deactivate=True)
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2527, in _close_impl
self._connection_rollback_impl()
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2519, in _connection_rollback_impl
self.connection._rollback_impl()
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 968, in _rollback_impl
self._handle_dbapi_exception(e, None, None, None, None)
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2026, in _handle_dbapi_exception
util.raise_(
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 966, in _rollback_impl
self.engine.dialect.do_rollback(self.connection)
File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 682, in do_rollback
dbapi_connection.rollback()
sqlalchemy.exc.ProgrammingError: (sqlite3.ProgrammingError) SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 24304 and this is thread id 12744.
(Background on this error at: https://sqlalche.me/e/14/f405)
I don't know why and how to fix this, does anyone know why this happens and how I can fix it?
This is the code for my models:
from market import db
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
username = db.Column(db.String(length=30), nullable=False, unique=True)
email_address = db.Column(db.String(length=50), nullable=False, unique=True)
password_hash = db.Column(db.String(length=60), nullable=False)
budget = db.Column(db.Integer(), nullable=False, default=1000) # Users have 1000 points to spend at the start
items = db.relationship('Item', backref='owned_user', lazy=True)
class Item(db.Model):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(length=30), nullable=False, unique=True)
price = db.Column(db.Integer(), nullable=False)
barcode = db.Column(db.String(length=12), nullable=False, unique=True)
description = db.Column(db.String(length=1000), nullable=False)
owner = db.Column(db.Integer(), db.ForeignKey('user.id'))
def __repr__(self):
return f'Item {self.name}'
I was executing all those database commands in the PyCharm repl. I believe it has something to do with memory which is why it won't work in the python console on Pycharm. It works fine in a command prompt terminal and in a python file.

flask db init returns "sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table"

I've been working on a web app in flask using an sqlite database. This has been going fine so far, and I am aware of the fact sqlite is limited in terms of alterations to tables once a database exists.
However, so far i have been able to modify tables (add columns, rename columns, etc.) of several models in the models.py without issue. Noting here I do use
migrate = Migrate(app, db, render_as_batch=True)
in the app initialization, which has been needed to realize some changes to the database.
Now however, I have received the following error when trying to run flask db migrate after adding a new column to the model "User":
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py", line 1249, in _execute_context
cursor, statement, parameters, context
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/default.py", line 580, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: user
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/bin/flask", line 8, in <module>
sys.exit(main())
File "/usr/local/lib/python3.6/dist-packages/flask/cli.py", line 966, in main
cli.main(prog_name="python -m flask" if as_module else None)
File "/usr/local/lib/python3.6/dist-packages/flask/cli.py", line 586, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/flask/cli.py", line 425, in decorator
with __ctx.ensure_object(ScriptInfo).load_app().app_context():
File "/usr/local/lib/python3.6/dist-packages/flask/cli.py", line 388, in load_app
app = locate_app(self, import_name, name)
File "/usr/local/lib/python3.6/dist-packages/flask/cli.py", line 240, in locate_app
__import__(module_name)
File "/home/arthur/Development/ISLWeb/islweb.py", line 1, in <module>
from app import app, db
File "/home/arthur/Development/ISLWeb/app/__init__.py", line 24, in <module>
from app import routes, models
File "/home/arthur/Development/ISLWeb/app/routes.py", line 11, in <module>
from app.forms import (LoginForm, RegistrationForm, CreateLaunchForm,
File "/home/arthur/Development/ISLWeb/app/forms.py", line 93, in <module>
class NewActionForm(FlaskForm):
File "/home/arthur/Development/ISLWeb/app/forms.py", line 95, in NewActionForm
users = User.query.all()
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/query.py", line 3186, in all
return list(self)
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/query.py", line 3342, in __iter__
return self._execute_and_instances(context)
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/query.py", line 3367, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py", line 988, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/sql/elements.py", line 287, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py", line 1107, in _execute_clauseelement
distilled_params,
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py", line 1253, in _execute_context
e, statement, parameters, cursor, context
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py", line 1473, in _handle_dbapi_exception
util.raise_from_cause(sqlalchemy_exception, exc_info)
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/compat.py", line 398, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/compat.py", line 152, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py", line 1249, in _execute_context
cursor, statement, parameters, context
File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/default.py", line 580, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user
[SQL: SELECT user.id AS user_id, user.username AS user_username, user.email AS user_email, user.password_hash AS user_password_hash, user.has_admin_rights AS user_has_admin_rights, user.is_customer AS user_is_customer
FROM user]
(Background on this error at: http://sqlalche.me/e/e3q8)
this is strange to me, because:
the table user is (and has been) there
I have been able to add columns to the User model before
I can still add columns to other models without errors
Now, I have seen this sqlite3.OperationalError coming up in many question here and elsewhere, but none of them seem to relate to the situation at hand here, as the codebase was working fine before, and so did migrations (they still do with all other models as well) Also, I have tried as a manner of test to delete the migrations folder as well as the database file, starting anew with:
flask db init
Which in my understanding starts a whole DB anew (including new migration script). Funnily enough this throws the exact same error as above. Which I also do not understand at all, as there is no db to read from.
My user model is as follows (with the column I'm trying to add commented):
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
actions = db.relationship('Action', backref='owner', lazy='dynamic')
events = db.relationship('WebLogEvent', backref='user', lazy='dynamic')
has_admin_rights = db.Column(db.Boolean)
is_customer = db.Column(db.Boolean)
#permissions = db.Column(db.String(256), index=True)
def __repr__(self):
return '<User {}>'.format(self.username)
#staticmethod
def table_header():
return ["ID", "Username", "e-mail", "Admin"]
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def as_table_row(self):
return [self.id, self.username, self.email, self.has_admin_rights]
Any thoughts on what could be the matter here are most welcome.
You are issuing a query in the global scope of the application, in class NewActionForm. The query is User.query.all(), according to your stack trace.
The problem with this is that code that is in the global scope executes at import time. For many things this is okay, but database access is usually problematic, because you have to create and configure your Flask application instance before the database is accessible.
So the solution is to not query the database in the global scope. You can probably move that logic into the form's constructor method.

Flask-SQLAlchemy wtform based on db

My app is working on my main PC. I tried to clone the app to my laptop (I tried to initialize it on PC in a different directory and the problem was the same so the problem isn't with the laptop) and when initializing the db with flask db init I got the following error:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: race [SQL: 'SELECT race.id AS race_id, race.name AS race_name \nFROM race'] (Background on this error at: http://sqlalche.me/e/e3q8)
What I'm trying to do is in one of my forms to include a wtforms RadioField with choices based on the race table in db. So for every row in that table I want one choice in the selection. The important part of the form looks like this:
class RegistrationForm(FlaskForm):
race = RadioField('Race', validators=[InputRequired('Choose a race.')],
choices=races, coerce=int)
And the races variable is outside the form like this (before the form itself):
with create_app().app_context():
races = [(race.id, race.name.capitalize()) for race in Race.query.all()]
I figured that this last line is the problem from the call stack:
Traceback (most recent call last):
File "/home/dareon4/workspace/test/venv/bin/flask", line 11, in <module>
sys.exit(main())
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/flask/cli.py", line 894, in main
cli.main(args=args, prog_name=name)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/flask/cli.py", line 557, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/click/decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/flask/cli.py", line 411, in decorator
with __ctx.ensure_object(ScriptInfo).load_app().app_context():
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/flask/cli.py", line 372, in load_app
app = locate_app(self, import_name, name)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/flask/cli.py", line 235, in locate_app
__import__(module_name)
File "/home/dareon4/workspace/test/shapes.py", line 5, in <module>
app = create_app()
File "/home/dareon4/workspace/test/app/__init__.py", line 43, in create_app
from app.blueprints.auth import bp as auth_bp
File "/home/dareon4/workspace/test/app/blueprints/auth/__init__.py", line 7, in <module>
from . import routes
File "/home/dareon4/workspace/test/app/blueprints/auth/routes.py", line 13, in <module>
from .forms import LoginForm, RegistrationForm, ResetPasswordRequestForm, \
File "/home/dareon4/workspace/test/app/blueprints/auth/forms.py", line 19, in <module>
races = [(race.id, race.name.capitalize()) for race in Race.query.all()]
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/sqlalchemy/orm/query.py", line 2836, in all
return list(self)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/sqlalchemy/orm/query.py", line 2988, in __iter__
return self._execute_and_instances(context)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/sqlalchemy/orm/query.py", line 3011, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 948, in execute
return meth(self, multiparams, params)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/sqlalchemy/sql/elements.py", line 269, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 1060, in _execute_clauseelement
compiled_sql, distilled_params
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 1200, in _execute_context
context)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 1413, in _handle_dbapi_exception
exc_info
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/sqlalchemy/util/compat.py", line 265, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/sqlalchemy/util/compat.py", line 248, in reraise
raise value.with_traceback(tb)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context
context)
File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/sqlalchemy/engine/default.py", line 509, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: race [SQL: 'SELECT race.id AS race_id, race.name AS race_name \nFROM race'] (Background on this error at: http://sqlalche.me/e/e3q8)
So the problem is that I don't have the db initialized when I'm running the flask db init command and that one line needs the db to exist. This probably doesn't have a solution so I'm not asking how to correct this implementation, but how to do it correctly to have form based on rows from the db. I don't have hundreds of races so I could hardcode them in but I wanted to do it this way.
So after some googling I found that you can add the RadioField choices dynamically in the views like this:
#bp.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
form.race.choices = [(race.id, race.name.capitalize()) for race in Race.query.all()]
This is exactly what I was looking for.

Flask-SQLAlchemy create_all()

When i run the dbManager.create_all() command, it runs with out errors but fails to create the tables. When i delete the database and run the create_all() command, i get the no such database as ##### error which i should get but when the database does exist, nothing happens.
Please can anyone see what i'm doing wrong?
from blogconfig import dbManager
class Art(dbManager.Model):
id = dbManager.Column(dbManager.Integer, primary_key = True)
title = dbManager.Column(dbManager.String(64), index = True, unique = True)
content = dbManager.Column(dbManager.Text(5000))
def __repr__(self):
return '<Art %r>' %(self.title)
EDIT
This is the shell command
from blogconfig import dbManager
>>> dbManager.create_all()
import models
>>> a = models.Art(title='des', content='asdfvhbdjbjdn')
>>> dbManager.session.add(a)
>>> dbManager.session.commit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/scoping.py", line 149, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 721, in commit
self.transaction.commit()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 354, in commit
self._prepare_impl()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 334, in _prepare_impl
self.session.flush()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1818, in flush
self._flush(objects)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1936, in _flush
transaction.rollback(_capture_exception=True)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/langhelpers.py", line 58, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1900, in _flush
flush_context.execute()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 372, in execute
rec.execute(self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 525, in execute
uow
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 64, in save_obj
table, insert)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 569, in _emit_insert_statements
execute(statement, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 662, in execute
params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 761, in _execute_clauseelement
compiled_sql, distilled_params
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 874, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1024, in _handle_dbapi_exception
exc_info
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/compat.py", line 195, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 867, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 324, in do_execute
cursor.execute(statement, parameters)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
sqlalchemy.exc.ProgrammingError: (ProgrammingError) (1146, "Table 'blog.art' doesn't exist") 'INSERT INTO art (title, content) VALUES (%s, %s)' ('des', 'asdfvhbdjbjdn')
dbManager will not know about the models you define in other modules unless they are imported before running create_all.
In a real application this shouldn't matter because running the flask app should set up the db and import views/blueprints to register them. Since the views use the models, the models are indirectly imported and are available to the dbManager.
Either import your models in the blogconfig module after creating the dbManager instance, or change the order of you shell commands to be
>>> from blogconfig import dbManager
>>> import models
>>> dbManager.create_all()
SQLAlchemy will only create tables, the database must already exist, which is why you're seeing the other error when you delete the database.

Categories