I have an appengine app that works with python2.7 and I want to migrate to python3.9. I started by making call to google ndb cloud inside my appengine app. I am using python3.9 and django as a web framwork. This is my code:
from django.shortcuts import render,redirect
from google.cloud import ndb
class Book(ndb.Model):
title = ndb.StringProperty()
client = ndb.Client()
def get_books():
with client.context():
books = Book.query()
return books
def main(request):
return HttpResponse(get_books())
And this is the traceback
File "/Users/hizan/Desktop/venvdjango/lib/python3.9/site-packages/google/cloud/ndb/query.py" in wrapper
1213. context = context_module.get_context()
File "/Users/hizan/Desktop/venvdjango/lib/python3.9/site-packages/google/cloud/ndb/context.py" in get_context
118. raise exceptions.ContextError()
Exception Type: ContextError at /
Exception Value: No current context. NDB calls must be made in context established by google.cloud.ndb.Client.context.
Instead of defining a context in each function/method where you're using NDB, you should create a middleware so that the context is automatically taken care of.
See example from Google for Django