我在使用 Mongodb 和 Python (Flask) 时遇到了一些问题。
我有这个 api.py 文件,我希望所有请求和响应都在 JSON 中,所以我这样实现。
#
# Imports
#
from datetime import datetime
from flask import Flask
from flask import g
from flask import jsonify
from flask import json
from flask import request
from flask import url_for
from flask import redirect
from flask import render_template
from flask import make_response
import pymongo
from pymongo import Connection
from bson import BSON
from bson import json_util
#
# App Create
#
app = Flask(__name__)
app.config.from_object(__name__)
#
# Database
#
# connect
connection = Connection()
db = connection['storage']
units = db['storage']
#
# Request Mixins
#
@app.before_request
def before_request():
#before
return
@app.teardown_request
def teardown_request(exception):
#after
return
#
# Functions
#
def isInt(n):
try:
num = int(n)
return True
except ValueError:
return False
def isFloat(n):
try:
num = float(n)
return True
except ValueError:
return False
def jd(obj):
return json.dumps(obj, default=json_util.default)
def jl(obj):
return json.loads(obj, object_hook=json_util.object_hook)
#
# Response
#
def response(data={}, code=200):
resp = {
"code" : code,
"data" : data
}
response = make_response(jd(resp))
response.headers['Status Code'] = resp['code']
response.headers['Content-Type'] = "application/json"
return response
#
# REST API calls
#
# index
@app.route('/')
def index():
return response()
# search
@app.route('/search', methods=['POST'])
def search():
return response()
# add
@app.route('/add', methods=['POST'])
def add():
unit = request.json
_id = units.save(unit)
return response(_id)
# get
@app.route('/show', methods=['GET'])
def show():
import pdb; pdb.set_trace();
return response(db.units.find())
#
# Error handing
#
@app.errorhandler(404)
def page_not_found(error):
return response({},404)
#
# Run it!
#
if __name__ == '__main__':
app.debug = True
app.run()
这里的问题是来自 mongo 的 json 编码数据。看来我已经能够通过将 request.json 作为保存字典来“破解”添加路由,所以这很好......问题是 /show。此代码不起作用...当我进行一些日志记录时,我得到
TypeError: <pymongo.cursor.Cursor object at 0x109bda150> is not JSON serializable
有任何想法吗?我也欢迎对其余代码提出任何建议,但 JSON 让我很生气。
提前致谢!