Flask at first run: Do not use the development server in a production environment
For deploying an application to production, one option is to use Waitress, a production WSGI server.
Here is an example of using waitress
in the code.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<h1>Hello!</h1>"
if __name__ == "__main__":
from waitress import serve
serve(app, host="0.0.0.0", port=8080)
Running the application:
$ python hello.py
Waitress also provides a command line utility waitress-serve
. To use that, you can modify the code to the following:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<h1>Hello!</h1>"
def create_app():
return app
Then we can use waitress-serve
as the following:
waitress-serve --port=8080 --call hello:create_app
And BTW, 8080 is the default port.
To validate the deployment, open a separate window:
% curl localhost:8080
<h1>Hello!</h1>%
Or directly in your browser http://localhost:8080/.
Other alternatives to deploy your app include Gunicorn and uWSGI. For more details, please refer to the flask deploy doc.
Unless you tell the development server that it's running in development mode, it will assume you're using it in production and warn you not to. The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure.
Enable development mode by setting the FLASK_ENV
environment variable to development
.
$ export FLASK_APP=example
$ export FLASK_ENV=development
$ flask run
If you're running in PyCharm (or probably any other IDE) you can set environment variables in the run configuration.
Development mode enables the debugger and reloader by default. If you don't want these, pass --no-debugger
or --no-reloader
to the run
command.
That warning is just a warning though, it's not an error preventing your app from running. If your app isn't working, there's something else wrong with your code.
To avoid these messsages, inside the CLI (Command Line Interface), run these commands.
export FLASK_APP=app.py
export FLASK_ENV=development
export FLASK_DEBUG=0
flask run