我想从当前的flask应用程序配置中获取route args默认值,但是我收到了这个错误。
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 473, in spawn_worker
worker.init_process()
File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 100, in init_process
self.wsgi = self.app.wsgi()
File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 115, in wsgi
self.callable = self.load()
File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 33, in load
return util.import_app(self.app_uri)
File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 362, in import_app
__import__(module)
File "/home/hamid/projects/bfl/develop.py", line 4, in <module>
application = create_app(DevelopmentConfig)
File "/home/hamid/projects/bfl/project/application.py", line 56, in create_app
configure_blueprints(app)
File "/home/hamid/projects/bfl/project/application.py", line 97, in configure_blueprints
bp = __import__('project.apps.%s' % blueprint_name, fromlist=['views'])
File "/home/hamid/projects/bfl/project/apps/store/views/__init__.py", line 6, in <module>
from .store import *
File "/home/hamid/projects/bfl/project/apps/store/views/store.py", line 193, in <module>
@mod.route('/<page>/', defaults={'per_page': current_app.config['PAGE_SIZE']})
File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/usr/local/lib/python2.7/dist-packages/flask/globals.py", line 34, in _find_app
raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context
这是我的示例代码:
@mod.route('/<page>/', defaults={'per_page': current_app.config['PAGE_SIZE']})
@mod.route('/<per_page>/<page>/')
@login_required
def index(per_page, page):
pagination_obj = Pagination(Store.objects(is_dealer=False), per_page, page)
return render('store/index.html', pagination=pagination_obj)
任何想法如何从当前应用程序配置中获取路径默认值?
答案 0 :(得分:2)
current_app只能访问"request context"中的“config”字典。
要在请求上下文之外访问配置值,您可以使用此自定义方法:
from . import app
def getConfig(key):
with app.app_context():
if key in current_app.config:
return current_app.config.get(key)
else:
raise Exception("Custom Message")
答案 1 :(得分:-1)
你的代码看起来不错。
由于在您拥有current_app.config['PAGE_SIZE']
的行中出现错误,您可以调试并确认此变量实际存在吗?
通过@mod
装饰器,我猜你正在使用蓝图。因此,current_app
可能不是您应用的名称,或者您尚未正确导入current_app
。或者,您还没有为您的app正确设置配置变量。
最后,在什么情况下你会收到这个错误?访问哪个URL?还是在测试环境中?
总之:错误可能不在你分享的代码中。