2017-02-17 6 views
0

数時間のデバッグの後、組織にはPythonの専門知識が多くないため、私はこのコミュニティに助けを求めています。SQLAchemy + Pyramidを使用してDBに行を保存できません

私はthis tutorialをデータベースにコミットすることを目標にしています。エラーは報告されませんが、私も行を保存していません。私は間違って何をしていますか?

db2Sessionを使用してコミットしようとすると、私が手:

トランザクションは、トランザクションマネージャを使用してコミットする必要があります。

しかし、チュートリアルのどこにも、トランザクションマネージャが使用されているとは限りません。私はこのマネージャがzope.sqlalchemyを使ってバインドされていると思いましたか?しかし、何も起こっていない。もう一度ヘルプをいただければ幸いです!

I持っピラミッドAppの私の主な機能は次のセットアップ:.modelsで

from sqlalchemy import engine_from_config 
from .models import db1Session, db2Session 

def main(global_config, **settings): 
""" This function returns a Pyramid WSGI application. 
""" 
    db1_engine = engine_from_config(settings, 'db1.') 
    db2_engine = engine_from_config(settings, 'db2.') 

    db1Session.configure(bind=db1_engine) 
    db2Session.configure(bind=db2_engine) 

/__ init__py、私が持っている:

from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy.orm import (scoped_session, sessionmaker) 
from zope.sqlalchemy import ZopeTransactionExtension 

db1Session = scoped_session(sessionmaker(
    extension=ZopeTransactionExtension())) 
db2Session =  
    scoped_session(sessionmaker(extension=ZopeTransactionExtension())) 

Base = declarative_base() 

./model/db2.py Iで持っている:

class PlateWellResult(Base): 
    __tablename__ = 'SomeTable' 
    __table_args__ = {"schema": 'some_schema'} 

    id = Column("ID", Integer, primary_key=True) 
    plate_id = Column("PlateID", Integer) 
    hit_group_id = Column("HitID", Integer, ForeignKey(
     'some_schema.HitGroupID.ID')) 
    well_loc = Column("WellLocation", String) 

私の保存機能の関連ビットはこのように見えます。 ./lib/db2_api.py:

def save_selected_rows(input_data, selected_rows, hit_group_id): 
    """ Wrapper method for saving selected rows """ 
    # Assume I have all the right data below. 
    new_hit_row = PlateWellResult(
     plate_id=master_plate_id, 
     hit_group_id=hit_group_id, 
     well_loc=selected_df_row.masterWellLocation) 

    db1Session.add(new_hit_row) 
    # When I try the row below: 
    # db2Session.commit() 
    # I get: Transaction must be committed using the transaction manager 
    # If I cancel the line above, nothing gets committed. 
    return 'Save successful.' 

この関数は、私のビューアから呼び出されます。

@view_config(route_name='some_routename', renderer='json', 
      permission='create_hit_group') 
def save_to_hitgroup(self): 
    """ Backend to AJAX call to save selected rows to a hit_group """ 
    try: 
     # Assume that all values were checked and all the right 
     # parameters are passed 
     status = save_selected_rows(some_result, 
            selected_rows_list, 
            hitgroup_id) 
     json_resp = json.dumps({'errors': [], 
           'status': status}) 
     return json_resp 
    except Exception as e: 
     json_resp = json.dumps({'errors': ['Error during saving. {' 
              '0}'.format(e)], 
           'status': []}) 
     return json_resp 
+0

"トランザクション"のためにリンクしたページを検索すると、トランザクションマネージャを使用する行があります: 'with transaction.manager:'。個人的に、私はそのような複雑なグローバルまたは疑似グローバルを避けます。リクエストごとに自分自身の 'Session'を作成するだけでもっと幸せです。 – jpmc26

+0

リクエストごとのトランザクション管理パッケージ['pyramid_tm'](http://docs.pylonsproject.org/projects/pyramid_tm/en/latest/)を使用しましたか?そうでなければ、あなたは何もしていません。また、前のポストで指摘されているようにトランザクションマネージャを明示的に使用することもできます。 –

+0

ああ、それを追加する場合は、例外ハンドラで 'transaction.doom() 'や' transaction.abort() 'を手動で覚えてください。 –

答えて

1

上記のコメントが良いです。私はちょうどここで要約したいと思った。

トランザクションマネージャは、pyramid_tmによって開始/コミット/アボートされます。あなたがそれを使用していない場合、それはおそらく問題です。

また、トランザクションマネージャーに伝達する必要のある可能性のあるデータベース例外を潰すこともあります。例外ハンドラでtransaction.abort()経由でこれを行うことができます。

関連する問題