5

I have defined an existing DB Table in my python script and whenever I tried to insert a row to db table, I receive an error message stating the "Table object is not callable"

Below you can find the code and error message I receive. Any support will be appreciated:

engine = create_engine('postgresql://user:pwd@localhost:5432/dbname', 

client_encoding='utf8')
metadata = MetaData()
MyTable = Table('target_table', metadata, autoload=True, autoload_with=engine)
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
:
:
:
def recod_to_db(db_hash):
    db_instance = MyTable(**db_hash)
    session.add(db_instance)
    session.commit()
    return

Error Message:

  File "myprog.py", line 319, in recod_to_db
    db_instance = MyTable(**db_hash)
TypeError: 'Table' object is not callable

This is how the table looks like

                                                             Table "public.target_table"
      Column       |            Type             |                       Modifiers                        | Storage  | Stats target | Description 
-------------------+-----------------------------+--------------------------------------------------------+----------+--------------+-------------
 id                | integer                     | not null default nextval('target_table_id_seq'::regclass) | plain    |              | 
 carid             | integer                     |                                                        | plain    |              | 
 triplecode        | character varying           |                                                        | extended |              | 
 lookup            | integer                     |                                                        | plain    |              | 
 type              | character varying           |                                                        | extended |              | 
 make              | character varying           |                                                        | extended |              | 
 series            | character varying           |                                                        | extended |              | 
 model             | character varying           |                                                        | extended |              | 
 year              | integer                     |                                                        | plain    |              | 
 fuel              | character varying           |                                                        | extended |              | 
 transmission      | character varying           |                                                        | extended |              | 
 mileage           | integer                     |                                                        | plain    |              | 
 hp                | integer                     |                                                        | plain    |              | 
 color             | character varying           |                                                        | extended |              | 
 door              | integer                     |                                                        | plain    |              | 
 location          | character varying           |                                                        | extended |              | 
 url               | character varying           |                                                        | extended |              | 
 register_date     | date                        |                                                        | plain    |              | 
 auction_end_time  | timestamp without time zone |                                                        | plain    |              | 
 body_damage       | integer                     |                                                        | plain    |              | 
 mechanical_damage | integer                     |                                                        | plain    |              | 
 target_buy        | integer                     |                                                        | plain    |              | 
 price             | integer                     |                                                        | plain    |              | 
 currency          | character varying           |                                                        | extended |              | 
 auctionid         | integer                     |                                                        | plain    |              | 
 seller            | character varying           |                                                        | extended |              | 
 auction_type      | character varying           |                                                        | extended |              | 
 created_at        | timestamp without time zone | not null                                               | plain    |              | 
 updated_at        | timestamp without time zone | not null                                               | plain    |              | 
 estimated_value   | integer                     |                                                        | plain    |              | 
Indexes:
    "target_table_pkey" PRIMARY KEY, btree (id)
3
  • Could you re-indent your code. How Table is defined? Commented Aug 23, 2017 at 16:32
  • Inside the definition of recod_to_db, you have MyTable(**db_hash). Shouldn't that be Table(**db_hash)? MyTable is an already created object that does not have a __call__ method. In any case, that's what the issue is. Commented Aug 23, 2017 at 17:56
  • 5
    Table is a SQLAlchemy Core concept; you cannot use it to construct an instance of a model and add it to the session (which are ORM concepts). You'll want to use automap to create mapped classes for your tables. Commented Aug 23, 2017 at 17:57

1 Answer 1

3

Another way of inserting without auto_map is using the table's method for insert. Documentation is here

insert(dml, values=None, inline=False, **kwargs) Generate an insert() construct against this TableClause.

E.g.:

table.insert().values(name='foo')

In code it would look like this:

  def record_to_db(MyTable):
      insert_stmnt = MyTable.insert().values(column_name=value_you_want_to_insert)
      session.execute(insert_stmnt) 

      session.commit()
      return

Ideally, you'd have your table defined in a separate folder other than in your app.py. You can also have utils functions that yields the session and then commits or catches an exception and that a rollback on it. Something like this:

def get_db_session_scope(sql_db_session):
    session = sql_db_session()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()

Then your function would look like this:

def record_to_db(MyTable):
      with get_db_session_scope(db) as db_session:
          insert_stmnt = 
MyTable.insert().values(column_name=value_you_want_to_insert)
          session.execute(insert_stmnt) 

      return

You can get db from your app.py through

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.