from flask import Flask
from flask import render_template
from pymongo import MongoClient
import json
from bson import json_util
from bson.json_util import dum
app = Flask(__name__)
MONGODB_HOST = 'localhost'
MONGODB_PORT = 27017
DBS_NAME = 'donorschoose'
COLLECTION_NAME = 'projects'
FIELDS = {'school_state': True, 'resource_type': True, 'poverty_level': True, 'date_posted': True, 'total_donations': True, '_id': False}
@app.route('/')
def index():
return render_template("index.html")
@app.route("/donorschoose/projects")
def donorschoose_projects():
connection = MongoClient(MONGODB_HOST, MONGODB_PORT)
collection = connection[DBS_NAME][COLLECTION_NAME]
projects = collection.find(projection=FIELDS)
json_projects = []
for project in projects:
json_projects.append(project)
json_projects = json.dumps(json_projects, default=json_util.default)
connection.close()
return json_projects
if __name__ == "__main__":
app.run(host='0.0.0.0',port=5000,debug=True)
这是我关注的教程:http://adilmoujahid.com/posts/2015/01/interactive-data-visualization-d3-dc-python-mongodb/
运行服务器时出现错误。
回溯(最近一次呼叫最后一次):文件" app.py",第3行,in <模块>
来自pymongo import MongoClient File" /home/olalkeith/Documents/Github/myproject/venv/local/lib/python2.7/site-packages/pymongo/ init .py",
第83行,在< module>中 来自pymongo.collection import ReturnDocument File" /home/olalkeith/Documents/Github/myproject/venv/local/lib/python2.7/site-packages/pymongo/collection.py",
第27行,在< module>中 来自bson.raw_bson导入RawBSONDocument文件" /home/olalkeith/Documents/Github/myproject/venv/local/lib/python2.7/site-packages/bson/raw_bson.py",
第20行,在< module>中 来自bson import _UNPACK_INT,_iterate_elements ImportError:无法导入名称_UNPACK_INT
答案 0 :(得分:19)
我遇到了同样的问题。尝试删除bson模块并重新安装pymongo。看到这个答案: