Getting error while commiting in the SQLAlchemy database - python

I'm working on a small flask tutorial and after add some data, I try to commit inside the database. And, in that time, I get the following error,
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user [SQL: u'INSERT INTO user (nickname, email) VALUES (?, ?)'] [parameters: ('john', 'john#email.com')]
This table stands with the mdoel provided in the models.py file:
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
def __repr__(self):
return '<User %r>' % (self.nickname)
class Post(db.Model):
id = db.Column(db.Integer, primary_key = True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return '<Post %r>' % (self.body)
It seems that the User table is not exist or created. So, I have run the following script in the shell,
from sqlalchemy import create_engine
from config import SQLALCHEMY_DATABASE_URI
engine = create_engine(SQLALCHEMY_DATABASE_URI)
from sqlalchemy import MetaData
m = MetaData()
m.reflect(engine)
for table in m.tables.values():
print(table.name)
for column in table.c:
print(column.name)
And I get the result as following,
migrate_version
repository_id
repository_path
version
post
id
body
timestamp
user_id
user
id
nickname
email
Which means that the user table is created and exist. What is the issue here and how to solve it ?
I have a second script also produces the same result:
from sqlalchemy import inspect
inspector = inspect(engine)
for table_name in inspector.get_table_names():
for column in inspector.get_columns(table_name):
print("Column: %s" % column['name'])

Related

flask-sqlalchemy foreignkey populating table with null

I'm trying to implement a foreign key at one of my tables in flask-sqlalchemy, but keep getting this error all the time:
sqlalchemy.exc.IntegrityError: (psycopg2.errors.NotNullViolation) null value in column "user_id" of relation "applications" violates not-null constraint DETAIL: Failing row contains (3, Company ABC, Software Engineer, New York, NY, USA, Applied, , 2022-09-09, null).
Here is the code:
from flask_login import UserMixin
from database.database import db
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(), nullable=False)
password = db.Column(db.String(), nullable=False)
name = db.Column(db.String(), default='', nullable=True)
application = db.relationship('JobApplicationTracker', lazy=True,backref='author')
def __repr__(self) -> str:
return self.email
def __str__(self) -> str:
return self.email
code:
from database.database import db
class JobApplicationTracker(db.Model):
__tablename__ = 'applications'
id = db.Column(db.Integer, primary_key=True, nullable=False)
name = db.Column(db.String(), nullable=False)
title = db.Column(db.String(), nullable=False)
location = db.Column(db.String(), nullable=False)
status = db.Column(db.String(), nullable=False)
notes = db.Column(db.String(), default='', nullable=True)
date_applied = db.Column(db.String(), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
def __repr__(self):
return f'{self.title} at {self.name}'
def __str__(self):
return f'{self.title} at {self.name}'
I have an "applications" table and a "users" table.
The issue is because you have set nullable=False for user_id column in your JobApplicationTracker model but when trying to add, you are passing null value for user_id.
You can try creating a user, pass that user id and things should work fine.
If you want it to work without user id, trying having nullable=true. Again, changing it in the model won't get reflected in the table. You might have to manually change it in the database

I have a confusion using backref in Flask SQLAlchemy database tables

models.py
#login_manager.user_loader
def load_user(username):
return User.query.get(username)
class User(db.Model,UserMixin):
__tablename__ = 'user_accounts'
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(50),unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20),default='default.jpg')
password = db.Column(db.String(80), nullable=False)
task = db.relationship('Tasks', backref='author', lazy=True)
def __repr__(self):
return f'User <{self.id}> {self.username}'
class Tasks(db.Model):
__tablename__ = 'tasks'
id = db.Column(db.Integer,primary_key=True)
title = db.Column(db.String(100),nullable=False)
content = db.Column(db.Text)
user = db.Column(db.String(50),db.ForeignKey('user_accounts.username'),nullable=False)
date_created = db.Column(db.DateTime, default=datetime.datetime.utcnow,nullable=False)
completed = db.Column(db.Boolean,default=False,nullable=False)
def __repr__(self):
return f'{self.title} by {self.user} ({self.date_created})'
Error:
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'tasks.author' could not find table 'user' with which to generate a foreign key to target column 'username'
Here I have a problem that when I trying to run db.create_all() in terminal I am getting the above error message. I am a bit confused in the usage of backref for db.relationship as my target is to represent a user could have specific task and a task is owned by that user so may I ask how could I properly organize the relationship between two tables in order to create a table with no error messages?

Unable to store data in sqlite db with Python / SQLAlchemy (Flask)

