我正在尝试实现Python Flask rest API。我有两个表(主从),以便从另一个rest API的已解析响应中插入值。
这是我的主从表;
sql_create_purchase_confirmation_response_table = """ CREATE TABLE IF NOT EXISTS purchase_confirmation (
id integer PRIMARY KEY,
responseDatetime DATETIME NOT NULL,
applicationCode text NOT NULL,
version text NOT NULL,
referenceId text NOT NULL,
paymentId text NOT NULL,
productCode text NOT NULL,
quantity integer NOT NULL,
currency text NOT NULL,
unitPrice integer NOT NULL,
totalPrice integer NOT NULL,
merchantProductCode text NOT NULL,
signature text NOT NULL,
purchaseStatusCode text NOT NULL,
purchaseStatusDate DATETIME NOT NULL
); """
sql_create_purchase_confirmation_detail_response_table = """ CREATE TABLE IF NOT EXISTS purchase_confirmation_detail (
referenceId text NOT NULL,
serials text NULL,
pins text NULL
); """
这是我要分别插入表中的函数。
def add_purchase_confirmation_response(database_file, response):
query = "INSERT INTO purchase_confirmation (responseDatetime, applicationCode, version, referenceId," \
"paymentId, productCode, quantity, currency, unitPrice, totalPrice, merchantProductCode," \
"purchaseStatusCode, purchaseStatusDate, signature) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
con = ''
try:
with sql.connect(database_file, isolation_level=None) as con:
con.execute('pragma journal_mode=wal')
cur = con.cursor()
cur.execute(query, [str(datetime.now()),
response['applicationCode'], response['version'], response['referenceId'],
response['paymentId'], response['productCode'], response['quantity'],
response['currency'], response['unitPrice'], response['totalPrice'],
response['merchantProductCode'], response['purchaseStatusCode'],
response['purchaseStatusDate'], response['signature']])
con.commit()
except sql as e:
con.rollback()
print e.message
except:
print("Unexpected error:", sys.exc_info()[0])
raise
finally:
con.close()
def add_purchase_confirmation_detail_response(database_file, response):
query = "INSERT INTO purchase_confirmation ( referenceId," \
"serials, pins) VALUES (?, ?, ?)"
con = ''
try:
pins = ''
# parse response coupons
for item in response['coupons']:
for itemS in item['serials']:
serials = itemS
for itemP in item['pins']:
pins = pins + itemP + ','
print serials.rstrip(',')
print pins.rstrip(',')
# insert into table here
with sql.connect(database_file, isolation_level=None) as con:
con.execute('pragma journal_mode=wal')
cur = con.cursor()
cur.execute(query, [response['referenceId'], serials, pins])
con.commit()
pins = ''
except sql as e:
con.rollback()
print e.message
except:
print("Unexpected error:", sys.exc_info()[0])
raise
finally:
con.close()
**为了提供数据一致性,是否有使用事务的方法?我是Python的新手,如果您能指导我,我将非常高兴。 **
def confirmation():
try:
uri = 'https://teststore.com/purchaseconfirmation'
r = requests.post(uri, data=request_params_confirmation)
add_purchase_confirmation_response('test.db', r.json())
add_purchase_confirmation_detail_response('test.db', r.json())
return jsonify(r.text)
except Exception as e:
return e.message
except:
print("Unexpected error:", sys.exc_info()[0])
raise
答案 0 :(得分:1)
如果使用BEGIN TRANSACTION
,则SQLite具有“原子”事务。可能是在confirmation
函数中,在add_purchase ...调用之前先调用BEGIN TRANSACTION
查询,然后根据成功或失败执行commit
或rollback
。您可能还会在busy timeout上找到此文档。