简体   繁体   English

Flask 应用程序出现“找不到 flask 应用程序。.....FLASK_APP 环境变量”错误 Flask 迁移

[英]Flask app getting error of "could not locate flask application. .....FLASK_APP environment variable" for Flask Migrate

I have a file db_table.py that looks like:我有一个文件db_table.py看起来像:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password@localhost/mydb'

db = SQLAlchemy(app)
migrate = Migrate(app, db)
.....db tables....

When I try to run:当我尝试运行时:

flask db init

I get:我得到:

Error: Could not locate Flask application. You did not provide the FLASK_APP environment variable.

I tried first manually setting FLASK_APP var, by doing set FLASK_APP=app.py then running flask db init again, but that didn't resolve the issue.我首先尝试通过执行set FLASK_APP=app.py然后再次运行flask db init手动设置FLASK_APP var,但这并没有解决问题。

The flask command line argument needs to know what module to locate the current Flask app instance in. flask命令行参数需要知道在哪个模块中定位当前Flask应用程序实例。

Set FLASK_APP as an environment variable:FLASK_APP设置为环境变量:

export FLASK_APP=db_table.py

before running your flask command-line app.在运行您的flask命令行应用程序之前。

See the Command Line Interface documentation :请参阅命令行界面文档

For the flask script to work, an application needs to be discovered.要使 Flask 脚本工作,需要发现一个应用程序。 This is achieved by exporting the FLASK_APP environment variable.这是通过导出FLASK_APP环境变量来实现的。 It can be either set to an import path or to a filename of a Python module that contains a Flask application.它可以设置为导入路径或包含 Flask 应用程序的 Python 模块的文件名。

You can also set the variable per command by setting it on the same command line:您还可以通过在同一命令行上设置每个命令来设置变量:

FLASK_APP=db_table.py flask db init

You can refer to this documentation to learn how to set environment variables in Flask.您可以参考此文档了解如何在 Flask 中设置环境变量。

Unix Bash (Linux, Mac, etc.): Unix Bash(Linux、Mac 等):

$ export FLASK_APP=hello
$ flask run

Windows CMD: Windows CMD:

> set FLASK_APP=hello
> flask run

Windows PowerShell: Windows PowerShell:

> $env:FLASK_APP = "hello"
> flask run

Some problem will can happen if you use DispatcherMiddleware (werkzeug.wsgi).如果您使用 DispatcherMiddleware (werkzeug.wsgi),可能会发生一些问题。 Change return object from app_dispatch to app without app_dispatch for migrate time.对于迁移时间,将返回对象从 app_dispatch 更改为没有 app_dispatch 的 app。

This is a rare case, I hope someone helps...这种情况很少见,希望有人帮助...

In VS code editor, click on Run and Debug.在 VS 代码编辑器中,单击运行和调试。 Select Flask debugger and type your file name. Select Flask 调试器并键入您的文件名。 This worked for me and hope it works for you too.这对我有用,希望它也对你有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM