我正在尝试学习python,mongodb和flask,并使用了Miguel Grinberg的VERY EXCELLENT博客,他在blog.miguelgrinberg.com上提供了很多教程
我有一个小型的RESTful服务器,可以正常工作,但现在想从mongo而不是mysql中提取内容
我可以使用下面的代码提取一条mongo记录,但正在努力使其呈现。
我在下面的代码中使用箭头来显示我在哪里挣扎,缺乏经验。任何想法将不胜感激。
#!flask/bin/python from flask import Flask, jsonify, abort, make_response, url_for from pymongo import MongoClient # connect to mongo database hosted on AWS # the script expects the host name to be in /etc/hosts file ''' Set up global variables here ''' mongo_server = "mongo_api" mongo_port = "27017" mongo_user = "admin" mongo_passwd = ":mysecretpassword@" connect_string = "mongodb://"+ mongo_user + mongo_passwd + mongo_server + ":" + mongo_port app = Flask(__name__) @app.errorhandler(404) def not_found(error): return make_response(jsonify( { 'error': 'Notfound' } ), 404) def make_public_page(page): new_page = {} for field in page: if field == 'id': new_page['uri'] = url_for('get_page', page_id = page['id'], _external = True) else: new_page[field] = page[field] return new_page @app.route('/api/v1.0/pages/<int:page_id>',methods = ['GET']) def get_page(page_id): ''' Can connect otherwise exit with message ''' try: connection = MongoClient(connect_string) # equal to > show dbs except: exit("Error: Unable to connect to the database") # exit with an error ''' connect to database and pull back collections ''' db = connection.test_database # equal to > use test_database pages = db.pages page = pages.find_one({"id": int(page_id)}) <------ this pulls back a document if page == None: <---- if a null set comes back then this works great abort(404) return jsonify( { 'page' : make_public_page(page[0])} ) <- error says its not json if __name__ == '__main__': app.run(debug = True)
感谢任何帮助,page [0]是无法正常工作的代码,我得到了
TypeError:ObjectId(‘527e17c538320915e9893f17’)不可序列化JSON
提前致谢
首先find_one将返回单个字典,或者如果集合中没有匹配的元素,则返回None。所以我认为这page[0]等同于获取密钥的页面字典的价值0
find_one
page[0]
0
如果返回的文档包含ObjectId,_id则不能简单地使用,jsonify因为ObjectIdJSON不可序列化。你可以使用如下形式:
ObjectId
_id
jsonify
ObjectIdJSON
jsonify({ 'page': make_public_page({k:v for k, v in page.items() if k != '_id'}))
或者你可以_id通过致电简单地删除page.pop('_id')
page.pop('_id')
你也可以使用bson.json_util。它包含用于在BSON和JSON之间进行转换的工具。
bson.json_util
from flask import Response from bson import json_util
然后,jsonify用类似以下内容替换:
return Response( json_util.dumps({'page' : make_public_page(page)}), mimetype='application/json' )
编辑
如果你想用简短,肮脏的方式来解决问题,可以这样进行:
from bson import json_util, ObjectId import json #Lets create some dummy document to prove it will work page = {'foo': ObjectId(), 'bar': [ObjectId(), ObjectId()]} #Dump loaded BSON to valid JSON string and reload it as dict page_sanitized = json.loads(json_util.dumps(page))