使用 Python/PyMongo 和 REST API 更新 MongoDB 时遇到问题



您好,我在使用 Python REST API 时更新 MongoDB 文档时遇到问题。 以下是 Python 代码:

import json
import bottle
from bson import json_util
from bson.json_util import dumps
from pymongo import MongoClient
from bottle import route, run, request, abort
connection = MongoClient('localhost', 27017)
db = connection['city']
collection = db['inspections']
#Create 
@route('/create', method='POST')
def post_create():
data=json.load(request.body)
id=data["id"]
certificate_number=data["certificate_number"]   
business_name=data["business_name"]
date=data["date"]
result=data["result"]
sector=data["sector"]
result=collection.insert_one({'id': id, 'certificate_number': certificate_number, 'business_name' : business_name, 'date' : date, 'result' : result, 'sector' : sector}).inserted_id
return json.loads(json.dumps(result, indent=4, default=json_util.default))
#Update
@route('/update', method='GET')
def update():
id=request.query.id
result=request.query.result
myquery = {"id": "10011-2017-TEST" }
newvalues = { "$set": { "result" : result } }
collection.update(myquery, newvalues)

在我启动上面的 Python 代码后,这是我在终端中运行的两个查询:

#Create
curl -H "Content-Type: application/json" -X POST -d '{"id" : "10011-2017-TEST","certificate_number" : 9278833,"business_name" : "ACME TEST INC.","date" : "Feb 20 2017","result" : "No Violation Issued","sector" : "Test Retail Dealer - 101"}' http://localhost:8080/create
#Update
curl http://localhost:8080/update?id="10011-2017-TEST"&result="Violation Issued"

第一个 curl 命令完美运行。 但是,当我运行第二个 curl 更新命令时,我收到一个空的"结果"。

{
"_id" : ObjectId("5e48b39618882a084aa35b86"),
"sector" : "Test Retail Dealer - 101",
"certificate_number" : 9278833,
"result" : "",
"date" : "Feb 20 2017",
"business_name" : "ACME TEST INC.",
"id" : "10011-2017-TEST"
}

我需要将"结果"从"未发出违规"更改为"已发布违规"。我想我很接近,因为我知道第二个更新 curl 命令引用了正确的文档,但是,它没有正确更新"结果"。我怀疑python函数看不到查询的第二部分,导致空白更新。

axme100 是正确的,空格是你的问题。有几种方法可以解决不同的外壳引号/转义等,但最简单的可能是:

curl 'http://localhost:8080/update?id=10011-2017-TEST&result=Violation%20Issued'

每当查询字符串中有&时,请将整个内容放在单引号中,以防止 shell 在后台运行它。

最新更新