How to Run a Flask Application

How to run a flask application?

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.

As of Flask 2.2, use the --app option 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. Use the --debug option to run in debug mode with the debugger and reloader.

$ flask --app sample --debug run

Prior to Flask 2.2, the FLASK_APP and FLASK_ENV=development environment variables were used instead. FLASK_APP and FLASK_DEBUG=1 can still be used in place of the CLI options above.

$ 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().

Run flask app with python instead of flask run

Insert the call to create_app at the end of init.py:

if __name__ == '__main__':
create_app().run(host='0.0.0.0', port=5000, debug=True)

The if statement avoid calling the app many times. It can only be called directly. Flask default host is 127.0.0.1 (localhost). Use 0.0.0.0 at production for better traffic monitoring. Default port is also 5000, so it's up to you to include. For better readability, you should explicit it.

Then call it

python webapp/init.py

How do I run a Flask application directly in the browser?

Try this:

import webbrowser

from flask import Flask
app = Flask(__name__)

#your staff
@app.route("/")
def hello():
return("Hello World!")

def open_browser():
webbrowser.open_new('http://127.0.0.1:5000/')

if __name__ == "__main__":
# the command you want
open_browser()
app.run(port=5000)

How to excecute code after Flask `app.run()` statement (run a Flask app and a function in parallel, execute code while Flask server is running)

You can do what you want by using multithreading:

from flask import Flask
import threading
import time

app = Flask(__name__)

@app.route("/")
def hello_world():
return "Hello, World!"

def run_app():
app.run(debug=False, threaded=True)

def while_function():
i = 0
while i < 20:
time.sleep(1)
print(i)
i += 1

if __name__ == "__main__":
first_thread = threading.Thread(target=run_app)
second_thread = threading.Thread(target=while_function)
first_thread.start()
second_thread.start()

Output:

 * Serving Flask app "app"
* Environment: production
* Debug mode: off
* Running on [...] (Press CTRL+C to quit)
0
1
2
3
4
5
6
7
8
[...]

The idea is simple:

  • create 2 functions, one to run the app and an other to execute the wile loop,
  • and then execute each function in a seperate thread, making them run in parallel

You can do this with multiprocessing instead of multithreading too:

The (main) differences here is that the functions will run on different CPUs and in memory spaces.

from flask import Flask
from multiprocessing import Process
import time

# Helper function to easly parallelize multiple functions
def parallelize_functions(*functions):
processes = []
for function in functions:
p = Process(target=function)
p.start()
processes.append(p)
for p in processes:
p.join()

# The function that will run in parallel with the Flask app
def while_function():
i = 0
while i < 20:
time.sleep(1)
print(i)
i += 1

app = Flask(__name__)

@app.route("/")
def hello_world():
return "Hello, World!"

def run_app():
app.run(debug=False)

if __name__ == '__main__':
parallelize_functions(while_function, run_app)

If you want to use before_first_request proposed by @Triet Doan: you will have to pass the while function as an argument of before_first_request like this:

from flask import Flask
import time

app = Flask(__name__)

def while_function(arg):
i = 0
while i < 5:
time.sleep(1)
print(i)
i += 1

@app.before_first_request(while_function)
@app.route("/")
def index():
print("index is running!")
return "Hello world"

if __name__ == "__main__":
app.run()

In this setup, the while function will be executed, and, when it will be finished, your app will run, but I don't think that was what you were asking for?

Run flask application with uWSGI

Your code under if __name__ == "__main__": is not executed because uwsgi does not run your script like python app.py. Instead it imports the module specified in wsgi-file and looks for an object specified as callable (app in our case). You can test it by using the following script:

from flask import Flask

app = Flask(__name__)

print(__name__)
if __name__ == '__main__':
app.run()

If you run it with python ./flask_app.py then the output will be

$ python ./flask_app.py
__main__
* Serving Flask app 'app' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

(notice __main__ - it means we're running the script). However if you run it with uwsgi the __name__ will be app (it will be the name of your file, so app in my case):

$ uwsgi --http 127.0.0.1:5000 --module app:app 
...
*** Operational MODE: single process ***
app
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x7fb2d0c067b0 pid: 46794 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 46794, cores: 1)

Similar output will be if you run your app with FLASK_APP=app flask run - it does not execute script, it just imports it and uses app object from it.

So, in order to initialize database you should either move your db initialization out of if __name__ == "__main__":

from flask import Flask

app = Flask(__name__)

class DB:
def init(self):
self.data = 'Hello, World'

db = DB()

@app.route("/")
def hello_world():
return db.data

db.init()

if __name__ == '__main__':
app.run()

Or add a before_first_request handler:

# replace db.init() with 
@app.before_first_request
def init_db():
db.init()

Notice the difference between them - if you put db.init() as a top-level statement it will be executed once you load app.py. If you register a before_first_request callback it will be executed once first request arrives to your application. Pick the one that works best for you.



Related Topics



Leave a reply



Submit