Simplest way to store a value in Google App Engine

2019-04-10 10:15发布

I'm lazy! And I just want to store one single string value. That's all! Can I jump over any kind of Modeling and just store a value?

3条回答
smile是对你的礼貌
2楼-- · 2019-04-10 10:52

Depending on how long you want to store the information, you can also use memcache:

Import:

from google.appengine.api import memcache

All you need to know to get and set data:

memcache.set("key", value)
value = memcache.get("key")

If your data needs long-term persistance, then you need to use the backend datastore. It is recommended to use both memcache and the datastore for your data, since the memcache can be flushed at any time. For short-term, ephemeral persistance, memcache does the trick.

More info here: http://code.google.com/appengine/docs/python/memcache/usingmemcache.html

查看更多
beautiful°
3楼-- · 2019-04-10 11:12

Not as far as I know: the DataStore is the only storage available on App Engine. However, it's not a lot of code, even if you are lazy. ;)

Make sure you import the db module:

from google.appengine.ext import db

Then just store a key/value pair (you can then use this model to store any other miscellaneous strings you might add as well):

class MyData(db.Model):
    myKey = db.StringProperty(required=True)
    myValue = db.StringProperty(required=True)

data = MyData(myKey="Title", myStringValue="My App Engine Application")
data.put()

You can get it again with:

db.Query(Entry).filter("myKey=", "Title").get().myStringValue
查看更多
孤傲高冷的网名
4楼-- · 2019-04-10 11:16

Mark B's solution is good however you will get better performance if your "key" is the proper key of the entity. That way you halve the scans through the data required. (In SQL terms, you will be selecting by primary key.)

class Global(db.Model):
    val = db.StringProperty()

    @classmethod
    def get(cls, key):
        return cls.get_by_key_name(key).val

    @classmethod
    def set(cls, key, val):
        entity = cls(key_name=key, val=val)
        entity.put()
        return val

Now you can get and set using the class method.

    Global.set('foo', 'this is the value for foo')
    print "The value of foo is: %r" % Global.get('foo')
查看更多
登录 后发表回答