4

我正在尝试使用 python 瓶框架创建一个 REST API 应用程序

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

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

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

我必须插入的 JSON 格式如下:

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

[我正在使用这个扩展来获取和放置 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)
4

1 回答 1

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运行并执行脚本,在localhostport上启动服务器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"}
于 2012-10-08T23:38:26.750 回答