python flask example

Flask is a compact and lightweight Python web framework that provides essential tools and capabilities for building online applications in Python. Because you can create a web application rapidly using only a single Python file, it allows developers more flexibility and is a more accessible framework for beginning developers. Flask is also extendable, and it doesn’t require complicated boilerplate code or a specific directory structure to get started.

You’ll utilize the Bootstrap toolkit to style your app to make it more aesthetically appealing as part of this article. Bootstrap makes it easy to include responsive web pages in your online application so that it works effectively on mobile browsers without having to write your HTML, CSS, or JavaScript code. Instead, you may concentrate on learning how Flask interacts with the toolbox.

Jinja is templating engine used by Flask to dynamically generate HTML pages using Python concepts like variables, loops, and lists. This template will be used in this project.

Using Flask in Python

In this article, you’ll learn how to create a mini-codeunderscored web app in Python 3 using Flask. Users of the application can navigate from one of the three pages on the site.

Installing Python

At this point, install Python on your PC if you don’t have it already. Python can be installed in different ways, but the two standard methods that are widely used include: –

-Installing Python through the terminal
-Downloading from the main site and doing a manual installation

The steps to accomplish may differ depending on the kind of operating system you are using.

Installing Python on Ubuntu
sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.8


Alternatively, go to the following link, and select your desired version and download it.

When done with the installation process, you can verify that you have Python successfully installed on your PC. Then, on the terminal, run the command that appears below.

python ––version

Installing Flask on Ubuntu

Run the following command on the terminal.

pip install flask

In case of failure, ensure that you have pip installed. If it’s not installed, you can have it by running the following command.

sudo apt update
sudo apt install python3-pip

Now that you have Flask installed create a folder on your desktop and name it FLASK EXAMPLE. We will then proceed by making the most straightforward hello flask application in a file called hello_Flask.py, as shown below.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, codeunderscored.com!"
    
if __name__ == "__main__":
    app.run(debug=True)

To verify that the application runs, open the same directory in the terminal and run the following command,

Python hello_Flask.py
run hello_Flask.py on the terminal
run hello_Flask.py on the terminal

When done, you should get a view that is close to the one shown below.

Output of running hello_Flask.py
Output of running hello_Flask.py

That’s it! Congratulations on creating your first Flask application.

In the next section, we will create a more in-depth application that will tie together several concepts on Flask web development. The example will be a simple website with three views and routes that will enable you to switch from one page to another. So, let’s dive right in.

Let’s start by adding more routes:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Welcome to codeunderscored.com !"
    

@app.route("/about")
def about():
    return "CodeUnderscored is your to go to tech platform"
    
if __name__ == "__main__":
    app.run(debug=True)

In both the examples above, we have returned the text. What if we want to make the website more attractive? This is where CSS and HTML come into play.

The flask framework’s render_template() method was imported. render_template() searches the templates folder for a template (HTML file). The template you requested will then be rendered.

Replace return with render_template(“home.html”). This allows us to see our HTML file. Use the updated file below for your reference.

from flask import Flask, render_template      

app = Flask(__name__)

@app.route("/")
def home():
      return render_template("home.html")
    
@app.route("/about")
def about():
    return render_template("about.html")
    
if __name__ == "__main__":
    app.run(debug=True)

Navigation

Let’s use the navigation to link the three pages. Connect the three pages by using a navigation menu at the top of the page. Again, we can utilize Flask to simplify the navigation menu creation process.

Let’s start by making a base.html file. This base.html will be used to create a child template. Its code will be passed down to our two child templates, home.html, contactus.html and about.html, that will inherit it.

<! -- base.html -->

<!DOCTYPE html>
<html lang="en" dir="ltr">
 <head>
   <meta charset="utf-8">
   <title>Flask codeunderscored Template</title>
   <link rel="stylesheet" href="{{ url_for('static',  filename='css/template.css') }}">
 </head>
 <body>
    <header>
      <div class="container">
        <h1 class="logo">First Flask codeunderscored App</h1>
        <strong><nav>
          <ul class="menu">
            <li><a href="{{ url_for('home') }}">Home</a></li>
            <li><a href="{{ url_for('about') }}">About</a></li>
          </ul>
        </nav></strong>
      </div>
    </header>
    
    {% block content %}
    {% endblock %}
    
 </body>
</html>

The function url_for() is used because it takes the function’s name as an argument. So, for the time being, we’ve given it the function’s name.

The content of home.html, contactus.html, and about.html will replace the two lines with curly brackets. This will be determined by the URL that the user is visiting.

These modifications make it possible for the child pages (home.html, contactus.html and about.html) to communicate with the parent page (base.html). In addition, this eliminates the need to copy the navigation menu code from about.html and home.html.

Using CSS to Enhance Our Website

