0

この sqlite3 コードがプログラムの本体にあるときに完全に動作するようになり、それだと思いましたが、さらにコードを書いて、これが月に 1 回 (月の最初の日に) 実行されるようにしました。コードは正常に動作しますが、テーブル エントリが発生するとsqlite3 error UNIQUE constraint failed: currentMonthStocks.id、下部に毎月の呼び出しを書いたときに、コードを本体から関数に移動しました。それが原因であるかどうかはわかりません.

私はこれについて半日検索し、一意のキーなどを調べましたが、問題は、テーブル名が UNIQUE 制約エラーをスローしていることにあるようです。これは、テーブルが存在するため非常に奇​​妙です。その名前の 1 つのテーブル。他のすべてのコードは正常に動作するはずです。INSERT INTO を INSERT または IGNORE INTO に変更しようとしたところ、for ループが実行されましたが、何も挿入されませんでした。再確認しましたが、テーブルは空です。

def get_symbols_at_month_start() -> None:
"""Function inserts a list of symbols to trade every month into the currentMonthStocks table in database.db.
This is called once at the start of the month, deletes the current symbols and adds the new ones.
:return: None."""

print('running get symbols function')
# curl for marketsmith stocks:
url = "https://marketsmith.investors.com/mstool/api/tool/list-table"

payload = "{...}"
headers = {...}

response = requests.request("POST", url, headers=headers, data=payload)
symbols = response.json()['content']['allInstrumentRows']
this_months_symbols = []
for symbol in symbols:
    this_months_symbols.append(symbol['Symbol'])

# DATABASE
try:
    conn = sqlite3.connect('database.db')
    c = conn.cursor()
    print("Database Connected")

    # c.execute("""CREATE TABLE currentMonthStocks (
    #             id INT PRIMARY KEY,
    #             symbol TEXT,
    #             month INT)""")
    # print("DB created successfully")

    time_now = datetime.datetime.now()  # get current time for the int conversion below
    this_month_int = time_now.month  # get the current month and set it to an int
    db_row_id = 1  # set the first row number

    for i in range(len(this_months_symbols)):
        c.execute("""INSERT INTO currentMonthStocks
                   (id, symbol, month)
                   VALUES (?, ?, ?)""", (db_row_id, this_months_symbols[i], this_month_int))
        db_row_id += 1
        print("one more entry")
    print("symbols successfully populated into db")

    conn.commit()  # commits the current transaction.
    # c.close()  # closes the connection to the db.

except sqlite3.Error as e:
    print("sqlite3 error", e)

finally:
    if conn:
        conn.close()
        print("Database Closed")

# set the timing of the get_symbols_at_month_start() code
today = datetime.datetime.now()
nextMonth = (today.replace(day=1) + datetime.timedelta(days=32)).replace(day=1)  # get first day of next month
diffMins = ((nextMonth - today).total_seconds()) / 60.0  # get difference in minutes

scheduler = BackgroundScheduler()
# scheduler.add_job(func=get_symbols_at_month_start, trigger='interval', minutes=diffMins)
scheduler.add_job(func=get_symbols_at_month_start, trigger='interval', seconds=8)
scheduler.start()
4

1 に答える 1