app.shell_context_processor装饰器未将函数注册为Shell上下文函数

时间:2018-07-14 10:54:11

标签: shell flask

我在microblog.py文件夹中的~/Programing/Rasa/myflaskapp/app文件中创建了以下函数。它创建一个Shell上下文,该上下文将数据库实例和模型添加到Shell会话中:

from app import app, db
from app.models import User, Post

@app.shell_context_processor
def make_shell_context():
    return {'db': db, 'User': User, 'Post': Post}

app.shell_context_processor解码器将该函数注册为Shell上下文函数。但是在执行flask shell命令时,在~/Programing/Rasa/myflaskapp/中,它不会调用此函数,并且不会按预期将其返回的元素记录在shell会话中。

所以我明白了:

(MyFlaskAppEnv) mike@mike-thinks:~/Programing/Rasa/myflaskapp$ flask shell
Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux
App: app [production]
Instance: /home/mike/Programing/Rasa/myflaskapp/instance
>>> db
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'db' is not defined

而不是:

(venv) $ flask shell
>>> db
<SQLAlchemy engine=sqlite:////Users/migu7781/Documents/dev/flask/microblog2/app.db>

更新:我试图检查该功能是否保存正确

但似乎不是:

>>> print(app.shell_context_processors[0]())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
IndexError: list index out of range

我仅通过导入microblog.pyapp来更改db

from app import app, db

@app.shell_context_processor
def make_shell_context():
    return {'db': db}

我试图将microblog.py放置在app文件夹中,甚至将其删除,它始终是相同的错误:我无法将函数注册为shell上下文函数。在Flask上下文中致电>>> app的同时,我确实有一个答案。

3 个答案:

答案 0 :(得分:2)

我通过设置FLASK_APP环境变量告诉Flask如何导入应用程序:

export FLASK_APP=microblog.py

似乎成功了!

答案 1 :(得分:1)

如果您使用 CMD ,则:CREATE OR REPLACE PROCEDURE GET_ITEMS_PROC( p_CODE VARCHAR2, p_CODE_SUPPLIER VARCHAR2, p_SELECT1 VARCHAR2, p_SELECT2 VARCHAR2, p_SELECT3 VARCHAR2, p_SELECT4 VARCHAR2, p_SELECT5 VARCHAR2, p_SELECT6 VARCHAR2, p_SELECT7 VARCHAR2, p_SELECT8 VARCHAR2, p_SELECT9 VARCHAR2, p_SELECT10 VARCHAR2, cur OUT sys_refcursor) AS BEGIN OPEN cur FOR SELECT * FROM ITEMS WHERE (p_CODE IS NULL OR CODE = p_CODE) AND ( p_CODE_SUPPLIER IS NULL OR SUP_CODE = p_CODE_SUPPLIER) AND ( p_SELECT1 IS NULL OR SELECT1 = p_SELECT1) AND ( p_SELECT2 IS NULL OR SELECT2 = p_SELECT2) AND ( p_SELECT3 IS NULL OR SELECT3 = p_SELECT3) AND ( p_SELECT4 IS NULL OR SELECT4 = p_SELECT4) AND ( p_SELECT5 IS NULL OR SELECT5 = p_SELECT5) AND ( p_SELECT6 IS NULL OR SELECT6 = p_SELECT6) AND ( p_SELECT7 IS NULL OR SELECT7 = p_SELECT7) AND ( p_SELECT8 IS NULL OR SELECT8 = p_SELECT8) AND ( p_SELECT9 IS NULL OR SELECT9 = p_SELECT9) AND ( p_SELECT10 IS NULL OR SELECT10 = p_SELECT10); END;

如果您使用 PowerShell ,则:set FLASK_APP=microblog.py

如果您使用 Bash(Linux),则:$env:FLASK_APP = '.\microblog.py'

问题出在变量export FLASK_APP=microblog.py

答案 2 :(得分:0)

我有同样的问题。我不得不重新导出FLASK_APP变量。