简体   繁体   中英

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM