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

我正在尝试使用python bottle框架创建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)
最佳答案
您的代码的以下修订版似乎按预期工作:

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上执行以下命令并获得预期结果:

$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"}

转载注明原文:python:如何通过http put在mongo中存储数据 - 代码日志