Skip to content

Instantly share code, notes, and snippets.

@dreid
Created February 26, 2013 20:02
Show Gist options
  • Save dreid/5041647 to your computer and use it in GitHub Desktop.
Save dreid/5041647 to your computer and use it in GitHub Desktop.
import json
from klein import Klein
app = Klein()
_collections = {}
@app.route('/collections/')
def collections(request):
request.setHeader('Content-Type', 'application/json')
return json.dumps(_collections)
@app.route('/collections/<string:colname>/', methods=['PUT'])
def save_collection(request, colname):
request.setHeader('Content-Type', 'application/json')
body = json.loads(request.content.read())
_collections[colname] = body
return json.dumps({'success': True})
@app.route('/collections/<string:colname>/', methods=['DELETE'])
def delete_collection(request, colname):
del _collections[colname]
return json.dumps({'success': True})
@app.route('/collections/<string:colname>/', methods=['GET'])
def get_collection(request, colname):
request.setHeader('Content-Type', 'application/json')
return json.dumps(_collections.get(colname))
@app.route('/collections/<string:colname>/<string:itemname>', methods=['GET', 'PUT'])
def get_item(request, colname, itemname):
return json.dumps(_collections.get(colname, {}).get(itemname))
if __name__ == '__main__':
print app.url_map
app.run('localhost', 8080)
Map([<Rule '/collections/' -> collections>,
<Rule '/collections/<colname>/<itemname>' (PUT, HEAD, GET) -> get_item>,
<Rule '/collections/<colname>/<__rest__>' (PUT) -> save_collection_branch>,
<Rule '/collections/<colname>/<__rest__>' (DELETE) -> delete_collection_branch>,
<Rule '/collections/<colname>/<__rest__>' (HEAD, GET) -> get_collection_branch>,
<Rule '/collections/<colname>/' (PUT) -> save_collection>,
<Rule '/collections/<colname>/' (DELETE) -> delete_collection>,
<Rule '/collections/<colname>/' (HEAD, GET) -> get_collection>,
<Rule '/collections/<__rest__>' -> collections_branch>])
(klein)thomasina dreid:~> curl -XPUT -d '{"bar": "baz"}' http://localhost:8080/collections/foo/
{"success": true}
thomasina dreid:~> curl -XPUT -d '{"bar": "baz"}' http://localhost:8080/collections/foo
{"foo": {"bar": "baz"}}
(klein)thomasina dreid:~> curl -XDELETE http://localhost:8080/collections/foo/bar
{"success": true}
(klein)thomasina dreid:~> curl http://localhost:8080/collections/
{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment