Python transactions help needed for master-detail table insertion
I am trying to implement Python Flask rest API. I have two tables (master-detail) in order to insert values from a parsed response of another rest API.
Here are my master-detail tables;
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
); """
And here is my functions to insert into tables separately.
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()
**In order to provide data consistency, is there a way to use transaction? I am new to Python, I would be glad if you can guide me. **
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
python-2.7 sqlite3 transactions python-requests
add a comment |
I am trying to implement Python Flask rest API. I have two tables (master-detail) in order to insert values from a parsed response of another rest API.
Here are my master-detail tables;
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
); """
And here is my functions to insert into tables separately.
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()
**In order to provide data consistency, is there a way to use transaction? I am new to Python, I would be glad if you can guide me. **
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
python-2.7 sqlite3 transactions python-requests
add a comment |
I am trying to implement Python Flask rest API. I have two tables (master-detail) in order to insert values from a parsed response of another rest API.
Here are my master-detail tables;
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
); """
And here is my functions to insert into tables separately.
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()
**In order to provide data consistency, is there a way to use transaction? I am new to Python, I would be glad if you can guide me. **
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
python-2.7 sqlite3 transactions python-requests
I am trying to implement Python Flask rest API. I have two tables (master-detail) in order to insert values from a parsed response of another rest API.
Here are my master-detail tables;
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
); """
And here is my functions to insert into tables separately.
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()
**In order to provide data consistency, is there a way to use transaction? I am new to Python, I would be glad if you can guide me. **
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
python-2.7 sqlite3 transactions python-requests
python-2.7 sqlite3 transactions python-requests
edited Nov 24 '18 at 12:59
raysefo
asked Nov 23 '18 at 9:51
rayseforaysefo
238
238
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
SQLite has "atomic" transactions if you use BEGIN TRANSACTION
. Probably in confirmation
function, call a BEGIN TRANSACTION
query before add_purchase... calls and then execute a commit
or rollback
depending on success or failure. You may also find this doc on busy timeout salient.
Should I remove commits 'con.commit()' inside of purchase calls?
– raysefo
Nov 24 '18 at 6:29
1
Yes, sorry I missed that. If you want to treat the two inserts as one transaction, they need to be "wrapped" as one transaction.
– DinoCoderSaurus
Nov 24 '18 at 12:36
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53444258%2fpython-transactions-help-needed-for-master-detail-table-insertion%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
SQLite has "atomic" transactions if you use BEGIN TRANSACTION
. Probably in confirmation
function, call a BEGIN TRANSACTION
query before add_purchase... calls and then execute a commit
or rollback
depending on success or failure. You may also find this doc on busy timeout salient.
Should I remove commits 'con.commit()' inside of purchase calls?
– raysefo
Nov 24 '18 at 6:29
1
Yes, sorry I missed that. If you want to treat the two inserts as one transaction, they need to be "wrapped" as one transaction.
– DinoCoderSaurus
Nov 24 '18 at 12:36
add a comment |
SQLite has "atomic" transactions if you use BEGIN TRANSACTION
. Probably in confirmation
function, call a BEGIN TRANSACTION
query before add_purchase... calls and then execute a commit
or rollback
depending on success or failure. You may also find this doc on busy timeout salient.
Should I remove commits 'con.commit()' inside of purchase calls?
– raysefo
Nov 24 '18 at 6:29
1
Yes, sorry I missed that. If you want to treat the two inserts as one transaction, they need to be "wrapped" as one transaction.
– DinoCoderSaurus
Nov 24 '18 at 12:36
add a comment |
SQLite has "atomic" transactions if you use BEGIN TRANSACTION
. Probably in confirmation
function, call a BEGIN TRANSACTION
query before add_purchase... calls and then execute a commit
or rollback
depending on success or failure. You may also find this doc on busy timeout salient.
SQLite has "atomic" transactions if you use BEGIN TRANSACTION
. Probably in confirmation
function, call a BEGIN TRANSACTION
query before add_purchase... calls and then execute a commit
or rollback
depending on success or failure. You may also find this doc on busy timeout salient.
edited Nov 24 '18 at 12:37
answered Nov 24 '18 at 1:35
DinoCoderSaurusDinoCoderSaurus
72158
72158
Should I remove commits 'con.commit()' inside of purchase calls?
– raysefo
Nov 24 '18 at 6:29
1
Yes, sorry I missed that. If you want to treat the two inserts as one transaction, they need to be "wrapped" as one transaction.
– DinoCoderSaurus
Nov 24 '18 at 12:36
add a comment |
Should I remove commits 'con.commit()' inside of purchase calls?
– raysefo
Nov 24 '18 at 6:29
1
Yes, sorry I missed that. If you want to treat the two inserts as one transaction, they need to be "wrapped" as one transaction.
– DinoCoderSaurus
Nov 24 '18 at 12:36
Should I remove commits 'con.commit()' inside of purchase calls?
– raysefo
Nov 24 '18 at 6:29
Should I remove commits 'con.commit()' inside of purchase calls?
– raysefo
Nov 24 '18 at 6:29
1
1
Yes, sorry I missed that. If you want to treat the two inserts as one transaction, they need to be "wrapped" as one transaction.
– DinoCoderSaurus
Nov 24 '18 at 12:36
Yes, sorry I missed that. If you want to treat the two inserts as one transaction, they need to be "wrapped" as one transaction.
– DinoCoderSaurus
Nov 24 '18 at 12:36
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53444258%2fpython-transactions-help-needed-for-master-detail-table-insertion%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown