1
我在單個頁面中檢索文檔的單個測試,我知道在單個頁面中做不正確;但它只是爲了理解所有這些工作,如純腳本,而不是爲了安靜。上下文中的瓶上下文,對於jsonfy,全部在單個頁面中
我的問題是當我使用:
print (jsonify({'result' : output}))
我得到這個錯誤:當我通過
print (output)
替換該行
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
沒有的錯誤及具有文件。
我如何指定jsonify的上下文?在另一個環境中?因爲我已經使用
with app.app_context():
下面的代碼:
from flask import Flask
from flask import g
from flask import jsonify
from flask import request
from flask_pymongo import PyMongo
from flask import make_response
from bson.objectid import ObjectId
from flask import current_app
import sys
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'restdb'
app.config['MONGO_URI'] = 'mongodb://localhost:27017/crm1'
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error':'Notfound' }),404)
with app.app_context():
mongo = PyMongo(app)
star = mongo.db.accounts
output = []
for s in star.find():
output.append({'id': str(s['_id']) ,'firstname' : s['firstname'], 'lastname' : s['lastname']})
print (jsonify({'result' : output}))
#print (output)
if __name__ == '__main__':
app.run(debug=True)
我已經解決了與current_app.test_request_context(),但它有reques(jsonify)沒有任何意義的工作,因爲沒有要求。 .. – stackdave
請更正您的響應,對於Python 3需要使用圓括號:print(json.dumps(輸出)) – stackdave
您正在嘗試一種黑客攻擊。看到http://stackoverflow.com/questions/7907596/json-dumps-vs-flask-jsonify –