python:如何通过http put在mongo中存储数据

时间:2012-10-08 19:23:13

标签: python mongodb rest bottle

我正在尝试使用python bottle framework

创建REST API应用程序

我希望能够通过HTTP PUT请求在mongodb中插入数据。

到目前为止,我可以使用HTTP GET从mongodb获得响应。

请帮我通过HTTP PUT在mongodb中插入数据。

JSON格式我必须按如下方式插入:

{"_id": "id_1", "key_1": "value_1"}

[我正在使用this extension来获取和发送http响应]

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)

1 个答案:

答案 0 :(得分:2)

以下修订版的代码似乎按预期工作:

import json

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()
    print(data)
    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.insert(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)

我有 MongoDB 运行并执行脚本,在localhost端口8080上启动服务器,然后在shell上执行以下命令并获得预期结果:< / p>

$ echo '{"_id": "id_1", "key_1": "value_1", "key_2": "value_2"}' | curl -X PUT -d @- http://localhost:8080/documents
$ curl http://localhost:8080/documents/id_1
{"_id": "id_1", "key_1": "value_1", "key_2": "value_2"}