我努力學習Python,和mongodb的燒瓶中,用米格爾格林貝格非常優秀的博客誰在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 = ":[email protected]"
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)
讚賞任何幫助,頁[0]是,只是沒有工作,我得到一個
類型錯誤代碼:物件( '527e17c538320915e9893f17')不是JSON序列化
在此先感謝
順便說一句,不能推薦米格爾的超級教程足以作爲一個地方開始構建的東西
這是晚,但你可以看看https://github.com/Bleezworld/ flask_skeleton,它是一個mongodb/Flask網站框架,其中包含一些使用示例(用戶登錄等) – Thomas