views:

116

answers:

3

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?

+5  A: 

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
Mark B
OK, it's not that hard. :) But I do like the memcache option.
marienbad
+2  A: 

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

Kousha
+3  A: 

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')
jhs
I would have thought that the performance advantage is negligible in this situation (when we're only storing a few strings), but the get/set code is much more elegant than my answer.
Mark B
You are right, for an individual value the performance is negligible. If you are doing 20 or more gets per query then it might add up since (IIRC) fetch by key is about 100ms but fetch by property filter is about 200ms.
jhs