Remember the need for a folder named static in the same way that we built a folder called templates to contain all of our HTML templates.

We’ll keep our CSS, JavaScript, pictures, and other relevant files static. As a result, you must create a CSS folder to house your stylesheets. When you’re finished, your project folder should look something like this:

organizing static files and templates
organizing static files and templates

Creating a link between our CSS and HTML files

The base.html file is the one that connects all of the pages. We can place the code here, and it will work on all child pages.

<!--base.html-->

<!DOCTYPE html>
<html lang="en" dir="ltr">
 <head>
   <meta charset="utf-8">
   <title>Flask Flask codeunderscored App</title>
   <link rel="stylesheet" href="{{ url_for('static',     filename='css/style.css') }}">
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
 </head>
 <body>
    <header>
      <div class="container">
        <nav class="navbar navbar-expand-md navbar-light bg-light">
            <a class="navbar-brand" href="{{ url_for('home')}}">Home</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                <li class="nav-item active">
                    <a class="nav-link" href="{{ url_for('about') }}">About</a>
                </li>
                <li class="nav-item ">
                    <a class="nav-link" href="{{ url_for('contactus') }}">Contact Us</a>
                </li>
                </ul>
            </div>
        </nav>

    </header>
    
  
    <div class="container">
        {% block content %} {% endblock %}
    </div>
    
 </body>
</html>

<!--home.html-->

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>codeunderscored Flask Tutorial</title>
  </head>
  <body>
    {% extends "base.html" %}
    {% block content %}
    <h1> Welcome to codeunderscored Flask Tutorial</h1>
    <p> Flask is Fun </p>
    {% endblock %}
  </body>
</html>
<!--about.html-->

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>About codeunderscored</title>
  </head>
  <body>
    {% extends "base.html" %}
    {% block content %}
    <h1> About codeunderscored </h1>
    <p> codeunderscored is a cutting edge platform on everything you need to know about development.</p>
    <p> The common platforms currently covered by codeunderscored include Java, C++, Python
         (Django, Flask) & Laravel.</p>
   
    {% endblock %}
  </body>
</html>
<!--contactus.html-->

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Contact Us</title>
  </head>
  <body>
    {% extends "base.html" %}
    {% block content %}
    <h1> Contact codeunderscored </h1>
    <div class="container">
      <div class="row">
          <div class="col-md-8">
              <div class="well well-sm">
                  <form>
                  <div class="row">
                      <div class="col-md-6">
                          <div class="form-group">
                              <label for="name">
                                  Name</label>
                              <input type="text" class="form-control" id="name" placeholder="Enter name" required="required" />
                          </div>
                          <div class="form-group">
                              <label for="email">
                                  Email Address</label>
                              <div class="input-group">
                                  <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span>
                                  </span>
                                  <input type="email" class="form-control" id="email" placeholder="Enter email" required="required" /></div>
                          </div>
                          <div class="form-group">
                              <label for="subject">
                                  Subject</label>
                              <select id="subject" name="subject" class="form-control" required="required">
                                  <option value="na" selected="">Choose One:</option>
                                  <option value="service">Python</option>
                                  <option value="suggestions">Django</option>
                                  <option value="product">Flask</option>
                              </select>
                          </div>
                      </div>
                      <div class="col-md-6">
                          <div class="form-group">
                              <label for="name">
                                  Message</label>
                              <textarea name="message" id="message" class="form-control" rows="9" cols="25" required="required"
                                  placeholder="Message"></textarea>
                          </div>
                      </div>
                      <div class="col-md-12">
                          <button type="submit" class="btn btn-primary pull-right" id="btnContactUs">
                              Send Message</button>
                      </div>
                  </div>
                  </form>
              </div>
          </div>
      </div>
  </div>
   
    {% endblock %}
  </body>
</html>

A majority of the code above is basic HTML and code snippets for Bootstrap. However, we will break down what the different tags mean as follows:

  • <meta> is a tag responsible for providing the browser with information
  • <link> is vital when you intend to connect Bootstrap CSS files to your HTML file
  • <script> Allows the user to embed JavaScript code. In some cases, it is a great way to pull in additional features of Bootstrap.

For further reading on the Bootstrap features, you can check out the Bootstrap documentation.

However, the following highlighted elements are specific to the Jinja template engine, which is used in Flask:

{% block title %} {% endblock %}:

A block title acts as your title’s placeholder. You’ll subsequently utilize the secondary templates. By so doing, you can give a custom title for each page in your application without rewriting the entire section each time.

{{ url_for('home')}}:

The function call above will return the URL for the home() view function. This is different from the former url_for() call we used to connect a static CSS file earlier. This is because it only takes one argument, which is the view function’s name. In addition, it links to the route associated with the function instead of a static file.

{% block content %} {% endblock %}:

