-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmongo.py
38 lines (31 loc) · 1003 Bytes
/
mongo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import json
import bottle
from bottle import route, run, request, abort
from pymongo import Connection
connection = Connection('localhost', 27017)
db = connection.mydatabase
@route('/documents', method='PUT')
def put_document():
data = request.body.readline()
if not data:
abort(400, 'No data received')
entity = json.loads(data)
if not entity.has_key('_id'):
abort(400, 'No _id specified')
try:
db['documents'].save(entity)
except ValidationError as ve:
abort(400, str(ve))
@route('/documents/:id', method='GET')
def get_document(id):
entity = db['documents'].find_one({'_id':id})
if not entity:
abort(404, 'No document with id %s' % id)
return entity
run(host='localhost', port=8080)
# Save
# http://localhost:8080/documents
# Now select PUT and enter the following data: {"_id": "doc1", "name": "Test Document 1"}
# Retrieve
# http://localhost:8080/documents/doc1
# {"_id": "doc1", "name": "Test Document 1"}