python 3.x - Initialize SQLAlchemy table with file data: empty object -


i started using sqlalchemy creating tables in postgresql , experienced folks here:

i have problem initializing table data read file. here's example of tried, in part based on this post.

schema = "spectr" # schema exists in database connstr = "postgresql+psycopg2://postgres:postgres@localhost/postgres" mymetadata = metadata(schema=schema) base = declarative_base(metadata=mymetadata) engine = create_engine(connstr, echo=true)  class file(base): """ file metadata """ __tablename__ = "files" id = column(integer, primary_key=true) altitude = column(numeric(precision=6, scale=1)) average_ref = column(integer, nullable=false) average_target = column(integer, nullable=false)  def __init__(self, filename=none):     if filename != none:         dic = read_sed(filename)          k in file.__table__.columns.keys():             if k != 'id':                 file.k = dic.get(k, none)  # 'read_sed' function returns dictionary of data in filename  file().__table__.create(engine, checkfirst=true) file = file(filename)  session = sessionmaker(bind=engine) session = session() session.add(file) session.commit()  # point error since file empty , many columns nullable=false.  

here's end of error output:

sqlalchemy.exc.integrityerror: (psycopg2.integrityerror) null value in column "average_ref" violates not-null constraint detail:  failing row contains (1, null, null, null). [sql: 'insert spectro.files (altitude, average_ref, average_target)  values (%(altitude)s, %(average_ref)s, %(average_target)s) returning spectro.files.id'] [parameters: {'average_target': none, 'average_ref': none, 'altitude': none}] 

any idea wrong?

thanks lot help.

i not sure line supposed do:

file.k = dic.get(k, none) 

as looks, set property k (not value of variable k) file class (not instance). assuming want set field such altitude, average_ref, average_target in loaded file on current instance of file, should set them on self using setattr instead:

setattr(self, k, dic.get(k, none)) 

also if dic instance of dict, , none redundant , can use setattr(self, k, dic.get(k))