最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Flask-PyMongo出错:RuntimeError Working outside of application context

Flask crifan 6219浏览 0评论

折腾:

【已解决】Flask中连接远程MongoDB数据库的gridfs并返回查询到的文件数据

期间,用代码:

<code>from flask_pymongo import PyMongo

mongo = PyMongo(app)
log.info("mongo=%s", mongo)
mongoDb = mongo.db
</code>

结果出错:

<code>[2018-04-18 18:00:06,039 INFO testRestApi.py:56 &lt;module&gt;] mongo=&lt;flask_pymongo.PyMongo object at 0x106c6f860&gt;
Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1668, in &lt;module&gt;
    main()
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1662, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1072, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/Users/crifan/dev/dev_root/company/naturling/projects/robotDemo/testRestApi.py", line 57, in &lt;module&gt;
    mongoDb = mongo.db
  File "/Users/crifan/.virtualenvs/robotDemo-HXjMJQEQ/lib/python3.6/site-packages/flask_pymongo/__init__.py", line 306, in db
    if self.config_prefix not in current_app.extensions['pymongo']:
  File "/Users/crifan/.virtualenvs/robotDemo-HXjMJQEQ/lib/python3.6/site-packages/werkzeug/local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/Users/crifan/.virtualenvs/robotDemo-HXjMJQEQ/lib/python3.6/site-packages/werkzeug/local.py", line 306, in _get_current_object
    return self.__local()
  File "/Users/crifan/.virtualenvs/robotDemo-HXjMJQEQ/lib/python3.6/site-packages/flask/globals.py", line 51, in _find_app
    raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in a way.  To solve
this set up an application context with app.app_context().  See the
documentation for more information.

Process finished with exit code 1

</code>

Flask-PyMongo RuntimeError Working outside of application context

The Application Context — Flask Documentation (0.12)

Flask中有两种state状态

  • application setup state== application context

    • app初始化时

    • 没有任何特殊的proxy处理

  • request handling state

    • context local objects

    • 用app_context()获取当前上下文

Flask支持一个进程中有多个应用application

用current_app获取当前的app

还是没有完全搞懂,此处为何出现这个错误

Understanding Contexts in Flask

flask 0.10 mongo working outside of application context | CODE Q&A [English]

Flask runtime error with database initialization.:flask

RuntimeError: working outside of application context · Issue #63 · mattupstate/flask-mail

RuntimeError: working outside of application context · Issue #16 · viniciuschiele/flask-apscheduler

python – Flask MongoDB error: “working outside of application context” – Stack Overflow

python – flask 0.10 mongo working outside of application context – Stack Overflow

还是不太懂

去找找标准初始化做法:

flask-pymongo initialization

flask-pymongo/__init__.py at master · dcrosta/flask-pymongo

python – Flask/PyMongo – Initialize pymongo at the top of the app – Stack Overflow

去试试:

with app.app_context():

然后就可以了:

再去试试,移动到request的代码中:

<code>class RobotAPI(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('q', type=str, help="input question")
        # play a Christmas song

        parsedArgs = parser.parse_args()
        log.info(parsedArgs)

        # with app.app_context():
        mongoDb = mongo.db
        log.info("mongoDb=%s", mongoDb)
</code>

结果是可以的:

【总结】

此处,没有完全搞懂,只知道是属于application context的问题

改为:

<code>mongo = PyMongo(app)
with app.app_context():
    mongoDb = mongo.db
</code>

即可。

或者把代码移动到某个api中:

<code>
class RobotAPI(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('q', type=str, help="input question")
        # play a Christmas song

        parsedArgs = parser.parse_args()
        log.info(parsedArgs)

        # with app.app_context():
        mongoDb = mongo.db
        log.info("mongoDb=%s", mongoDb)

api.add_resource(RobotAPI, '/qa', endpoint='qa')


if __name__ == "__main__":
    # app.debug = True
    app.run()
</code>

也可以。

转载请注明:在路上 » 【已解决】Flask-PyMongo出错:RuntimeError Working outside of application context

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
88 queries in 0.199 seconds, using 22.18MB memory