Skip to content

Instantly share code, notes, and snippets.

@physacco
Created March 23, 2013 12:01
Show Gist options
  • Save physacco/5227459 to your computer and use it in GitHub Desktop.
Save physacco/5227459 to your computer and use it in GitHub Desktop.
This demo implements a simple key-value storage server based on GAE DataStore.

Start dev server

~/src/google/appengine/dev_appserver.py .

Test from client

$ curl http://localhost:8080/cache
$ curl -X PUT -d 'this is foo' http://localhost:8080/cache/foo
$ curl http://localhost:8080/cache/foo
this is foo
$ curl -X PUT -d 'this is bar' http://localhost:8080/cache/bar
$ curl http://localhost:8080/cache/bar
this is bar
$ curl http://localhost:8080/cache
bar
foo
$ curl -X DELETE http://localhost:8080/cache/foo
$ curl http://localhost:8080/cache/foo
$ curl http://localhost:8080/cache
bar
$ curl -X DELETE http://localhost:8080/cache/bar
$ curl http://localhost:8080/cache
$ 
application: cache
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: cache.app
# encoding: utf-8
import webapp2 as webapp
from google.appengine.ext import db
class BigHash(db.Model):
val = db.BlobProperty()
@classmethod
def get(cls, key, default=None):
entity = cls.get_by_key_name(key)
if entity:
return entity.val
return default
@classmethod
def set(cls, key, val):
entity = cls(key_name=key, val=db.Blob(val))
entity.put()
return val
@classmethod
def delete(cls, key):
db.delete(db.Key.from_path('BigHash', key))
class CacheHandler(webapp.RequestHandler):
def get(self):
params = self.request.params
try:
# offset >= 0, default is 0
offset = max(0, int(params.get('offset')))
except TypeError, ValueError:
offset = 0
try:
# 1 <= limit <= 1000, default is 100
limit = min(1000, max(1, int(params.get('limit'))))
except TypeError, ValueError:
limit = 100
# __key__, key(): db.Key
# app() app name, e.g. u'dev~hello'
# id() entity id, may be None
# name() entity name, may be None
# kind() entity kind, u'BigHash'
# to_path() [unicode], e.g. [u'BigHash', u'foo']
gql = 'SELECT __key__ from BigHash ORDER BY __key__ ' + \
'LIMIT %d OFFSET %d' % (limit, offset)
keys = [str(key.name()) for key in db.GqlQuery(gql)]
body = '\n'.join(keys + [''])
self.response.content_type = 'text/plain'
self.response.out.write(body)
class CacheItemHandler(webapp.RequestHandler):
def get(self, key):
val = BigHash.get(key, '')
self.response.content_type = 'application/octet-stream'
self.response.charset = 'binary'
self.response.out.write(val)
def put(self, key):
val = self.request.body
BigHash.set(key, val)
self.response.status_int = 204
def delete(self, key):
BigHash.delete(key)
self.response.status_int = 204
Routes = [(r'^/cache/?$', CacheHandler),
(r'^/cache/([^\/]*)/?$', CacheItemHandler)]
app = webapp.WSGIApplication(Routes, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment