我想使用“ flask”命令从终端运行一些命令,但是它不起作用。
以下是我的项目结构-
FlaskUserAuthentication
├── FlaskUserAuthentication
│ ├── API
│ │ ├── __init__.py
│ │ ├── db_models.py
│ │ └── routes.py
│ ├── Site
│ │ ├── __init__.py
│ │ ├── routes.py
│ │ ├── static
│ │ │ └── form_style.css
│ │ └── templates
│ │ └── Site
│ │ ├── base_layout.html
│ │ ├── index.html
│ │ ├── logout.html
│ │ ├── profile.html
│ │ ├── signin.html
│ │ └── signup.html
│ ├── __init__.py
│ └── commands.py
├── run.py
└── venv
在flask run
命令运行该应用程序时,我确定我的环境变量设置正确。但是,当我尝试使用flask-cli命令之类的
flask create_db
我明白了,Error: No such command "create_db".
以下是我的FlaskUserAuthentication/commands.py
文件-
from FlaskUserAuthentication import app, db
from FlaskUserAuthentication.API.db_models import Group, Member, Project, Milestone
@app.cli.command('create_db')
def createDatabase():
db.create_all()
print('***** Datebase created ****')
#....some more commands
和FlaskUserAuthentication/__init__.py
模块(在其中启动Flask应用实例的模块)-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'justasamplekey'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
from FlaskUserAuthentication.API.routes import api
from FlaskUserAuthentication.Site.routes import site
app.register_blueprint(api)
app.register_blueprint(site)
答案 0 :(得分:0)
问题是command.py
模块未被应用识别。我尝试过的解决方案是在commands
模块中启动一个蓝图,然后在启动__init__.py
实例的app
模块中,向其注册相应的蓝图。因此,更新后的commands.py
-
from FlaskUserAuthentication import db
from flask import Blueprint
from FlaskUserAuthentication.API.db_models import Group, Member, Project, Milestone
@cmd = Blueprint('db', __name__) #created a Blueprint for this module
@cmd.cli.command('create_db') #rather than generating the cli command with app,
def createDatabase(): # used the blueprint, cmd
db.create_all()
print('***** Datebase created ****')
和更新的__init__.py
模块
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'justasamplekey'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
from FlaskUserAuthentication.API.routes import api
from FlaskUserAuthentication.Site.routes import site
from FlaskUserAuthentication.commands import cmd
app.register_blueprint(api)
app.register_blueprint(site)
app.register_blueprint(cmd) # registered the command module as blueprint
现在在(终端中)设置环境变量和开发服务器-
export FLASK_APP=FlaskUserAuthentication/__init__.py
export FLASK_DEBUG=1
之后,使用flask命令,例如-
flask db create_db
P.S .:现在是由于蓝图而不是flask create_db
,所以命令将是
flask db create_db
我需要意识到问题的根源,为此,我要感谢帖子的作者
Where should I implement flask custom commands (cli)
作者@ emont01对他的回复。