I just started learning flask and I am stuck at setting up Flask. I don't know how to setup environment variable. Whenever I use the Flask run command, I encounter the following. I did a lot of google searches to setup environment variable on Windows but I am unable to find and somemtime not able to understand the solution. How to do this ? How to get the "app.py" or "wsgi.py" ? Please help.
command : flask run
Error message : Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.
You need to actually run it from your Windows command line, NOT the built in command line for something like Visual Studio Code. Run those commands from your windows command line, in the proper directory, and everything should work.
The reason this creates problems - Visual Studio Code creates a Powershell environment for your command line. You could use the recommended $env:FLASK_APP = "your_app.py" from within the VSC environment and that will work too.
A bit late but I hope this helps others!!!
A step-wise solution is provided below:
Go to the folder where you have placed your flask app (on the command line)
Create a virtual environment as using the command (
$ py -m venv env
) here 'venv' is the short form of the virtual environment and 'env' at the end represents the name of the environment which you want (I have named it as env). Thereafter you can see at from the file explorer that a folder named 'env' is created in the folder stated at point #1 above.Enter the following command (
$env\Scripts\activate
) by pressing enter this will turn on your virtual environmentThereafter, enter the following command (
$set FLASK_APP=<your app name>.py
)Enter the following command (
$flask run
)you need to provide an application environment. So Flask needs to know, the
.py
file to run. Try to run that commandwhere
application.py
- name of your Flask app in my case it is application.py.after that
The
set
command works but to setup the environment, you need to make sure that you are in the right directory where the file is located. For example, if my application ishello_world.py
and it is located at thevenv\hello\hello_world.py
, you need to make sure that you are in the right directory before setting upset FLASK_APP=hello_world.py
this is for windows but in another OS, you need to useexport
insteadset
I don't think the 'flask run' command is the one which causes the error here. I got the same message error and the problem came from the fact I copied/pasted the
set FLASK_APP
and$env: FLASK_APP
commands as written in the documentation. I had to add spaces before and after '>' or '=', and then everything worked.Example: this command didn't work
'C:\path\to\app>set FLASK_APP=hello.py'
, but this one did'C:\path\to\app > set FLASK_APP = hello.py'
.Maybe it's the same problem you have?