For this article, I wanted to create a guide to building a simple Flask app from scratch. This guide is just to get you through the first steps of creating a Flask application.
My favourite IDE is PyCharm. To create a simple Flask application, I have created a new project within PyCharm. The advantage of doing that in PyCharm is, that my IDE creates immediately a virtual environment.
You have to install Flask in your virtual environment:
pip install Flask
Save the dependencies in a file (requirements.txt) in root directory with command:
pip freeze > requirements.txt
Legend:
pip freeze
: This command creates a list of all your installed packages in the virtual environment, along with their versions.> requirements.txt
: This part of the command saves all the installed packages and their versions into a file called: requirements.txt
. When this file doesn't exist that command creates this file in root directory.To create a simple Flask application, you have to create in your root directory a file named: 'server.py' (you can name it whatever you like but AVOID to name it 'flask.py') and add this:
# server.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
Legend:
route()
decorator tells Flask which URL triggers our function.The next step is to start the server:
flask --app server run --debug
Legend:
flask
: Is the Flask CLI tool to manage the application.--app server
: This part specifies that the Flask application is defined in the server.py
file.run
: This command starts the Flask development server and serves the application locally.--debug
: This part enables the debug mode of the Flask application.And that is it, you can go to your browser and enter: http://127.0.0.1:5000
and you should see "Hello World!" displayed on your browser screen.