如何在 python 中使用 SQLalchemy 在数据库中有新条目时 运行 脚本?

How to run a script when ever there is a new entry in database using SQLalchemy in python?

我是 SQL Alchemy 的新手,每当向 table 添加新条目时,我需要一种方法来 运行 脚本。我目前正在使用以下方法来完成任务,但我相信必须有更有效的方法。

我的项目使用 python 2,数据库使用 MS SQL。

假设我的 table 是 carData 并且我为来自网站的汽车详细信息添加了一个新行。新的汽车数据被添加到 carData。我的代码工作如下

class CarData:
    <fields for table class>

with session_scope() as session:
    car_data = session.query(CarData)
    reference_df = pd.read_sql_query(car_data.statement, car_data.session.bind)

while True:
    with session_scope() as session:
        new_df = pd.read_sql_query(car_data.statement, car_data.session.bind)
        if len(new_df) > len(reference_df):
            print "New Car details added"
            <code to get the id of new row added>
            <run script>
            reference_df = new_df
    sleep(10)

以上当然是我正在使用的代码的一个更简单的版本,但我的想法是有一个参考点,然后每 10 秒检查一次是否有新条目。然而,即使在使用 session_scope() 几天后我也看到了连接问题,因为这个脚本应该无限期地 运行。

是否有更好的方法来了解已添加新行、获取新行的 ID 和 运行 所需的脚本?

我认为您描述的错误是数据库的连接问题,例如临时网络问题

OperationalError: TCP Provider: Error code 0x68

所以你需要做的就是通过错误处理来解决这个问题!

try:
    new_df = pd.read_sql_query(car_data.statement, car_data.session.bind)
except:
    print("Problem with query, will try again shortly")