我在 Flask 應用程式中使用原始 SQLAlchemy,并且曾經在使用 SQLAlchemy 會話時遇到很多麻煩。我曾經經常收到 500 INTERNAL SERVER ERROR 提示上次會話未正確關閉或回滾錯誤。在確定了這些問題后,我對代碼進行了修改,到目前為止它對我來說效果很好。但是,我有時會收到錯誤,尤其是當我的 API 在回應之前中斷時。我想知道使用這些會話的最佳方式是什么,以便在正確的時間發生commit()、rollback()、close()等,并且它適用于所有 API。我知道 Flask-SQLAlchemy 能夠自動處理這個問題,但我想堅持使用原始 SQLAlchemy。
到目前為止,對我來說最好的作業代碼是 -
from flask import Flask
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind = mysql_engine())
db_session = Session()
@app.route('/get-score', methods=['POST'])
def handle_route1():
...
row = db_session.query(DB_Model_1) \
.filter(DB_Model_1.user_id == user_id) \
.all()
row = row[0] if row else None
if not row:
db_session.close()
return {}
db_session.close()
return {
'userId': row.user_id,
'score' : row.score
}
@app.route('/insert-score', methods=['POST'])
def handle_route2():
...
@app.route('/update-score', methods=['POST'])
def handle_route3():
...
@app.route('/delete-score', methods=['POST'])
def handle_route3():
...
我正在處理所有不同路線中的GET, INSERT, UPDATE,DELETE并且我正在尋找一種方法來盡可能有效地處理這些事務,以避免由于 API 中的任何錯誤而中斷與資料庫的連接。
一種方法是使用try-except塊,但我相信肯定有比在每條路線中單獨提及 try-except 塊更好的方法。
uj5u.com熱心網友回復:
我相信最優雅的方法是使用具有會話/事務范圍的背景關系管理器:
from contextlib import contextmanager
@contextmanager
def transaction_scope(session, close_at_exit=False):
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
finally:
if close_at_exit:
session.close()
您可以通過兩種不同的方式使用它:
1.
@app.route('/get-score', methods=['POST'])
def handle_route1():
with Session() as session:
with transaction_scope(session):
...
row = session.query(DB_Model_1) \
.filter(DB_Model_1.user_id == user_id) \
.all()
row = row[0] if row else None
if not row:
return {}
return {
'userId': row.user_id,
'score' : row.score
}
@app.route('/get-score', methods=['POST'])
def handle_route1():
session = Session()
with transaction_scope(session, close_at_exit=True):
...
row = session.query(DB_Model_1) \
.filter(DB_Model_1.user_id == user_id) \
.all()
row = row[0] if row else None
if not row:
return {}
return {
'userId': row.user_id,
'score' : row.score
}
uj5u.com熱心網友回復:
我強烈建議閱讀SQLAlchemy 檔案的這一部分。
但是 tl:dr 你可以使用 python 背景關系管理器來控制會話的范圍:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('postgresql://scott:tiger@localhost/')
Session = sessionmaker(engine)
with Session.begin() as session:
session.add(some_object)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/496551.html
標籤:Python 烧瓶 sqlalchemy
上一篇:我無法解決這個錯誤:jinja2.exceptions.UndefinedError:'user'isundefined
