gpt4 book ai didi

python - Flask-pymongo 运行时错误 : Working outside of application context

转载 作者:太空宇宙 更新时间:2023-11-03 20:38:51 24 4
gpt4 key购买 nike

我正在编写一个程序,使用flask-pymongo根据id字段读取mongodb文档。但我遇到了错误,有人能告诉我哪里出错了吗?

代码:

from flask import Flask, make_response, jsonify
from flask_pymongo import PyMongo
from collections import OrderedDict
from bson import json_util
import json

app = Flask('__name__')
app.config['MONGO_DBNAME'] = 'db_name'
app.config['MONGO_URI'] = 'mongodb://192.168.55.24:27017/db_name'
mongo_connection = PyMongo(app)

@app.route('/')
def index(inp_id):
collection = mongo_connection.db.table_name
one_record = collection.find_one({'id': inp_id})
obj_str = json_util.dumps(one_record)
obj_dict = json.loads(obj_str, object_hook=OrderedDict)
return make_response(jsonify(obj_dict), 200)

if __name__ == '__main__':
index('5cd00a468b36db516b6d2f16') # I think this is where I'm going wrong

给我以下错误:

RuntimeError: Working outside of application context.

如果我直接在 inp_id 的位置传递 id 值,我会得到结果,但我正在尝试编写一个通用的结果。

最佳答案

Flask 有一个应用程序上下文,您可能需要使用 app.app_context() 才能使其工作。

The application context keeps track of the application-level data during a request, CLI command, or other activity. Rather than passing the application around to each function, the current_app and g proxies are accessed instead.

试试这个:

def index(inp_id):
with app.app_context():
collection = mongo_connection.db.table_name
one_record = collection.find_one({'id': inp_id})
obj_str = json_util.dumps(one_record)
obj_dict = json.loads(obj_str, object_hook=OrderedDict)
return make_response(jsonify(obj_dict), 200)

有关更多信息,请阅读 Flask Application context

关于python - Flask-pymongo 运行时错误 : Working outside of application context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56982395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com