w00
w00

Reputation: 26772

set namespace for all db operations

I'm trying to set the namespace for all DB operations for the Google App Engine in python, but i can't get it done.

Currently my code looks something like this:

""" Set Google namespace """
if user:
    namespace = thisUser.namespace
    namespace_manager.set_namespace(namespace)
""" End Google namespace """

#Then i have all sorts of classes:

class MainPage(BaseHandler):
    def get(self):
        #code with DB operations like get and put...

class MainPage2(BaseHandler):
    def get(self):
        #code with DB operations like get and put...

class MainPage3(BaseHandler):
    def get(self):
        #code with DB operations like get and put...

app = webapp2.WSGIApplication([ ... ], debug=True, config=webapp2_config)

The problem with this is, is that in the classes all DB operations are still done on the default namespace (so as if no namespace is set). Eventhough i set the namespace in the very top of my code.

When i print the variable "namespace", which i also set in the top of the code, then i do get to see the namespace that i wish to use.

But it looks like Google App Engine somewhere resets the namespace to empty before running the code in the classes.

So now i'm wondering if there's a good way to set the namespace once somewhere.

Currently i set it like this in all "def's":

class MainPage(BaseHandler):
    def get(self):
        namespace_manager.set_namespace(namespace)

        #code with DB operations like get and put...

class MainPage(BaseHandler):
    def get(self):
        namespace_manager.set_namespace(namespace)

        #code with DB operations like get and put...

etc...

It's just not a very elegant solution.

Upvotes: 0

Views: 131

Answers (3)

Tim Hoffman
Tim Hoffman

Reputation: 12986

You can use appconfig.py and define namespace_manager_default_namespace_for_request()

Have a read of https://developers.google.com/appengine/docs/python/multitenancy/multitenancy see the first section of "Setting the Current Namespace"

Upvotes: 1

sahid
sahid

Reputation: 2610

A good solution is to add a hook. Something like that should be works.

from google.appengine.api import apiproxy_stub_map

NAMESPACE_NAME = 'noname'
def namespace_call(service, call, request, response):
    if hasattr(request, 'set_name_space'):
        request.set_name_space(NAMESPACE_NAME)
apiproxy_stub_map.apiproxy.GetPreCallHooks().Append(
    'datastore-hooks', namespace_call, 'datastore_v3')

You can add it in your main.py or appengine_config.py. By this way the hook is configured during the loading of the instances and keeps his state.

Upvotes: 1

Shay Erlichmen
Shay Erlichmen

Reputation: 31928

You need to write a middleware that will intercept the request and will set the namespace according to your app logic.

Upvotes: 2

Related Questions