我正在使用Bottle和MongoDB创建REST服务。问题是尝试插入文档时出现500错误代码。
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>Error: 500 Internal Server Error</title>
<style type="text/css">
html {background-color: #eee; font-family: sans;}
body {background-color: #fff; border: 1px solid #ddd;
padding: 15px; margin: 15px;}
pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;}
</style>
</head>
<body>
<h1>Error: 500 Internal Server Error</h1>
<p>Sorry, the requested URL <tt>'http://localhost:8080/create'</tt>
caused an error:</p>
<pre>Unhandled exception</pre>
</body>
</html>
cURL
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
事实是,即使得到500错误代码,我仍然能够成功插入文档。为什么会收到500错误代码?我一直在尝试为MongoDB和Bottle实施异常处理。不知道这就是为什么我要获取代码。如果没有,如何正确实施异常处理?我已经阅读了中止的内容,但是对此有麻烦。另外,当我注释掉return result
时,我得到200的响应代码,但是我想返回插入的文档的ID。谢谢
源代码:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from bson import json_util
import json
import bottle
from bottle import route, run, request, abort, post, error
import pymongo
from pymongo import MongoClient
import datetime as datetime
connection = MongoClient('localhost', 27017)
db = connection['city']
collection = db['inspections']
@route('/create', method='POST')
def insert_document():
try:
data = request.json
result = collection.insert_one(data).inserted_id
except Exception, e:
print ('EXCEPTION: ', e)
return result
if __name__ == '__main__':
run(host='localhost', port=8080)
更改
return result
to
return str(result)
或完全删除该行。