Domanda

What is the best way to store one editable string in Python Google App Engine? I tried to use NDB, with a single route to create, read, and update the string. But this does not seem to work:

class Storage(ndb.Model):
    content  = ndb.StringProperty()

class CreateReadUpdate(webapp2.RequestHandler):
    def get(self):
        entity = ndb.Key(Storage, 'name').get()
        self.response.out.write(entity.content)
    def post(self):
        content = json.loads(self.request.body).get('content')
        entity = ndb.Key(Storage, 'name').get()
        if not entity:
            entity = Storage(content='')
        entity.content = content
        entity.put()

Not sure how to debug in this environment. So I have to ask, what is wrong here? I just want the simplest App Engine CRUD possible.

È stato utile?

Soluzione

Start debugging with logging on dev and on production.

Simple example:

import logging

...

logging.info(entity.property)

Your problem is that you are not providing a key_name/id for the entity you are saving (if everything else is fine), thus when you try to display it you get nothing.

Change you save logic to this:

def post(self):
    content = json.loads(self.request.body).get('content')
    entity = ndb.Key(Storage, 'name').get()
    if not entity:
        entity = Storage(id='name', content='') # see here
    entity.content = content
    entity.put()

or as an alternative:

def post(self):
    content = json.loads(self.request.body).get('content')
    entity = Storage.get_or_insert('name')
    entity.content = content
    entity.put()

If you need an example check "How to use GAE with AJAX" from a previous answer and this is the repo

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top