How to do transactions using on google cloud datastore using google-cloud-ndb library in python3

Viewed 599

Hi I am developing an application in python3 using the flask frame work that is going to run on appengine standard that uses cloud datastore for persistence

I want to perform transactions

so I tried the following i

@ndb.transactional()
def update_user(req_data):
    print("running for req")
    print(req_data)
    query = TestUser.query(ndb.AND(TestUser.age=="1"))
    with client.context():
        result = query.get()
        if result.name == "the one":
            print("not writing")
            return
        else:
            print(result.name+ " is not equal to 'the one'")
            print(result.name)
        result.name = req_data["name"]
        result.put()

    print("transaction ended")

@app.route('/test_req',methods=['POST'])
def test_req_handler():
    req_data = request.get_json()
    update_user(req_data)

    print(req_data)
    return "ok"

In the local development environment when I hit the handler /test_req I am getting the following error

\lib\site-packages\google\cloud\ndb\context.py", line 72, in get_context
    raise exceptions.ContextError()
google.cloud.ndb.exceptions.ContextError: No current context. NDB calls must be made in context established by google.cloud.ndb.Client.context.

when I remove the @ndb.transactional() decorator entities gets updated and there is no error

1 Answers
Related