我正在使用 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 -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 實現異常處理。不確定這是否是我獲取代碼的原因。如果沒有,我該如何正確實現異常處理?我已經閱讀了 abort 但我遇到了麻煩。另外,當我注釋掉時return result,我得到一個 200 響應代碼,但我想返回插入的文檔的 id。謝謝源代碼:#!/usr/bin/python# -*- coding: utf-8 -*-from bson import json_utilimport jsonimport bottlefrom bottle import route, run, request, abort, post, errorimport pymongofrom pymongo import MongoClientimport datetime as datetimeconnection = 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 resultif __name__ == '__main__': run(host='localhost', port=8080)
添加回答
舉報
0/150
提交
取消