【问题标题】:"RuntimeError: working outside of application context" for config module配置模块的“RuntimeError:在应用程序上下文之外工作”
【发布时间】:2016-08-13 04:22:46
【问题描述】:

我有一个从我的主文件调用的 config.py 模块,它有各种 app.configs 用于 jinja2filters 和我正在使用的一些其他插件:

config.py 的摘录:

from flask import current_app as app  
#imports go here

def function1:
    print("hello")

app.config['PROPERTY_1'] = 'configgoeshere'

#jinja2 functions and configs would go here like
app.jinja_env.filters['datetime'] = datetimeformat

从 index.py 调用:

from flask import Flask, flash, render_template, jsonify, request, json, request, redirect, url_for, Response, send_from_directory

app = Flask(__name__)
app.config['DEBUG'] = False

app.config.from_object('config') #config file

############################################################################################################################
# MAIN ROUTES
############################################################################################################################
# The route for the homepage
@app.route('/')
def index():

返回错误:

RuntimeError: working outside of application context

更新 我现在正在尝试传递应用程序上下文,这里是 index.py:

from flask import Flask, flash, render_template, jsonify, request, json, request, redirect, url_for, Response, send_from_directory
import time, datetime, os, urllib, urllib2, urlparse, requests, json, string
from urllib2 import Request, urlopen, URLError, HTTPError, urlparse

app = Flask(__name__)
app.config['DEBUG'] = False

app.config.from_object('config')


############################################################################################################################
# MAIN ROUTES
############################################################################################################################
# The route for the homepage
@app.route('/')
def index():

这是更新后的 config.py 摘录:

from index import app
#imports go here

def function1:
    print("hello")

app.config['PROPERTY_1'] = 'configgoeshere'

#jinja2 functions and configs would go here like
app.jinja_env.filters['datetime'] = datetimeformat

返回的错误是:

$ python index.py
Traceback (most recent call last):
  File "index.py", line 8, in <module>
    app.config.from_object('config')
  File "C:\Python27\lib\site-packages\flask\config.py", line 162, in from_object
    obj = import_string(obj)
  File "C:\Python27\lib\site-packages\werkzeug\utils.py", line 418, in import_string
    __import__(import_name)
  File "C:\Users\****\Desktop\*****\config.py", line 1, in <module>
    from index import app
  File "C:\Users\***\Desktop\*****\index.py", line 17, in <module>
    @app.route('/')
  File "C:\Python27\lib\site-packages\werkzeug\local.py", line 343, in __getattr__
    return getattr(self._get_current_object(), name)
  File "C:\Python27\lib\site-packages\werkzeug\local.py", line 302, in _get_current_object
    return self.__local()
  File "C:\Python27\lib\site-packages\flask\globals.py", line 34, in _find_app
    raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context

注意 - config.py 内的第 162 行没有代码,就像错误提示的那样

【问题讨论】:

    标签: python flask jinja2


    【解决方案1】:

    查看Flask对Application Contexts的解释。

    在您的config.py 文件中,from flask import current_app as app 使得对app.config['PROPERTY_1'] = 'configgoeshere' 的调用实际上尝试在current_app 上设置配置,尽管在请求进入之前默认情况下没有应用程序上下文(因此错误)。由于该调用不在函数内,因此它会在其他任何事情(如请求)发生之前立即执行。

    我建议在索引中的 app 实例而不是 current_app 上进行配置。

    【讨论】:

    • 我真的很想将它保存在一个单独的文件中,因为它在我的主文件中添加了太多行。有没有办法可以将应用程序上下文从索引“传递”到配置文件?我已经研究过像 __ init __.py 或烧瓶蓝图这样的解决方案,但它们似乎有点过分了
    • config.py 中,您可以从index 导入app 而不是current_app 并在那里设置配置。
    • 我已将 app.config.from_object('config') 添加到 index.py 并将 from index import app 添加到 config.py 但仍然收到错误消息 RuntimeError: working outside of application context ... 有什么想法吗?
    • 您是否删除了from flask import current_app as app?我运行代码没有问题,除非您没有显示代码。建议更新问题或询问其他问题,因为 cmets 部分似乎不是最好的地方。
    • 晚了四年,但这件事发生在我身上。这似乎很简单,但我只是一遍又一遍地得到同样的错误。 @24x7 的答案是什么?
    【解决方案2】:

    我最终使用了 karin 所描述的内容。

    index.py

    from __future__ import print_function # For printing output to CMD
    import sys
    
    from flask import Flask, flash, render_template, jsonify, request, json, request, redirect, url_for, Response, send_from_directory
    import os, urllib, urllib2, urlparse, requests, json, string
    from urllib2 import Request, urlopen, URLError, HTTPError, urlparse
    
    app = Flask(__name__)
    
    from config import * 
    // ... rest of code for main file (like routes and stuff) below
    

    config.py

    from flask import Flask, current_app
    
    app = Flask(__name__)
    
    with app.app_context():
        // code goes here ...
        // in this case, I'm configuring various services like API's and jinja2
    
    

    【讨论】:

      猜你喜欢
      • 2015-10-05
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 2021-02-06
      • 1970-01-01
      相关资源
      最近更新 更多