Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a flask application?

Tags:

python

flask

I want to know the correct way to start a flask application. The docs show two different commands:

$ flask -a sample run 

and

$ python3.4 sample.py  

produce the same result and run the application correctly.

What is the difference between the two and which should be used to run a Flask application?

like image 351
KarateKid Avatar asked Apr 26 '15 19:04

KarateKid


People also ask

How do I run a flask app?

To run the app outside of the VS Code debugger, use the following steps from a terminal: Set an environment variable for FLASK_APP . On Linux and macOS, use export set FLASK_APP=webapp ; on Windows use set FLASK_APP=webapp . Navigate into the hello_app folder, then launch the program using python -m flask run .

How do I run flask app in my browser?

To install flask, simply type in pip install flask in your computer terminal/command line. Once you have made sure flask is installed, simply run the hello.py script. Once you run the script, the website should now be up and running on your local machine, and it can be viewed by visiting localhost:5000 in your browser.


1 Answers

The flask command is a CLI for interacting with Flask apps. The docs describe how to use CLI commands and add custom commands. The flask run command is the preferred way to start the development server.

Never use this command to deploy publicly, use a production WSGI server such as Gunicorn, uWSGI, Waitress, or mod_wsgi.

Set the FLASK_APP environment variable to point the command at your app. It can point to an import name or file name. It will automatically detect an app instance or an app factory called create_app. Set FLASK_ENV=development to run with the debugger and reloader.

$ export FLASK_APP=sample $ export FLASK_ENV=development $ flask run 

On Windows CMD, use set instead of export.

> set FLASK_APP=sample 

For PowerShell, use $env:.

> $env:FLASK_APP = "sample" 

The python sample.py command runs a Python file and sets __name__ == "__main__". If the main block calls app.run(), it will run the development server. If you use an app factory, you could also instantiate an app instance at this point.

if __name__ == "__main__":     app = create_app()     app.run(debug=True) 

Both these commands ultimately start the Werkzeug development server, which as the name implies starts a simple HTTP server that should only be used during development. You should prefer using the flask run command over the app.run() method.

like image 159
davidism Avatar answered Oct 07 '22 23:10

davidism