I would like to run a transaction operation in Google App Engine using google-cloud-ndb. I deployed this app.
Here is my code.
# -*- coding: utf-8 -*-
from flask import Flask
from google.cloud import ndb
import time
app = Flask(__name__)
class Book(ndb.Model):
hoge = ndb.IntegerProperty()
class Book2(ndb.Model):
hoge = ndb.IntegerProperty()
@ndb.transactional()
def test1():
ent = ndb.Key(Book, "a").get()
print("after get: %s", ent)
ent.hoge = ent.hoge + 1
ent.put()
print("after put: %s", ent)
print("wakeup")
@ndb.transactional()
def test2():
ent = ndb.Key(Book2, "a").get()
print("after get: %s", ent)
ent.hoge = ent.hoge + 1
ent.put()
print("after put: %s", ent)
time.sleep(10)
print("wakeup")
@app.route('/piyo')
def piyo():
print("before transaction")
try:
with ndb.Client().context():
print("enter transaction")
test1()
except Exception as e:
print(e)
print("completed")
return '', 204
@app.route('/foo')
def foo():
print("before transaction")
try:
with ndb.Client().context():
print("enter transaction")
test2()
except Exception as e:
print(e)
print("completed")
return '', 204
if __name__ == "__main__":
app.run()
The attempt to run this will unexpected result for me. Datastore dont conflict for different entity-groups(As far as i know). But they seem to be conflicting and wait completing the preceding operation.
Why does this work?
Logging:
2020-01-30 21:23:18.878 GET 204 116B 10.3s /foo
2020-01-30 21:23:18.882 before transaction
2020-01-30 21:23:18.887 enter transaction
2020-01-30 21:23:19.061 after get: %s Book2(key=Key('Book2', 'a'), hoge=33)
2020-01-30 21:23:19.062 after put: %s Book2(key=Key('Book2', 'a'), hoge=34)
★ sleep
2020-01-30 21:23:29.062 wakeup
2020-01-30 21:23:29.130 completed
2020-01-30 21:23:22.699 GET 204 116B 6.6s Android /piyo
★ confrict and wait completing "Book2" transaction
2020-01-30 21:23:29.132 before transaction
2020-01-30 21:23:29.136 enter transaction
2020-01-30 21:23:29.221 after get: %s Book(key=Key('Book', 'a'), hoge=30)
2020-01-30 21:23:29.221 after put: %s Book(key=Key('Book', 'a'), hoge=31)
2020-01-30 21:23:29.221 wakeup
2020-01-30 21:23:29.285 completed
I'm using Python 3.7. I have these tools installed in my environment:
Flask==1.0.3
google-cloud-ndb==0.2.2
Please help me with my problem. Thank you before