This is another block that will be replaced by the content dependent on the child template. These are essentially templates that inherit from base.html that will override it.

Why should you use virtualenv?

The uses of Python are vast and diverse in addition to web development. For instance, different Python versions, dependencies, and packages may be installed in your projects.

Virtualenv is responsible for building your project in an isolated environment. It means that each project can have its dependencies independent of other projects’ dependencies.

Using virtualenv for the first time

To begin, install virtualenv by typing the following command into your command prompt or terminal:

pip install virtualenv
pip install virtualenv
pip install virtualenv

Next, you can give the virtual a name. In this example, we prefer to use my_virtual. So, create a virtualenv by running the following command on the terminal, virtualenv my_virtual. This is what it will look like:

virtualenv my_virtual
create a virtualenv called  my_virtual
create a virtualenv called my_virtual

The virtual environment must be established in the same directory as your application files.

How to activate the virtual environment

Now go to your command prompt or terminal. Then, change the directory to where the activation file is located. The aim is to activate the virtual environment and the activate file is located in the Scripts folder for Windows and bin for OS X and Linux.

For the Macintosh and Linux environments:

source my_virtual/bin/activate
activating your virtual environment
activating your virtual environment

The following step is to install Flask on your virtual environment to run the application there. Execute the following command:

pip install flask
install flask in your virtual environment
install flask in your virtual environment

To get the application up and running, initiate the process on the command line by running the following command.

flask run

There are various pieces of information in the preceding output, including:

  • The name of the program you’re using.
  • The context in which the application is being executed.
  • The Flask debugger is active when debug mode is set to on. When things go wrong, this is important since it gives us precise error messages, making debugging easier.
fun flask applic ation on my_virtual
fun flask applic ation on my_virtual

The program is accessible locally via http://127.0.0.1:5000/, where 127.0.0.1 is your machine’s localhost IP address and:5000 is the port number.

Suppose you open a browser and put in http://127.0.0.1:5000/, the home page! Will appear. As a result, this indicates that your application is up and operating.

Caution! Flask serves our application using a simple web server in a development environment, which also means the Flask debugger is running to make spotting mistakes easier. In a production deployment, this development server should not be used. For further information, see the Flask documentation’s Deployment Options page, as well as Flask deployment.

Final Thoughts

This article introduced essential concepts of the Flask Python framework by creating a mini-codeunderscored website having a home page, about and contact us pages. In addition, you learned how to run it in a development server and allow the user to navigate from one view to another via the URL in the web forms. You also used the Jinja template engine to reuse HTML files and use logic in them. In summary, you’ve all learned how to do the following things as a result of this tutorial:

  • To use Python as a server-side language, utilize the Flask framework.
  • How to construct a website using HTML, CSS, and Flask.
  • How to use virtualenv to construct virtual environments.

Similar Posts

One Comment

  1. followed your instructions until last command ‘flask run’ and my system doesn’t recognize it(Linux Mint).
    “Usage: flask run [OPTIONS]
    Try ‘flask run –help’ for help.

    Error: Could not locate a Flask application. Use the ‘flask –app’ option, ‘FLASK_APP’ environment variable, or a ‘wsgi.py’ or ‘app.py’ file in the current directory.”
    When I try to run in Firefox the IP address created gives me another errors:

    NameError

    NameError: name ‘render_template’ is not defined
    Traceback (most recent call last)

    File “/home/hephaistos/anaconda3/lib/python3.10/site-packages/flask/app.py”, line 2548, in __call__

    return self.wsgi_app(environ, start_response)

    File “/home/hephaistos/anaconda3/lib/python3.10/site-packages/flask/app.py”, line 2528, in wsgi_app

    response = self.handle_exception(e)

    File “/home/hephaistos/anaconda3/lib/python3.10/site-packages/flask/app.py”, line 2525, in wsgi_app

    response = self.full_dispatch_request()

    File “/home/hephaistos/anaconda3/lib/python3.10/site-packages/flask/app.py”, line 1822, in full_dispatch_request

    rv = self.handle_user_exception(e)

    File “/home/hephaistos/anaconda3/lib/python3.10/site-packages/flask/app.py”, line 1820, in full_dispatch_request

    rv = self.dispatch_request()

    File “/home/hephaistos/anaconda3/lib/python3.10/site-packages/flask/app.py”, line 1796, in dispatch_request

    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)

    File “/home/hephaistos/Desktop/Flask Example/hello_Flask.py”, line 7, in home

    return render_template(“home.html”)

    NameError: name ‘render_template’ is not defined

    The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.

    To switch between the interactive traceback and the plaintext one, you can click on the “Traceback” headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

    You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

    dump() shows all variables in the frame
    dump(obj) dumps all that’s known about the object

    Could you, please, advise?
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *