[Python] Sqlalchemy add duplicated record in database

Discussão em 'Python' iniciado por Stack, Abril 20, 2025.

  1. Stack

    Stack Membro Participativo

    I'm learning the way how to modularize flask application using blueprints and break database models into multiple files (one per entity)

    I encounter a strange issue while building SQLite file and writing initial record for admin account, - SQLAlchemy added two records for one user.

    Here is project layout and key files

    [​IMG]

    runserver.py

    #import os
    from sbsuite import app
    from sbsuite.database import init_db, createAdmin

    init_db()
    createAdmin()

    if __name__ == "__main__":
    app.run(debug=True)


    models.py

    from sbsuite import app
    from sqlalchemy import Column, Integer, String
    from sbsuite.database import Base
    from flask_marshmallow import Marshmallow

    class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    email = Column(String(80))
    password = Column(String(50))
    roles = Column(String(50))


    # JSON Schema
    # should I create Marshmallow instance here?
    ma = Marshmallow(app)

    class UserSchema(ma.Schema):
    class Meta:
    fields = ('id', 'name', 'email', 'password')

    user_schema = UserSchema()
    users_schema = UserSchema(many=True)


    database.py

    from sbsuite import app
    from sqlalchemy import create_engine
    from sqlalchemy.orm import Session, scoped_session, sessionmaker
    from sqlalchemy.ext.declarative import declarative_base
    from flask_sqlalchemy import SQLAlchemy

    engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], convert_unicode=True)
    db_session = scoped_session(sessionmaker(autocommit=False,
    autoflush=False,
    bind=engine))

    Base = declarative_base()
    Base.query = db_session.query_property()


    from sbsuite.api.models import User, UserSchema
    from sbsuite.api.productMdl import Product, ProductSchema

    def init_db():
    Base.metadata.create_all(bind=engine)

    def createAdmin():
    print("Create admin user")
    admin = User(name="admin",email="admin@sbsuite.com", password="password", roles = "admin")
    with Session(engine) as session:
    session.add(admin)
    session.commit()
    print("admin user created") # why users added twice?


    In last snippet after session.commit() I check database and see two records for admin user.

    Continue reading...

Compartilhe esta Página