DEV Community

DoriDoro
DoriDoro

Posted on

How to create a simple Flask application

Introduction:

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.

creating a simple Flask app

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
Enter fullscreen mode Exit fullscreen mode

Save the dependencies in a file (requirements.txt) in root directory with command:

pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode

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>"
Enter fullscreen mode Exit fullscreen mode

Legend:

  1. We import the Flask class at the beginning of our file. An instance of this class will be our WSGI application.
  2. Next we create an instance of the Flask class.
  3. The route() decorator tells Flask which URL triggers our function.
  4. In this simple example, the function returns a paragraph with the content of "Hello World!".

The next step is to start the server:

flask --app server run --debug
Enter fullscreen mode Exit fullscreen mode

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.

Flask documentation

Top comments (0)