Skip to content

Instantly share code, notes, and snippets.

@gbishop
Created February 12, 2010 19:58
Show Gist options
  • Save gbishop/302912 to your computer and use it in GitHub Desktop.
Save gbishop/302912 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Explorer + JsonRestStore</title>
<link rel="stylesheet" type="text/css" href=
"http://ajax.googleapis.com/ajax/libs/dojo/1.4.0/dojo/resources/dojo.css"/>
<link rel="stylesheet" type="text/css" href=
"http://ajax.googleapis.com/ajax/libs/dojo/1.4.0/dijit/themes/tundra/tundra.css"/>
<link rel="stylesheet" type="text/css" href=
"http://ajax.googleapis.com/ajax/libs/dojo/1.4.0/dojox/grid/resources/Grid.css"/>
<link rel="stylesheet" type="text/css" href=
"http://ajax.googleapis.com/ajax/libs/dojo/1.4.0/dojox/grid/resources/tundraGrid.css"/>
<style type="text/css">
#gridNode {
width: 200px;
height: 200px;
}
</style>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/dojo/1.4.1/dojo/dojo.xd.js"
baseUrl='./'
djConfig="parseOnLoad:true">
</script>
<script type="text/javascript">
dojo.require("dojox.data.StoreExplorer");
dojo.require("dojox.data.JsonRestStore");
dojo.require("dojo.parser");
dojo.ready(function(){
exp.grid.startup();
});
</script>
</head>
<body class="tundra">
<div dojoType="dojox.data.JsonRestStore" target="/data" idAttribute="id" jsId="store"></div>
<div dojoType="dojox.data.StoreExplorer" store="store" jsId='exp'
style="height:500px;width:100%;border:1px solid black"></div>
</body>
</html>
'''A data server with use with dojo'''
import tornado.httpserver
import tornado.ioloop
import tornado.web
import os
import json
import re
import random
import string
# fake up some data to supply
class DB(object):
choices = 'foo bar baz fee faa boo'.split()
data = {}
for i in range(100): # 100 fake items
data[str(i)] = { 'id': i, 'label': random.choice(choices) }
nextIndex = 100
# return a page to kick things off
class MainHandler(tornado.web.RequestHandler):
def get(self, fname):
bytes = file(fname, 'r').read()
self.write(bytes)
# handle requests for data
class DataHandler(tornado.web.RequestHandler):
def get(self, id):
'''Handle requests for items and queries'''
if id:
# request for a single item, how to generate these from JS?
# should this return an array?
s = json.dumps(DB.data[id])
self.set_header('Content-length', len(s))
self.set_header('Content-type', 'application/json')
self.write(s)
return
result = DB.data.values()
# check for a sorting request
s = re.compile(r'sort\(([+-])(\w+)\)').search(self.request.query)
if s:
col = s.group(2)
dir = s.group(1)
result.sort(key=lambda item: item[col], reverse=dir=='-')
# check for a query
for key,val in self.request.arguments.iteritems():
q = val[0].replace('*', '.*').replace('?', '.?')
result = [ item for item in result if re.match(q, item.get(key,'')) ]
Nitems = len(result)
# see how much we are to send
r = re.compile(r'items=(\d+)-(\d+)').match(self.request.headers.get('Range', ''))
if r:
start = int(r.group(1))
stop = int(r.group(2))
result = result[start:stop+1]
else:
start = 0
stop = len(result)
# send the result
self.set_header('Content-range', 'items %d-%d/%d' % (start,stop,Nitems))
s = json.dumps(result)
self.set_header('Content-length', len(s))
self.set_header('Content-type', 'application/json')
self.write(s)
def put(self, id):
'''update an item after an edit, no response?'''
item = json.loads(self.request.body)
DB.data[id] = item
def post(self, id):
'''Create a new item and return the single item not an array'''
item = json.loads(self.request.body)
id = DB.nextIndex
DB.nextIndex += 1
item['id'] = id
DB.data[str(id)] = item
self.set_header('Location', '/%d' % id)
s = json.dumps(item)
self.set_header('Content-length', len(s))
self.set_header('Content-type', 'application/json')
self.write(s)
def delete(self, id):
'''Delete an item, what should I return?'''
del DB.data[id];
settings = {
"static_path": os.path.join(os.path.dirname(__file__), "static"),
'debug': True,
}
application = tornado.web.Application([
(r"/(\w+\.html)", MainHandler),
# why do we need this optional undefined string, explorer seems to be adding it
(r"/data/(?:undefined)?(\d*)", DataHandler),
], **settings)
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment