NiklasR
NiklasR

Reputation: 523

AttributeError when using memcache.gets()

I am trying to use memcached with Google App Engine. I import the library using

from google.appengine.api import memcache

and then call it using

posts = memcache.gets("posts")

Then I get the following error: AttributeError: 'module' object has no attribute 'gets'

I have looked through the Google App Engine documentation regarding memcache, but I can't find any examples using memcache.gets(). Memcache.get() seems to be used the way I call gets above.

Upvotes: 1

Views: 973

Answers (2)

P_S
P_S

Reputation: 345

If you actually do need to compare and set, a very good explanation can be found here:

The Client object is required because the gets() operation actually squirrels away some hidden information that is used by the subsequent cas() operation. Because the memcache functions are stateless (meaning they don't alter any global values), these operations are only available as methods on the Client object, not as functions in the memcache module. (Apart from these two, the methods on the Client object are exactly the same as the functions in the module, as you can tell by comparing the documentation.)

The solution would be to use the class:

client = memcache.Client()
posts = client.gets("posts")
...
client.cas("posts", "new_value")

Although, of course, you would need more than that for cas to be useful.

Upvotes: 0

Alex Martelli
Alex Martelli

Reputation: 881555

gets is a method of the memcache client object, not a module-level function of memcache. The module-level functions are quite simple, stateless, and synchronous; using the client object, you can do more advanced stuff, if you have to, as documented at https://cloud.google.com/appengine/docs/python/memcache/clientclass .

Specifically, per the docs at https://cloud.google.com/appengine/docs/python/memcache/clientclass#Client_gets , "You use" gets "rather than get if you want to avoid conditions in which two or more callers are trying to modify the same key value at the same time, leading to undesired overwrites." since gets also gets (and stashes in the client object) the cas_id which lets you use the cas (compare-and-set) call (you don't have to explicitly handle the cas_id yourself).

Since it doesn't seem you're attempting a compare-and-set operation, I would recommend using the simpler module-level function get, rather than instantiating a client object and using its instance method gets.

Upvotes: 2

Related Questions