DEV Community

Cover image for Building a "Hello World!": An Intro to Flask for Web Development
Lisandra Melo
Lisandra Melo

Posted on

Building a "Hello World!": An Intro to Flask for Web Development

What is Flask?

Flask is a Python micro-framework built to work with both web applications and RESTful APIs. Being a micro-framework gives Flask the ability to be simpler and lighter than other frameworks, (such as Django) in fact, Flask only "carries" along with it the libraries: Jinja and Werkzeug.

Jinja Library is a template engine tool used in Python web Frameworks (again, such as Django), Jinja gives us the ability to use variables and Python expressions inside HTML and XML files. Thus, you can write lines of codes in static files, such as HTML, and then, when the files are rendered, the code is executed and the static content is dynamically changed.

The Werkzeug library is a set of utilities and applications WSGI (Web Server Gateway Interface), hence, this library has applications for web server and web application communication and it controls and processes requests. Shortly, the library acts as a bridge, managing the interactions between users and our Flask applications.

What do I Need to Start with Flask?

To start with Flask, it is recommended that you have a basic knowledge of Python, along with some knowledge of HTML, CSS, and JavaScript. Besides, of course, the installation of Python and Flask.

That said, we will now install Flask, as Flask is a python library you will need to have the programming language installed on your machine before start using Flask. As for the library installation, we will use a python package installer (that comes with python on its installation), called pip, and to perform the installation we will type the following command in our terminal:

$ pip install Flask
Enter fullscreen mode Exit fullscreen mode

When using this command you will be installing Flask on your entire machine, but it is recommended that we do not do this and use a virtual environment like Virtualenv, but to avoid any complications we will choose the simplest path shown above.

Building our "Hello World!"

Now we start the coding! First, we will have to import the Flask class from the flask library into our program:

from flask import Flask
Enter fullscreen mode Exit fullscreen mode

After that, we will need to create an object of the Flask class, in its constructor we usually use the term __name__, because with it Flask will know where to look for HTML, CSS, and other files.

app = Flask(__name__)
Enter fullscreen mode Exit fullscreen mode

Flask works with an internal route system, each route represents an address of our domain, that is, imagine that the domain of our page is helloworld.com.br a route from that address can be/specialhello that behaves being concatenated to the domain to represent another route on our website, in this case, the route address would be helloworld.com.br/specialhello.

Each route triggers the operation of a specific method (the method located immediately below the definition of the route) in our code and that method will determine what will be executed at our address upon its return. The return of this function is interpreted as pure HTML and rendered as one.

So, we will create our first two routes.

"""
Now we will define a route with @app.route(), the parameter inside the parentheses
represent an address of our route.
When using only '/' in parentheses we are specifying the main route
of our website, that is, we are just accessing the homepage of the website
"""
@app.route('/')
def hello_world():
    return 'Hello World!'

"""
Now we will define a second route with @app.route(), the parameter inside the
parentheses represents an address of our route. In this case, our route
will be ourdomain.com/lisandra
"""
@app.route('/lisandra')
def hello_lisandra():
    # We will return our text with a HTML tag this time
    return '<h1>Hello Lisandra!</h1>'
Enter fullscreen mode Exit fullscreen mode

And you need to save all that in a file with a .py format.

Now we have our first web application ready to be executed, and we can do that in two ways.

First Method of Running Flask Locally

The first method for executing the flash is to use the flask command to run your program, but first, you must tell flask settings what your program name is.

  • If you are on Linux, you can type the following command in your terminal:
$ export FLASK_APP=<your_program_name>.py
Enter fullscreen mode Exit fullscreen mode
  • If you are on Windows, type the following line of code at your command prompt:
C:\your\application\directory>set FLASK_APP=<your_program_name>.py
Enter fullscreen mode Exit fullscreen mode
  • And if you are in the PowerShell, type:
PS C:\your\application\directory>$env:FLASK_APP = "<your_program_name>.py"
Enter fullscreen mode Exit fullscreen mode

Then, you can run the following command to run your program.

flask run
Enter fullscreen mode Exit fullscreen mode

Second Method

Another way to run your application is by adding a few lines of code to your application.

First, we will test whether we are running this program as a program alone or importing it as a library, if it is being executed as a program the variable __name__ receives the value of__main__.

After that, we will use the run() method of the Flask class to run our program.

"""
Now we will determine that we want to run our app, for that we use app.run()
we could only write this at the end of our program, but we do a test
before this test checks if our variable __name__ is equal to '__main__' when
a .py file is executed by itself as a program, __name__ is defined
as '__main__' so if we run our program we will run app.run ()
"""
if __name__ == "__main__":
     app.run ()
Enter fullscreen mode Exit fullscreen mode

Then, to run your program, type the following command in your terminal.

python <your_program_name>.py
Enter fullscreen mode Exit fullscreen mode

Execution

When you run the program, in either one of the ways presented before, you will see something on the screen like the following output.

 * Serving Flask app "hello" (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)
Enter fullscreen mode Exit fullscreen mode

And now if you access the address shown in your output you will see the following page:
Hello World developed in the program presented in the browser
Hello World developed in the program presented in the browser

If you access our route '/lisandra' at the address http://127.0.0.1:5000/lisandra you will see the output "Hello Lisandra!", because it was what we asked for it to return.
Screenshot of the page in the second route created
Screenshot of the page in the second route created

Note that "Hello Lisandra!" is printed as a <h1> element, that happens because our return in the /lisandra route function is always executed as HTML content, so any tags in the return will be executed as such.

Now you can see your first website using Flask up and running!

The program developed in this tutorial is available in my GitLab.

Top comments (1)

Collapse
 
rr9853462 profile image
Rima Sharma

This is an excellent article on introducing Flask for web development. I'm really looking forward to learning more about using Flask and creating my own web development projects. It's great to see such an informative introduction for those who are just getting started. Thanks for sharing!