Hello I'm struggling with this error since weeks.
In my python/flask app I need to store a pw in a db table user in SQLite with SQLalchemy.
The table seemds to be correctly created when I check sqlite> .schema the column pwd is there.
When I run the app it returns an error saying the column pwd does not exist (see error below).
I tried several times dropping the table, trying in a new db but nothing, I think the table is created correctly but there must be something wrong in the code? Could also be the db that was messed up but I don't think so.
Here I create the table and define the User class, as per official SQLAlchemy documentation
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from sqlalchemy import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data-users.sqlite'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer(), primary_key = True, autoincrement=True)
username = db.Column(db.String(64), unique = True)
pwd = db.Column(db.String())
def __repr__(self):
return '<User %r>' % self.username
Here I store the user data in the table
from store_user_db import User, db
db.create_all()
DICP_FTP_DESTINATION_PSW=self.submit_pwd()
user = User(id=001,username="ita_itf",pwd=DICP_FTP_DESTINATION_PSW)
db.session.add(user)
db.session.commit()
This is the error:
sqlalchemy.exc.OperationalError
OperationalError: (sqlite3.OperationalError) table user has no column named pwd
[SQL: INSERT INTO user (id, username, pwd) VALUES (?, ?, ?)]
[parameters: (1, 'ita_itf', <read-only buffer for 0x7efe495709f0, size -1, offset 0 at 0x7.....
I don't have much experience flask and SQlAlchemy, but here is a sample app which is working for me.
The Model definitions are taken from the documentation and added a test model during runtime to see if it is still able to create new tables and it did.
If you have a large app, I'd prefer to use flask-migrate library which can create versioned migrations from your models for creating/modifying your tables.
from datetime import datetime
from flask import Flask, request, flash, url_for, redirect, json
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = "user"
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
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
def __repr__(self):
return '<Category %r>' % self.name
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80), nullable=False)
body = db.Column(db.Text, nullable=False)
pub_date = db.Column(db.DateTime, nullable=False,
default=datetime.utcnow)
category_id = db.Column(db.Integer, db.ForeignKey('category.id'),
nullable=False)
category = db.relationship('Category',
backref=db.backref('posts', lazy=True))
def __repr__(self):
return '<Post %r>' % self.title
class Test(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
def __repr__(self):
return '<Test %r>' % self.name
def insertAdminUser():
admin = User(username='admin', email='admin#example.com')
db.session.add(admin)
db.session.commit()
#app.route('/insert-admin', methods = ['GET'])
def insertAdmin():
insertAdminUser()
return app.response_class(
response=json.dumps({
"message": "inserted"
}),
mimetype='application/json'
)
if __name__ == '__main__':
db.create_all()
app.run(debug = True)

Cannot create user in database: sqlalchemy.exc.InvalidRequestError

I am trying to add an user to the database file but i get the following error when trying to create an User object:
sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class Patient->patient'. Original exception was: Could not determine join condition between parent/child tables on relationship Patient.documents - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
from flask import Flask, render_template, flash
from flask_sqlalchemy import SQLAlchemy
from forms import LoginForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'SECRETKEY'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///storage.db'
db = SQLAlchemy(app)
"""
Users
"""
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
username = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
mail = db.Column(db.String, default='test#mail')
role = db.Column(db.Integer)
def __repr__(self):
return f"User('{self.username}', '{self.name}')"
"""
Patients
"""
class Patient(db.Model):
id = db.Column(db.Integer, primary_key=True)
prename = db.Column(db.String, nullable=False)
name = db.Column(db.String, nullable=False)
mail = db.Column(db.String, default='test#mail')
birthdate = db.Column(db.String, nullable=False)
documents = db.relationship('Doc', backref='patient', lazy=True)
def __repr__(self):
return f"Patient('{self.prename}', '{self.name}')"
"""
Documents
"""
class Doc(db.Model):
from datetime import datetime
pdfid = db.Column(db.Integer, primary_key=True)
path = db.Column(db.String)
created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
deletetime = db.Column(db.Integer, nullable=False)
patientid = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f"Docs('{self.path}', '{self.created}')"
My Steps in a python Terminal (the file is called index):
from index import db
db.create_all()
from index import User, Doc, Patient
user1 = User(name='Test User', username='test', password='testtest', role=1)
When I try step 4 I get the above described error.
I don't see any problem in my code so I would appreciate any help :)

SQLAlchemy show me that "AttributeError: type object 'User' has no attribute 'columns'"

I am building a small project use python+Flask+SQLAlchemy, I make a model file following:
################# start of models.py #####################
from sqlalchemy import Column, Integer, String, Sequence, Date, DateTime, ForeignKey
from sqlalchemy.orm import relationship, backref
from dk.database import Base
import datetime
class User(Base):
__tablename__ = 'users'
id = Column(Integer, Sequence('seq_user_id'), primary_key=True)
name = Column(String(50), unique=True, index = True, nullable = False)
email = Column(String(120), unique=True, index = True, nullable = False)
password = Column(String(128), nullable = False)
def __init__(self, name, email, password):
self.name = name
self.email = email
self.password = password
def __repr__(self):
return '<User %r>' % (self.name)
class Session(Base):
__tablename__ = 'session'
id = Column(String(128), primary_key = True, nullable = False)
user_name = Column(String(30), nullable = False)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship('User', backref=backref('session', lazy='dynamic'))
def __repr__(self):
return '<Session %r>' % (self.id)
################# end of models.py #####################
and I build a initial file following:
################# start of __init__.py #################
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config') #load database config information
db = SQLAlchemy(app)
################# end of __init__.py #################
when I run the "init_db()" in script, tables built to database successful.
but when I want to see the SQL script then I run the "print CreateTable(User)" in script, the system show follwing errors:
File "/home/jacky/flaskcode/venv/lib/python2.6/site-packages/sqlalchemy/schema.py", line 3361, in __init__
for column in element.columns
AttributeError: type object 'User' has no attribute 'columns'
I have no idea how to solve this problem!
You need to pass in a Table object for CreateTable():
CreateTable(User.__table__)
but if you wanted to see the SQL statements that SQLAlchemy issues you are better off switching on echoing by setting echo=True when creating the connection.
The Flask SQLAlchemy integration layer supports a SQLALCHEMY_ECHO option to set that flag.

Categories

Resources