Python - SQLAlchemy获取'表' object不可调用错误

时间:2017-08-23 16:29:14

标签: python sqlalchemy

我已经在我的python脚本中定义了一个现有的DB表,每当我尝试向db表插入一行时,都会收到一条错误消息,指出" Table对象不可调用"

您可以在下面找到我收到的代码和错误消息。任何支持将不胜感激:

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

错误讯息:

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

这就是表格的样子

                                                             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)

1 个答案:

答案 0 :(得分:0)

不使用auto_map插入的另一种方法是将表的方法用于插入。文档为here

  

插入(dml,值=无,内联=假,**假)   对此TableClause生成一个insert()构造。

     

例如:

     

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

在代码中看起来像这样:

class test implements TestInterface {
    @Override
    public void showOne() {
        System.out.println("1");
    }

    @Override
    public void showTwo() {
        System.out.println("2");
    }
}


public class ImplementInterface {
    public static void main(String[] args) {
        test t1 = new test();
        t1.showOne();    // prints 1
        t1.showTwo();    // prints 2

        TestInterface1 t2 = new test();
        t2.showOne();    // prints 1
        t2.showTwo();    // prints 2
    }
}

理想情况下,您将定义在单独的文件夹中,而不是在 app.py 中。您还可以使用utils函数,该函数产生会话,然后提交或捕获异常并对其进行回滚。像这样:

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

      session.commit()
      return

然后您的函数将如下所示:

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

您可以通过

从您的 app.py 中获取 db
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