Skip to content

Instantly share code, notes, and snippets.

@jamescasbon
Created June 17, 2011 10:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamescasbon/1031207 to your computer and use it in GitHub Desktop.
Save jamescasbon/1031207 to your computer and use it in GitHub Desktop.
REST handlers for backbone.js based on cyclone
# hmm no imports ;)
class BaseHandler(cyclone.web.RequestHandler):
def get_current_user(self):
return self.get_secure_cookie("user")
class LoginHandler(BaseHandler):
def get(self):
err = self.get_argument("e", None)
self.finish("""
<html><body><form action="/auth/login" method="post">
username: <input type="text" name="u"><br>
password: <input type="password" name="p"><br>
<input type="submit" value="sign in"><br>
%s
</body></html>
""" % (err == "invalid" and "invalid username or password" or ""))
@defer.inlineCallbacks
def post(self):
u, p = self.get_argument("u"), self.get_argument("p")
password = hashlib.md5(p).hexdigest()
try:
user = yield self.settings.user_db.find_one({"user":u, "password":password}, fields=["user"])
except Exception, e:
log.err("mongo can't find_one({u:%s, p:%s}): %s" % (u, password, e))
raise cyclone.web.HTTPError(503)
if user:
user["_id"] = str(user["_id"])
print 'setting user', user
self.set_secure_cookie("user", cyclone.escape.json_encode(user))
self.redirect("/")
else:
self.redirect("/auth/login?e=invalid")
class LogoutHandler(BaseHandler):
@cyclone.web.authenticated
def get(self):
self.clear_cookie("user")
self.redirect("/")
class CellsHandler(BaseHandler):
@cyclone.web.authenticated
@defer.inlineCallbacks
def get(self, nbid):
""" fetch a list of cells """
result = yield self.settings.cell_db.find({'nbid': nbid})
self.write(json.dumps(result))
self.finish()
@cyclone.web.authenticated
@defer.inlineCallbacks
def post(self, nbid):
""" create a cell """
cell = json.loads(self.request.body)
cell['id'] = str(uuid.uuid1())
cell['nbid'] = nbid
result = yield self.settings.cell_db.save(cell)
self.write(json.dumps(result))
class CellHandler(BaseHandler):
@cyclone.web.authenticated
@defer.inlineCallbacks
def get(self, nbid, cid):
""" fetch a cell """
result = yield self.settings.cell_db.find_one({'nbid': nbid, 'id': cid})
if not result:
raise cyclone.web.HTTPError(404)
self.write(json.dumps(result))
self.finish()
@cyclone.web.authenticated
@defer.inlineCallbacks
def put(self, nbid, cid):
""" update a cell """
print self.request.body
cell = json.loads(self.request.body)
result = yield self.settings.cell_db.save(cell)
self.write("ok\n")
@cyclone.web.authenticated
@defer.inlineCallbacks
def delete(self, nbid, cid):
""" update a cell """
result = yield self.settings.cell_db.find_one({'nbid': nbid, 'id': cid})
result = yield self.settings.cell_db.remove(result)
self.write("ok\n")
class WebMongo(cyclone.web.Application):
def __init__(self):
handlers = [
(r"/auth/login", LoginHandler),
(r"/auth/logout", LogoutHandler),
(r"/notebooks/([\w]+)/cells", CellsHandler),
(r"/notebooks/([\w]+)/cells/([\w-]+)", CellHandler),
]
mongo = txmongo.lazyMongoConnectionPool()
settings = dict(
cell_db= mongo.test.cells,
notebook_db= mongo.test.notebooks,
)
cyclone.web.Application.__init__(self, handlers, **settings)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment