One place for hosting & domains

      Application

      How To Use Templates in a Flask Application


      The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Flask is a lightweight Python web framework that provides useful tools and features for creating web applications in the Python Language.

      When developing a web application, it is important to separate business logic from presentation logic. Business logic is what handles user requests and talks to the database to build an appropriate response. Presentation logic is how the data is presented to the user, typically using HTML files to build the basic structure of the response web page, and CSS styles to style HTML components. For example, in a social media application, you might have a username field and a password field that can be displayed only when the user is not logged in. If the user is logged in, you display a logout button instead. This is the presentation logic. If a user types in their username and password, you can use Flask to perform business logic: You extract the data (the username and password) from the request, log the user in if the credentials are correct or respond with an error message. How the error message is displayed will be handled by the presentation logic.

      In Flask, you can use the Jinja templating language to render HTML templates. A template is a file that can contain both fixed and dynamic content. When a user requests something from your application (such as an index page, or a login page), Jinja allows you to respond with an HTML template where you can use many features that are not available in standard HTML, such as variables, if statements, for loops, filters, and template inheritance. These features allow you to efficiently write easy-to-maintain HTML pages. Jinja also automatically escapes HTML to prevent Cross-Site Scripting (XSS) attacks.

      In this tutorial, you’ll build a small web application that renders several HTML files. You’ll use variables to pass data from the server to the templates. Template inheritance will help you avoid repetition. You’ll use logic in templates such as conditionals and loops, use filters to modify text, and use the Bootstrap toolkit to style your application.

      Prerequisites

      Step 1 — Rendering a Template and Using Variables

      Make sure you have activated your environment and have Flask installed, and then you can start building your application. The first step is to display a message that greets visitors on the index page. You’ll use Flask’s render_template() helper function to serve an HTML template as the response. You will also see how to pass variables from your application side to your templates.

      First, in your flask_app directory, open a file named app.py for editing. Use nano or your favorite text editor:

      Add the following code inside the app.py file:

      flask_app/app.py

      
      from flask import Flask, render_template
      
      app = Flask(__name__)
      
      
      @app.route('/')
      def hello():
          return render_template('index.html')
      

      Save and close the file.

      In this code block, you import the Flask class and the render_template() function from the flask package. You use the Flask class to create your Flask application instance named app. Then you define a view function (which is a Python function that returns an HTTP response) called hello() using the app.route() decorator, which converts a regular function into a view function. This view function uses the render_template() function to render a template file called index.html.

      Next, you’ll have to create the index.html template file in a directory called templates inside your flask_app directory. Flask looks for templates in the templates directory, which is called templates, so the name is important. Make sure you’re inside the flask_app directory and run the following command to create the templates directory:

      Next, open a file called index.html inside the templates directory for editing. The name index.html here is not a standard required name; you can call it home.html or homepage.html or anything else if you want:

      • nano templates/index.html

      Add the following HTML code inside the index.html file:

      flask_app/templates/index.html

      
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>FlaskApp</title>
      </head>
      <body>
          <h1>Hello World!</h1>
          <h2>Welcome to FlaskApp!</h2>
      </body>
      </html>
      

      Here, you set a title, added a Hello World! message as an H1 heading, and created a Welcome to FlaskApp! message as an H2 heading.

      Save and close the file.

      While in your flask_app directory with your virtual environment activated, tell Flask about the application (app.py in your case) using the FLASK_APP environment variable, and set the FLASK_ENV environment variable to development to run the application in development mode and get access to the debugger. Use the following commands to do this (on Windows, use set instead of export):

      • export FLASK_APP=app
      • export FLASK_ENV=development

      Then, run the application using the flask run command:

      With the development server running, visit the following URL using your browser:

      http://127.0.0.1:5000/
      

      You’ll see the title of the page is set to FlaskApp, and the two headings are rendered HTML.

      In web applications, you often need to pass data from your application’s Python files to your HTML templates. To demonstrate how to do this in this application, you will pass a variable containing the current UTC date and time to the index template, and you’ll display the value of the variable in the template.

      Leave the server running, and open your app.py file for editing in a new terminal:

      Import the datetime module from the Python standard library and edit the index() function so the file looks as follows:

      flask_app/app.py

      import datetime
      from flask import Flask, render_template
      
      app = Flask(__name__)
      
      
      @app.route('/')
      def hello():
          return render_template('index.html"https://www.digitalocean.com/community/tutorials/, utc_dt=datetime.datetime.utcnow())
      

      Save and close the file.

      Here you imported the datetime module and passed a variable called utc_dt to the index.html template with the value of datetime.datetime.utcnow(), which is the current UTC date and time.

      Next, to display the variable’s value on the index page, open the index.html file for editing:

      • nano templates/index.html

      Edit the file to look as follows:

      flask_app/templates/index.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>FlaskApp</title>
      </head>
      <body>
          <h1>Hello World!</h1>
          <h2>Welcome to FlaskApp!</h2>
          <h3>{{ utc_dt }}</h3>
      </body>
      </html>
      

      Save and close the file.

      You added an H3 heading with the special {{ ... }} delimiter to print the value of the utc_dt variable.

      Open your browser and visit the index page:

      http://127.0.0.1:5000/
      

      You’ll see a page similar to the following image:

      The Index Page

      You’ve now created an index page with an HTML template in your Flask application, rendered a template, and passed and displayed a variable value. Next you’ll avoid code repetition by using template inheritance.

      Step 2 — Using Template Inheritance

      In this step, you’ll make a base template with content that can be shared with your other templates. You’ll edit your index template to inherit from the base template. Then, you’ll make a new page that will serve as your application’s About page, where users can find more information about your application.

      A base template contains HTML components that are typically shared between all other templates, such as the application’s title, navigation bars, and footers.

      First, open a new file called base.html for editing inside your templates directory:

      Write the following code inside your base.html file:

      flask_app/templates/base.html

      
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>{% block title %} {% endblock %} - FlaskApp</title>
          <style>
              nav a {
                  color: #d64161;
                  font-size: 3em;
                  margin-left: 50px;
                  text-decoration: none;
              }
          </style>
      </head>
      <body>
          <nav>
              <a href="#">FlaskApp</a>
              <a href="#">About</a>
          </nav>
          <hr>
          <div class="content">
              {% block content %} {% endblock %}
          </div>
      </body>
      </html>
      

      Save and close the file.

      Most of the code in this file is standard HTML, a title, some styling for the navigation links, a navigation bar with two links, one for the index page and one for the About page not yet created, and a <div> for the page’s content. (The links don’t work yet; the next step will demonstrate how to link between pages).

      However, the following highlighted parts are specific to the Jinja template engine:

      • {% block title %} {% endblock %}: A block that serves as a placeholder for a title. You’ll later use it in other templates to provide a custom title for each page in your application without rewriting the entire <head> section each time.

      • {% block content %} {% endblock %}: Another block that will be replaced by content depending on the child template (a template that inherits from base.html) that will override it.

      Now that you have a base template, you can take advantage of it using inheritance. Open the index.html file:

      • nano templates/index.html

      Then replace its contents with the following:

      flask_app/templates/index.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Index {% endblock %}</h1>
          <h1>Hello World!</h1>
          <h2>Welcome to FlaskApp!</h2>
          <h3>{{ utc_dt }}</h3>
      {% endblock %}
      

      Here, you use the {% extends %} tag to inherit from the base.html template. You then extend it via replacing the content block in the base template with what is inside the content block in the preceding code block.

      This content block contains an <h1> tag with the text Index inside a title block, which in turn replaces the original title block in the base.html template with the text Index so that the complete title becomes Index - FlaskApp. This way, you can avoid repeating the same text twice, as it works both as a title for the page and a heading that appears below the navigation bar inherited from the base template.

      Then you have a few more headings: one <h1> heading with the text Hello World!, an <h2> heading, and an <h3> heading containing the value of the utc_dt variable.

      Template inheritance gives you the ability to reuse the HTML code you have in other templates (base.html in this case) without having to repeat it each time it is needed.

      Save and close the file and refresh the index page on your browser. The page will look as follows:

      The Index Page After Inheritance

      Next, you’ll create the About page. Open the app.py file to add a new route:

      Add the following route at the end of the file:

      flask_app/app.py

      
      # ...
      @app.route('/about/')
      def about():
          return render_template('about.html')
      

      Here you use the app.route() decorator to create a view function called about(). In it, you return the result of calling the render_template() function with the about.html template file name as an argument.

      Save and close the file.

      Open a template file called about.html for editing:

      • nano templates/about.html

      Add the following code to the file:

      flask_app/templates/about.html

      
      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} About {% endblock %}</h1>
          <h3>FlaskApp is a Flask web application written in Python.</h3>
      {% endblock %}
      

      Here, you inherit from the base template using the extends tag, replace the base template’s content block with an <h1> tag that also serves as the page’s title, and add an <h3> tag with some information about the application.

      Save and close the file.

      With the development server running, visit the following URL using your browser:

      http://127.0.0.1:5000/about
      

      You’ll see a page similar to the following:

      About Page

      Notice how the navigation bar and part of the title are inherited from the base template.

      You’ve now created a base template and used it in your index page and about page to avoid code repetition. The links in the navigation bar don’t do anything at this point. In the next step, you’ll learn how to link between routes in your templates by fixing the navigation bar links.

      Step 3 — Linking between Pages

      In this step, you’ll learn how to link between pages in your templates using the url_for() helper function. You will add two links to the navigation bar in your base template, one for the index page, and one for the About page.

      First open your base template for editing:

      Edit the file to look as follows:

      flask_app/templates/base.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>{% block title %} {% endblock %} - FlaskApp</title>
          <style>
              nav a {
                  color: #d64161;
                  font-size: 3em;
                  margin-left: 50px;
                  text-decoration: none;
              }
          </style>
      </head>
      <body>
          <nav>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for('hello') }}">FlaskApp</a>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for('about') }}">About</a>
          </nav>
          <hr>
          <div class="content">
              {% block content %} {% endblock %}
          </div>
      </body>
      </html>
      

      Here, you use the special url_for() function that will return the URL for the view function you give it. The first link links to the route of the hello() view function (which is the index page). The second link links to the route of the about() view function. Notice that you pass the name of the view function, not the route (/ or /about).

      Using the url_for() function to build URLs helps you manage URLs better. If you hard-code URLs, your links will break if you edit the routes. With url_for() you can edit routes and guarantee that the links will still work as expected. The url_for() function also takes care of other things like escaping special characters.

      Save and close the file.

      Now go to the index page and try out the links in the navigation bar. You’ll see that they work as expected.

      You learned how to use the url_for() function to link to other routes in your templates. Next, you will add some conditional statements to control what is displayed in your templates depending on conditions you set, and use for loops in your templates to display list items.

      Step 4 — Using Conditionals and Loops

      In this step, you’ll use if statements in your templates to control what to display depending on certain conditions. You’ll also use for loops to go through Python lists and display each item in the list. You’ll add a new page that displays comments in a list. Comments with an even index number will have a blue background, and comments with an odd index number will be displayed with a gray background.

      First, you will create a route for the comments page. Open your app.py file for editing:

      Add the following route at the end of the file:

      flask_app/app.py

      
      # ...
      
      @app.route('/comments/')
      def comments():
          comments = ['This is the first comment.',
                      'This is the second comment.',
                      'This is the third comment.',
                      'This is the fourth comment.'
                      ]
      
          return render_template('comments.html', comments=comments)
      

      In the route above, you have a Python list called comments that contains four items. (These comments would usually come from a database in a real-world scenario rather than being hard-coded like you’ve done here.) You return a template file called comments.html in the last line, passing a variable called comments containing the list to the template file.

      Save and close the file.

      Next, open a new comments.html file inside the templates directory for editing:

      • nano templates/comments.html

      Add the following code to the file:

      flask_app/templates/comments.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Comments {% endblock %}</h1>
          <div style="width: 50%; margin: auto">
              {% for comment in comments %}
              <div style="padding: 10px; background-color: #EEE; margin: 20px">
                  <p style="font-size: 24px">{{ comment }}</p>
              </div>
              {% endfor %}
          </div>
      {% endblock %}
      

      Here, you extend the base.html template and replace the contents of the content block. First, you use an <h1> heading that also serves as the page’s title.

      You use a Jinja for loop in the line {% for comment in comments %} to go through each comment in the comments list (which gets stored in the comment variable). You display the comment in the <p style="font-size: 24px">{{ comment }}</p> tag the same way you would normally display a variable in Jinja. You signal the ending of the for loop using the {% endfor %} keyword. This is different from the way Python for loops are constructed because there is no special indentation in Jinja templates.

      Save and close the file.

      With the development server running, open your browser and visit the comments page:

      http://127.0.0.1:5000/comments
      

      You will see a page similar to the following:

      Comments Page

      Now you will use the if conditional statement in your templates by displaying comments with an odd index number with a gray background, and comments with an even index number with a blue background.

      Open your comments.html template file for editing:

      • nano templates/comments.html

      Edit it to look as follows:

      flask_app/templates/comments.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Comments {% endblock %}</h1>
          <div style="width: 50%; margin: auto">
              {% for comment in comments %}
                  {% if loop.index % 2 == 0 %}
                      {% set bg_color="#e6f9ff" %}
                  {% else %}
                      {% set bg_color="#eee" %}
                  {% endif %}
      
                  <div style="padding: 10px; background-color: {{ bg_color }}; margin: 20px">
                      <p>#{{ loop.index }}</p>
                      <p style="font-size: 24px">{{ comment }}</p>
                  </div>
              {% endfor %}
          </div>
      {% endblock %}
      

      With this new edit, you added an if statement in the line {% if loop.index % 2 == 0 %}. The loop variable is a special Jinja variable that gives you access to information about the current loop. Here you use loop.index to get the index of the current item, which starts from 1, not 0 as in Python lists.

      The if statement here checks whether the index is even using the % operator. It checks for the remainder of dividing the index number by 2; if the remainder is 0 it means the index number is even, otherwise, the index number is odd. You use the {% set %} tag to declare a variable called bg_color. If the index number is even, you set it to a blueish color, otherwise, if the index number is odd, you set the bg_color variable to gray. You then use the bg_color variable to set a background color for the <div> tag that contains the comment. Above the comment’s text, you use loop.index to display the current index number in a <p> tag.

      Save and close the file.

      Open your browser and visit the comments page:

      http://127.0.0.1:5000/comments
      

      You will see your new Comments page:

      Comments Page With Alternating Background Colors

      This was a demonstration of how to use the if statement. But you can also achieve the same effect by using the special loop.cycle() Jinja helper. To demonstrate this, open the comments.html file:

      • nano templates/comments.html

      Edit it to look as follows:

      flask_app/templates/comments.html

      
      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Comments {% endblock %}</h1>
          <div style="width: 50%; margin: auto">
              {% for comment in comments %}
                  <div style="padding: 10px;
                              background-color: {{ loop.cycle('#EEE', '#e6f9ff') }};
                              margin: 20px">
                      <p>#{{ loop.index }}</p>
                      <p style="font-size: 24px">{{ comment }}</p>
                  </div>
              {% endfor %}
          </div>
      {% endblock %}
      

      Here, you removed the if/else statement and used the loop.cycle('#EEE', '#e6f9ff') helper to cycle between the two colors. The value of background-color will be #EEE one time and #e6f9ff another.

      Save and close the file.

      Open the comments page in your browser, refresh it, and you’ll see that this has the same effect as the if statement.

      You can use if statements for multiple purposes, including controlling what gets displayed on the page. For example, to display all comments except for the second one, you can use an if statement with the condition loop.index != 2 to filter out the second comment.

      Open the comments template:

      • nano templates/comments.html

      And edit it to look as follows:

      flask_app/templates/comments.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Comments {% endblock %}</h1>
          <div style="width: 50%; margin: auto">
              {% for comment in comments %}
                  {% if loop.index != 2 %}
                      <div style="padding: 10px;
                                  background-color: #EEE;
                                  margin: 20px">
                          <p>#{{ loop.index }}</p>
                          <p style="font-size: 24px">{{ comment }}</p>
                      </div>
                  {% endif %}
              {% endfor %}
          </div>
      {% endblock %}
      

      Here, you use {% if loop.index != 2 %} to show only the comments that don’t have the index 2, which means all the comments except for the second one. You also use a hard-coded value for the background color instead of the loop.cycle() helper to make things simpler, and the rest is not changed. You end the if statement using {% endif %}.

      Save and close the file.

      Refresh the comments page and you’ll see that the second comment is not displayed.

      You now need to add a link that takes users to the Comments page in the navigation bar. Open the base template for editing:

      Edit the contents of the <nav> tag by adding a new <a> link to it:

      flask_app/templates/base.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>{% block title %} {% endblock %} - FlaskApp</title>
          <style>
              nav a {
                  color: #d64161;
                  font-size: 3em;
                  margin-left: 50px;
                  text-decoration: none;
              }
          </style>
      </head>
      <body>
          <nav>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for("hello') }}">FlaskApp</a>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for("comments') }}">Comments</a>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for("about') }}">About</a>
          </nav>
          <hr>
          <div class="content">
              {% block content %} {% endblock %}
          </div>
      </body>
      </html>
      

      Here, you use the url_for() helper to link to the comments() view function.

      Save and close the file.

      The navigation bar will now have a new link that links to the comments page.

      You used if statements in your templates to control what to display depending on certain conditions. You used for loops to go through Python lists and display each item in the list, and you learned about the special loop variable in Jinja. Next, you’ll use Jinja filters to control how variable data is displayed.

      Step 5 — Using Filters

      In this step, you’ll learn how to use Jinja filters in your templates. You’ll use the upper filter to convert comments you added in the previous step to uppercase, you’ll use the join filter to join a sequence of strings into one string, and you’ll learn how to render trusted HTML code without escaping it using the safe filter.

      First, you will convert the comments in the comments page to uppercase. Open the comments.html template for editing:

      • nano templates/comments.html

      Edit it to look as follows:

      flask_app/templates/comments.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Comments {% endblock %}</h1>
          <div style="width: 50%; margin: auto">
              {% for comment in comments %}
                  {% if loop.index != 2 %}
                      <div style="padding: 10px;
                                  background-color: #EEE;
                                  margin: 20px">
                          <p>#{{ loop.index }}</p>
                          <p style="font-size: 24px">{{ comment | upper }}</p>
                      </div>
                  {% endif %}
              {% endfor %}
          </div>
      {% endblock %}
      

      Here, you added the upper filter using the pipe symbol (|). This will modify the value of the comment variable to be uppercase.

      Save and close the file.

      With the development server running, open the comments page with your browser:

      http://127.0.0.1:5000/comments
      

      You can see that the comments are all in uppercase after applying the filter.

      Filters can also take arguments in parentheses. To demonstrate this, you’ll use the join filter to join all the comments in the comments list.

      Open the comments template:

      • nano templates/comments.html

      Edit it to look as follows:

      flask_app/templates/comments.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Comments {% endblock %}</h1>
          <div style="width: 50%; margin: auto">
              {% for comment in comments %}
                  {% if loop.index != 2 %}
                      <div style="padding: 10px;
                                  background-color: #EEE;
                                  margin: 20px">
                          <p>#{{ loop.index }}</p>
                          <p style="font-size: 24px">{{ comment | upper }}</p>
                      </div>
                  {% endif %}
              {% endfor %}
              <hr>
              <div>
                  <p>{{ comments | join(" | ") }}</p>
              </div>
          </div>
      {% endblock %}
      

      Here you added an <hr> tag and a <div> tag where you join all the comments in the comments list using the join() filter.

      Save and close the file.

      Refresh the comments page and you’ll see a page similar to the following:

      Comments Page With Join Filter

      As you can see, the comments list is displayed with the comments separated by a pipe symbol, which is what you passed to the join() filter.

      Another important filter is the safe filter, which allows you to render trusted HTML on the browser. To illustrate this, you’ll add some text containing an HTML tag to your comments template using the {{ }} Jinja delimiter. In a real-world scenario, this would come as a variable from the server. Then you’ll edit the join() argument to be the <hr> tag instead of the pipe symbol.

      Open the comments template:

      • nano templates/comments.html

      Edit it to look as follows:

      flask_app/templates/comments.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Comments {% endblock %}</h1>
          <div style="width: 50%; margin: auto">
              {% for comment in comments %}
                  {% if loop.index != 2 %}
                      <div style="padding: 10px;
                                  background-color: #EEE;
                                  margin: 20px">
                          <p>#{{ loop.index }}</p>
                          <p style="font-size: 24px">{{ comment | upper }}</p>
                      </div>
                  {% endif %}
              {% endfor %}
              <hr>
              <div>
                  {{ "<h1>COMMENTS</h1>" }}
                  <p>{{ comments | join("https://www.digitalocean.com/community/tutorials/ <hr> ") }}</p>
              </div>
          </div>
      {% endblock %}
      

      Here, you added the value "<h1>COMMENTS</h1>" and changed the join argument to the <hr> tag.

      Save and close the file.

      Refresh the comments page and you’ll see a page similar to the following:

      Comments Page With No Safe Filter

      As you can see, the HTML tags were not rendered. This is a safety feature in Jinja, because some HTML tags can be harmful and may result in a Cross Site Scripting (XSS) attack. You should allow only trusted HTML to be rendered in the browser.

      To render the HTML tags above, open the comments template file:

      • nano templates/comments.html

      Edit it by adding the safe filter:

      flask_app/templates/comments.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Comments {% endblock %}</h1>
          <div style="width: 50%; margin: auto">
              {% for comment in comments %}
                  {% if loop.index != 2 %}
                      <div style="padding: 10px;
                                  background-color: #EEE;
                                  margin: 20px">
                          <p>#{{ loop.index }}</p>
                          <p style="font-size: 24px">{{ comment | upper }}</p>
                      </div>
                  {% endif %}
              {% endfor %}
              <hr>
              <div>
                  {{ "<h1>COMMENTS</h1>"https://www.digitalocean.com/community/tutorials/ | safe }}
                  <p>{{ comments | join(" <hr> ") | safe }}</p>
              </div>
          </div>
      {% endblock %}
      

      You can see that you can also chain filters like in the line <p>{{ comments | join(" <hr> ") | safe }}</p>. Each filter gets applied to the result of the previous filtering.

      Save and close the file.

      Refresh the comments page and you’ll see that the HTML tags are now rendered as expected:

      Comments Page With Safe Filter

      Warning: Using the safe filter on HTML from unknown data sources may open up your application to XSS attacks. Do not use it unless the HTML you are rendering is from a trusted source.

      For more information, check out the list of built-in Jinja filters.

      You have now learned how to use filters in your Jinja templates to modify variable values. Next, you’ll integrate the Bootstrap toolkit to style your application.

      Step 6 — Integrating Bootstrap

      In this step, you’ll learn how to use the Bootstrap toolkit to style your application. You’ll add a Bootstrap navigation bar in the base template that will appear in all the pages that inherit from the base template.

      The Bootstrap toolkit helps you style your application so it is more visually appealing. It will also help you incorporate responsive web pages in your web application so that it works well on mobile browsers without writing your own HTML, CSS, and JavaScript code to achieve these goals.

      To use Bootstrap, you’ll need to add it to the base template so you can use it in all other templates.

      Open your base.html template, for editing:

      Edit it to look as follows:

      flask_app/templates/base.html

      <!doctype html>
      <html lang="en">
        <head>
          <!-- Required meta tags -->
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
      
          <!-- Bootstrap CSS -->
          <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
      
          <title>{% block title %} {% endblock %} - FlaskApp</title>
        </head>
        <body>
          <nav class="navbar navbar-expand-lg navbar-light bg-light">
          <div class="container-fluid">
              <a class="navbar-brand" href="https://www.digitalocean.com/community/tutorials/{{ url_for("hello') }}">FlaskApp</a>
              <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-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">
                    <a class="nav-link" href="https://www.digitalocean.com/community/tutorials/{{ url_for("comments') }}">Comments</a>
                  </li>
                  <li class="nav-item">
                    <a class="nav-link" href="https://www.digitalocean.com/community/tutorials/{{ url_for("about') }}">About</a>
                  </li>
              </ul>
              </div>
          </div>
          </nav>
          <div class="container">
              {% block content %} {% endblock %}
          </div>
      
          <!-- Optional JavaScript -->
      
          <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
      
        </body>
      </html>
      

      Most of the code above is Bootstrap boilerplate required to use it. You have some meta tags, a link to the Bootstrap CSS file in the <head> section, and at the bottom you have a link to optional JavaScript. The highlighted parts of the code contain Jinja code explained in the previous steps. Notice how you use specific tags and CSS classes to tell Bootstrap how to display each element.

      In the <nav> tag above, you have an <a> tag with the class navbar-brand, which determines the brand link in the navigation bar. Inside the <ul class="navbar-nav"> tag, you have regular navigation bar items inside an <a> tag in an <li> tag.

      To learn more about these tags and CSS classes, see the Bootstrap components.

      Save and close the file.

      With the development server running, open the index page with your browser:

      http://127.0.0.1:5000/
      

      You’ll see a page similar to the following:

      Index Page with Bootstrap

      You can now use Bootstrap components to style items in your Flask application in all of your templates.

      Conclusion

      You now know how to use HTML templates in your Flask web application. You’ve used variables to pass data from the server to templates, employed template inheritance to avoid repetition, incorporated elements such as if conditionals and for loops, and linked between different pages. You learned about filters to modify text and display trusted HTML, and you integrated Bootstrap into your application.

      If you would like to read more about Flask, check out the Flask topic page.



      Source link

      How To Create Your First Web Application Using Flask and Python 3


      The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Flask is a lightweight Python web framework that provides useful tools and features for creating web applications in the Python Language. It gives developers flexibility and is an accessible framework for new developers because you can build a web application quickly using only a single Python file. Flask is also extensible and doesn’t force a particular directory structure or require complicated boilerplate code before getting started.

      Learning Flask will allow you to quickly create web applications in Python. You can take advantage of Python libraries to add advanced features to your web application, like storing your data in a database, or validating web forms.

      In this tutorial, you’ll build a small web application that renders HTML text on the browser. You’ll install Flask, write and run a Flask application, and run the application in development mode. You’ll use routing to display various web pages that serve different purposes in your web application. You’ll also use view functions to allow users to interact with the application through dynamic routes. Finally, you’ll use the debugger to troubleshoot errors.

      Prerequisites

      Step 1 — Installing Flask

      In this step, you’ll activate your Python environment and install Flask using the pip package installer.

      First, activate your programming environment if you haven’t already:

      Once you have activated your programming environment, install Flask using the pip install command:

      Once the installation is complete, you will see a list of installed packages in the last parts of the output, similar to the following:

      Output

      ... Installing collected packages: Werkzeug, MarkupSafe, Jinja2, itsdangerous, click, flask Successfully installed Jinja2-3.0.1 MarkupSafe-2.0.1 Werkzeug-2.0.1 click-8.0.1 flask-2.0.1 itsdangerous-2.0.1

      This means that installing Flask also installed several other packages. These packages are dependencies Flask needs to perform different functions.

      You’ve created the project folder, a virtual environment, and installed Flask. You can now move on to setting up a simple application.

      Step 2 — Creating a Simple Application

      Now that you have your programming environment set up, you’ll start using Flask. In this step, you’ll make a small Flask web application inside a Python file, in which you’ll write HTML code to display on the browser.

      In your flask_app directory, open a file named app.py for editing, use nano or your favorite text editor:

      Write the following code inside the app.py file:

      flask_app/app.py

      
      from flask import Flask
      
      app = Flask(__name__)
      
      
      @app.route('/')
      def hello():
          return '<h1>Hello, World!</h1>'
      

      Save and close the file.

      In the above code block, you first import the Flask object from the flask package. You then use it to create your Flask application instance, giving it the name app. You pass the special variable __name__, which holds the name of the current Python module. This name tells the instance where it’s located; you need this because Flask sets up some paths behind the scenes.

      Once you create the app instance, you can use it to handle incoming web requests and send responses to the user. @app.route is a decorator that turns a regular Python function into a Flask view function, which converts the function’s return value into an HTTP response to be displayed by an HTTP client, such as a web browser. You pass the value '/' to @app.route() to signify that this function will respond to web requests for the URL /, which is the main URL.

      The hello() view function returns the string '<h1>Hello, World!</h1>' as an HTTP response.

      You now have a simple Flask application in a Python file called app.py, in the next step, you will run the application to see the result of the hello() view function rendered in a web browser.

      Step 3 — Running the Application

      After creating the file that contains the Flask application, you’ll run it using the Flask command line interface to start the development server and render on the browser the HTML code you wrote as a return value for the hello() view function in the previous step.

      First, while in your flask_app directory with your virtual environment activated, tell Flask where to find the application (app.py in your case) using the FLASK_APP environment variable with the following command (on Windows, use set instead of export):

      Then specify that you want to run the application in development mode (so you can use the debugger to catch errors) with the FLASK_ENV environment variable:

      • export FLASK_ENV=development

      Lastly, run the application using the flask run command:

      Once the application is running, the output will be something like this:

      Output

      * Serving Flask app "app" (lazy loading) * Environment: development * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 296-353-699

      The preceding output has several pieces of information, such as:

      • The name of the application you’re running ("app").
      • The environment in which the application is being run (development).
      • Debug mode: on signifies that the Flask debugger is running. This is useful when developing because it provides detailed error messages when things go wrong, which makes troubleshooting easier.
      • The application is running locally on the URL http://127.0.0.1:5000/. 127.0.0.1 is the IP that represents your machine’s localhost and :5000 is the port number.

      Open a browser and type in the URL http://127.0.0.1:5000/. You will see the text Hello, World! in an <h1> heading as a response. This confirms that your application is successfully running.

      If you want to stop the development server, press CTRL+C.

      Warning: Flask uses a simple web server to serve your application in a development environment, which also means that the Flask debugger is running to make catching errors easier. You should not use this development server in a production deployment. See the Deployment Options page on the Flask documentation for more information. You can also check out this Flask deployment tutorial with Gunicorn or this one with uWSGI or you can use DigitalOcean App Platform to deploy your Flask application by following the How To Deploy a Flask App Using Gunicorn to App Platform tutorial.

      To continue developing the app.py application, leave the development server running and open another terminal window. Move into the flask_app directory, activate the virtual environment, set the environment variables FLASK_ENV and FLASK_APP, and continue to the next steps. (These commands are listed earlier in this step.)

      Note: When opening a new terminal, or when you close the one you are running the development server on and want to rerun it, it is important to remember activating the virtual environment and setting the environment variables FLASK_ENV and FLASK_APP for the flask run command to work properly.

      You only need to run the server once in one terminal window.

      While a Flask application’s development server is already running, it is not possible to run another Flask application with the same flask run command. This is because flask run uses the port number 5000 by default, and once it is taken, it becomes unavailable to run another application on so you would receive an error similar to the following:

      Output

      OSError: [Errno 98] Address already in use

      To solve this problem, either stop the server that’s currently running via CTRL+C, then run flask run again, or if you want to run both applications at the same time, you can pass a different port number to the -p argument, for example, to run another application on port 5001 use the following command:

      With this you can have one application running on http://127.0.0.1:5000/ and another one on http://127.0.0.1:5001/ if you want to.

      You now have a small Flask web application. You’ve run your application and displayed information on the web browser. Next, you’ll learn about routes and how to use them to serve multiple web pages.

      Step 4 — Routes and View Functions

      In this step, you’ll add a few routes to your application to display different pages depending on the requested URL. You’ll also learn about view functions and how to use them.

      A route is a URL you can use to determine what the user receives when they visit your web application on their browser. For example, http://127.0.0.1:5000/ is the main route that might be used to display an index page. The URL http://127.0.0.1:5000/about may be another route used for an about page that gives the visitor some information about your web application. Similarly, you can create a route that allows users to sign in to your application at http://127.0.0.1:5000/login.

      Your Flask application currently has one route that serves users who request the main URL (http://127.0.0.1:5000/). To demonstrate how to add a new web page to your application, you will edit your application file to add another route that provides information on your web application at http://127.0.0.1:5000/about.

      First, open your app.py file for editing:

      Edit the file by adding the following highlighted code at the end of the file:

      flask_app/app.py

      from flask import Flask
      
      app = Flask(__name__)
      
      
      @app.route('/')
      def hello():
          return '<h1>Hello, World!</h1>'
      
      
      @app.route('/about/')
      def about():
          return '<h3>This is a Flask web application.</h3>'
      

      Save and close the file.

      You added a new function called about(). This function is decorated with the @app.route() decorator that transforms it into a view function that handles requests for the http://127.0.0.1:5000/about endpoint.

      With the development server running, visit the following URL using your browser:

      http://127.0.0.1:5000/about
      

      You will see the text This is a Flask web application. rendered in an <h3> HTML heading.

      You can also use multiple routes for one view function. For example, you can serve the index page at both / and /index/. To do this, open your app.py file for editing:

      Edit the file by adding another decorator to the hello() view function:

      flask_app/app.py

      from flask import Flask
      
      app = Flask(__name__)
      
      @app.route('/')
      @app.route('/index/')
      def hello():
          return '<h1>Hello, World!</h1>'
      
      @app.route('/about/')
      def about():
          return '<h3>This is a Flask web application.</h3>'
      

      Save and close the file.

      After adding this new decorator, you can access the index page at both http://127.0.0.1:5000/ and http://127.0.0.1:5000/index.

      You now understand what routes are, how to use them to make view functions, and how to add new routes to your application. Next, you’ll use dynamic routes to allow users to control the application’s response.

      Step 5 — Dynamic Routes

      In this step, you’ll use dynamic routes to allow users to interact with the application. You’ll make a route that capitalizes words passed through the URL, and a route that adds two numbers together and displays the result.

      Normally, users don’t interact with a web application by manually editing the URL. Rather, the user interacts with elements on the page that lead to different URLs depending on the user’s input and action, but for the purposes of this tutorial, you will edit the URL to demonstrate how to make the application respond differently with different URLs.

      First, open your app.py file for editing:

      If you allow the user to submit something to your web application, such as a value in the URL as you are going to do in the following edit, you should always keep in mind that your app should not directly display untrusted data (data the user submits). To display user data safely, use the escape() function that comes with the markupsafe package, which was installed along with Flask.

      Edit app.py and add the following line to the top of the file, above the Flask import:

      flask_app/app.py

      from markupsafe import escape
      from flask import Flask
      
      # ...
      

      Then, add the following route to the end of the file:

      flask_app/app.py

      # ...
      
      @app.route('/capitalize/<word>/')
      def capitalize(word):
          return '<h1>{}</h1>'.format(escape(word.capitalize()))
      

      Save and close the file.

      This new route has a variable section <word>. This tells Flask to take the value from the URL and pass it to the view function. The URL variable <word> passes a keyword argument to the capitalize() view function. The argument has the same name as the URL variable (word in this case). With this you can access the word passed through the URL and respond with a capitalized version of it using the capitalize() method in Python.

      You use the escape() function you imported earlier to render the word string as text. This is important to avoid Cross Site Scripting (XSS) attacks. If the user submits malicious JavaScript instead of a word, escape() will it render as text and the browser will not run it, keeping your web application safe.

      To display the capitalized word inside an <h1> HTML heading, you use the format() Python method, for more on this method, see How To Use String Formatters in Python 3

      With the development server running, open your browser and visit the following URLs. You can replace the highlighted words with any word of your choice.

      http://127.0.0.1:5000/capitalize/hello
      http://127.0.0.1:5000/capitalize/flask
      http://127.0.0.1:5000/capitalize/python
      

      You can see the word in the URL capitalized in an <h1> tag on the page.

      You can also use multiple variables in a route. To demonstrate this, you will add a route that adds two positive integer numbers together and displays the result.

      Open your app.py file for editing:

      Add the following route to the end of the file:

      flask_app/app.py

      # ...
      
      @app.route('/add/<int:n1>/<int:n2>/')
      def add(n1, n2):
          return '<h1>{}</h1>'.format(n1 + n2)
      

      Save and close the file.

      In this route, you use a special converter int with the URL variable (/add/<int:n1>/<int:n2>/) which only accepts positive integers. By default, URL variables are assumed to be strings and are treated as such.

      With the development server running, open your browser and visit the following URL:

      http://127.0.0.1:5000/add/5/5/
      

      The result will be the sum of the two numbers (10 in this case).

      You now have an understanding of how to use dynamic routes to display different responses in a single route depending on the requested URL. Next, you’ll learn how to troubleshoot and debug your Flask application in case of an error.

      Step 6 — Debugging A Flask Application

      When developing a web application, you will frequently run into situations where the application displays an error instead of the behavior you expect. You may misspell a variable or forget to define or import a function. To make fixing these problems easier, Flask provides a debugger when running the application in development mode. In this step, you will learn how to fix errors in your application using the Flask debugger.

      To demonstrate how to handle errors, you will create a route that greets a user from a list of usernames.

      Open your app.py file for editing:

      Add the following route to the end of the file:

      flask_app/app.py

      # ...
      
      @app.route('/users/<int:user_id>/')
      def greet_user(user_id):
          users = ['Bob', 'Jane', 'Adam']
          return '<h2>Hi {}</h2>'.format(users[user_id])
      

      Save and close the file.

      In the route above, the greet_user() view function receives a user_id argument from the user_id URL variable. You use the int converter to accept positive integers. Inside the function, you have a Python list called users, which contains three strings representing usernames. The view function returns a string that is constructed depending on the provided user_id. If the user_id is 0, the response will be Hi Bob in an <h2> tag because Bob is the first item in the list (the value of users[0]).

      With the development server running, open your browser and visit the following URLs:

      http://127.0.0.1:5000/users/0
      http://127.0.0.1:5000/users/1
      http://127.0.0.1:5000/users/2
      

      You will receive the following responses:

      Output

      Hi Bob Hi Jane Hi Adam

      This works well so far, but it can go wrong when you request a greeting for a user who doesn’t exist. To demonstrate how the Flask debugger works, visit the following URL:

      http://127.0.0.1:5000/users/3
      

      You’ll see a page that looks like this:

      Flask Debugger

      At the top, the page gives you the name of the Python exception, which is IndexError, indicating that the list index (3 in this case) is out of the list’s range (which is only from 0 to 2 because the list has only three items). In the debugger, you can see the traceback that tells you the lines of code that raised this exception.

      The last two lines of the traceback usually give the source of the error. In your case the lines may be something like the following:

      File "/home/USER/flask_app/app.py", line 28, in greet_user
          return '<h2>Hi {}</h2>'.format(users[user_id])
      

      This tells you that the error originates from the greet_user() function inside the app.py file, specifically in the return line.

      Knowing the original line that raises the exception will help you determine what went wrong in your code, and decide what to do to fix it.

      In this case you can use a simple try...except clause to fix this error. If the requested URL has an index outside the list’s range, the user will receive a 404 Not Found error, which is an HTTP error that tells the user the page they are looking for does not exist.

      Open your app.py file for editing:

      To respond with an HTTP 404 error, you will need Flask’s abort() function, which can be used to make HTTP error responses. Change the second line in the file to also import this function:

      flask_app/app.py

      from markupsafe import escape
      from flask import Flask, abort
      

      Then edit the greet_user() view function to look as follows:

      flask_app/app.py

      # ...
      
      @app.route('/users/<int:user_id>/')
      def greet_user(user_id):
          users = ['Bob', 'Jane', 'Adam']
          try:
              return '<h2>Hi {}</h2>'.format(users[user_id])
          except IndexError:
              abort(404)
      

      You use try above to test the return expression for errors. If there was no error, meaning that user_id has a value that matches an index in the users list, the application will respond with the appropriate greeting. If the value of user_id is outside the list’s range, an IndexError exception will be raised, and you use except to catch the error and respond with an HTTP 404 error using the abort() Flask helper function.

      Now, with the development server running, visit the URL again:

      http://127.0.0.1:5000/users/3
      

      This time you’ll see a standard 404 error page informing the user that the page does not exist.

      By the end of this tutorial, your app.py file will look like this:

      flask_app/app.py

      from markupsafe import escape
      from flask import Flask, abort
      
      app = Flask(__name__)
      
      
      @app.route('/')
      @app.route('/index/')
      def hello():
          return '<h1>Hello, World!</h1>'
      
      
      @app.route('/about/')
      def about():
          return '<h3>This is a Flask web application.</h3>'
      
      @app.route('/capitalize/<word>/')
      def capitalize(word):
          return '<h1>{}</h1>'.format(escape(word.capitalize()))
      
      @app.route('/add/<int:n1>/<int:n2>/')
      def add(n1, n2):
          return '<h1>{}</h1>'.format(n1 + n2)
      
      @app.route('/users/<int:user_id>/')
      def greet_user(user_id):
          users = ['Bob', 'Jane', 'Adam']
          try:
              return '<h2>Hi {}</h2>'.format(users[user_id])
          except IndexError:
              abort(404)
      

      You now have a general idea of how to use the Flask debugger to troubleshoot your errors and help you determine the appropriate course of action to fix them.

      Conclusion

      You now have a general understanding of what Flask is, how to install it, and how to use it to write a web application, how to run the development server, and how to use routes and view functions to display different web pages that serve specific purposes. You’ve also learned how to use dynamic routes to allow users to interact with your web application via the URL, and how to use the debugger to troubleshoot errors.

      If you would like to read more about Flask, check out the Flask topic page.



      Source link

      How To Develop a Docker Application on Windows using WSL, Visual Studio Code, and Docker Desktop


      Introduction

      The advent of the Windows Subsystem for Linux 2 (WSL 2 or WSL for short) has simplified Linux-based development on Windows. The WSL 2 allows for direct integration with Docker Desktop and has plugins for direct development using Visual Studio Code.

      In this tutorial you’ll set up a development environment on Windows using Visual Studio Code, the WSL, and Docker Desktop. You’ll build a Python Flask web service in Docker to demonstrate the development functionality of these tools.

      Prerequisites

      In order to follow along with this guide, you’ll need:

      • Personal Computer with Windows 10 and the WSL 2 installed: You’ll want to ensure that the WSL is installed correctly and that you have Ubuntu 20.04 installed into the WSL. You can follow the tutorial How To Install the Windows Subsystem for Linux 2 on Microsoft Windows 10 to set this up.

      • VSCode Installed: You can download and install VSCode from its official website. You do not need to worry about installing plugins. The required plugins will be discussed in this tutorial.

      Step 1 — Installing Docker Desktop and Connecting to the WSL

      Docker is a common development tool used by developers to deploy applications. Docker Desktop has the advantage of also being able to run and integrate with your WSL Linux environments.

      Set up Docker by downloading Docker Desktop from Docker’s website and clicking the Get Docker button to start the download.

      Go to Docker's website and download Docker Desktop

      Run the executable once you get it downloaded and allow it to make changes.

      Run the executable and let Docker make changes

      During the installation make sure that Install required Windows components for WSL 2 is checked. Whether or not you want a Desktop icon is up to you.

      Make sure that

      After the installation process is done you’ll be prompted to log out and back in for your changes to take effect. Click on the Close button and then make sure to log out and back in so that the changes take effect.

      Once Docker is done installing you'll need to logout and log back in for changes to take effect

      Log back in and launch Docker Desktop from the Start menu.

      Launch Docker Desktop from the start menu

      Warning: When you first launch Docker it will prompt you with a Docker tutorial.

      Docker Tutorial Launched

      If you are unfamiliar with Docker it may be worth your time to do the Docker tutorial, but it is not required for this current tutorial. Once you have either done the tutorial or skipped it, continue on.

      The Docker dashboard will show up. This is where any running containers will appear as well as settings and status of Docker. If you see the logo is green in the bottom left corner that means that Docker is running. If it is yellow then Docker Desktop is still starting; give it a minute or so to finish. If the indicator is red, then Docker is unable to start.

      The Docker dashboard will open. If the logo in the bottom left is green it means Docker is running

      Next you’ll need to expose Docker to the WSL so you can run Docker on your Ubuntu environment. Click on the Gear icon in the top right corner to open Settings. From there you’ll click the Resource tab and then click WSL Integration. You’ll see your Ubuntu environment there, but toggled off, along with any other WSL environments you may have installed.

      Go to Settings, select Resources, and select WSL Integration. You'll see your WSL Ubuntu there, not selected

      Enable Docker in your Ubuntu environment by clicking on the slider to turn it on, and then click Apply & Restart. Once the restart is done your Ubuntu environment will have access to Docker.

      Select your WSL Ubuntu and click Apply & Restart

      Now you can test your Docker connectivity with the WSL. Open a terminal to the operating system you enabled Docker in, Ubuntu in this case, and run the Docker hello world command:

      Your Ubuntu environment should download and run the hello world container and display its output.

      Test Docker by running Docker run hello-world in your WSL Ubuntu

      Now that you have Docker connected to the WSL you’ll learn how to develop within the WSL directly using Visual Studio Code and the Remote Development Extension.

      Step 2 — Using Visual Studio Code’s Remote Extension to Develop within the WSL

      You can integrate your WSL Ubuntu environment with your Visual Studio Code, henceforth known as VSCode, to be able to develop directly in a Linux environment.

      First, open VSCode. Go to the Extensions tab on the left hand side of the window. Search for Remote - WSL and the Remote - WSL extension will appear. Click on it and click Install to install it.

      Open VSCode, go to Extensions and search for Remote. Install the Remote - WSL Extension

      Once the installation is completed, press CTRL + Shift + P to open the VSCode command dialog. Type Remote-WSL and you’ll see a few options appear. You can open a new WSL environment, open an existing folder, etc. Select Remote-WSL: New WSL Window. This will open a new VSCode window connected to the Ubuntu WSL environment.

      Press CTRL + Shift + P to open the VSCode command dialog and type Remote. You'll see WSL there. Select Remote-WSL: New WSL Window

      Now that you’re in this new window you can press CTRL + Shift + ` or by clicking on Terminal -> New Terminal in the navigation bar to open up a new terminal and you’ll be dropped into the WSL terminal. Any file you create will be stored in the WSL filesystem as well.

      If you open a new terminal you'll open your Ubuntu terminal and be able to develop using VSCode directly in the WSL

      Now that you have your development environment set up, you’ll build a Python microservice using the Flask framework that creates a 301 redirect to a site that you specify as an environment variable and package it within a Docker container.

      Step 3 — Setting Up Your Developer Environment

      First you’ll want to set up a development environment so you can develop your code using Visual Studio Code. Navigate to the sidebar on the left hand side and click on the topmost icon that looks like a sheet of paper. You will be prompted to either Open a Folder or Clone a Repository.

      File explorer dialog box open

      From here select Open a Folder. The default location will be your home directory. Select this option and click OK.

      Open home directory

      You may be prompted by Visual Studio Code asking if you trust the authors of this folder. This is a security measure to ensure that no automatically executed code can harm your PC. In this case, everything is good so select Yes, I trust the authors.

      Author Trust Dialog box

      Now you should see your home directory in the file explorer panel to the left. Next, create a directory to store your project. Navigate to the folder icon with a plus symbol. When you hover over the icon a popup should appear saying New Folder. Click on this icon to create a new folder and name it my-app. A new empty directory should appear in the explorer to the right.

      New Folder Icon
      You now have your developer environment set up and ready to build your Python microservice in the next step.

      Step 4 — Creating a Python Virtual Environment for Your Project

      Before you get started coding, you need to set up your Python developer environment. In this step, you will install and activate your Python requirements within a virtual environment for easier management.

      You can do all of this from within the terminal in Visual Studio Code. Press the CTRL + Shift + ` key combo to open a new terminal or click on New Terminal under the Terminal section in the top navigation bar. Once you’ve done this you should see a new terminal appear at the bottom of the Visual Studio Code window.

      New terminal in Visual Studio Code

      From this terminal navigate into the directory you created for you code, my-app.

      Next, install the python3-venv Ubuntu package so you can create Python virtual environments.

      • sudo apt update && sudo apt install python3-venv

      Now create your virtual environment using Python:

      This will create a directory called myapp in your current directory. Inside, it will install a local version of Python and a local version of pip, the package manager for Python. You can use this to install and configure an isolated Python environment for your project.

      Before you install your project’s Python requirements, activate the virtual environment:

      • source myapp/bin/activate

      Your prompt should change to indicate that you are now operating within a Python virtual environment. It will look something like this: (myapp)user@host:~/my-app$.

      With your virtual environment active, install flask and gunicorn with the local instance of pip:

      • pip install flask gunicorn

      Note: Once you have activate your virtual environment (when your prompt has (myapp) preceding it), use pip instead of pip3, even if you are using Python 3. The virtual environment’s copy of the tool is always named pip, regardless of the Python version.

      Now that you have the packages installed, you will need to save this requirement and its dependencies. This is good practice so you can recreate your developer environment as needed and will aid in installing the correct packages into your Dockerfile in a later step.

      Use pip to save your environment’s information to a requirements.txt file:

      • pip freeze > requirements.txt

      Now that you have a working virtual environment for development, let’s build the microservice.

      Step 5 — Building a Python Microservice to Redirect Traffic

      The first thing you’ll need to do is create a Python file named app.py and a Dockerfile to specify your Docker requirements. You can create files via the terminal with the touch command and then refreshing the explorer:

      You can also use the file explorer to create a new file by clicking on your my-app folder, then clicking on the New File icon that looks like a piece of paper with a plus sign, then typing out the full name and extension of the file.

      Create your app.py

      Use either method to create app.py and Dockerfile.

      Once you’ve done this, open app.py. The microservice you are going to write today will have only one endpoint, as defined by the @app.route("/") decorator. This endpoint will use the redirect method within the Flask library to perform a 301 redirect to a site that is specified in an environment variable. If no environment variable is set, the app will redirect to DigitalOcean’s website by default.

      Open app.py by clicking on it and add the following lines of code.

      Add an import statement to import the os package, which will enable the microservice to read the environment variable you’ll define later:

      import os
      

      Next, import the Flask class and redirect function from the flask library. You’ll use these to set up your web framework and to redirect traffic to another site.

      from flask import Flask,redirect
      

      Next, create a Flask object that can be acted upon within the code. This is the instance of your web app that you will register routes to.

      app = Flask(__name__)
      

      Create a single method at the / route. You’ll use your Flask instance to decorate the function to specify the route. Within the function, you will use the Flask redirect function to perform a 301 redirect to another site that will be read from an environment variable. If the environment variable is not found, your app will default redirect to DigitalOcean’s home page. This is to ensure your app doesn’t crash if you forget to set an environment variable.

      @app.route('/')
      def hello():
          # Attempt to read REDIRECT_TO from the environment. If nothing is set
          # perform a 301 redirect to DigitalOcean's website
          return redirect(os.environ.get("REDIRECT_TO", "https://www.digitalocean.com"), code=301)
      

      Finally, create a main function that runs your Flask app externally on port 8080. The address 0.0.0.0 is used to designate that you want your app to run on the externally facing network interface of your device, not the local loopback device, also known as localhost.

      if __name__ == '__main__':
          app.run(host="0.0.0.0", port=8080)
      

      The finished app.py can be found below:

      # Import the os package to read the environment variable
      import os
      
      # Import the Flask class and redirect function from the flask library
      from flask import Flask,redirect
      
      
      # Create a Flask object to be acted upon
      app = Flask(__name__)
      
      # Python decorator that specifies the web route that will execute the code below
      @app.route('/')
      def hello():
          # Attempt to read REDIRECT_TO from the environment. If nothing is set
          # perform a 301 redirect to DigitalOcean's website
          return redirect(os.environ.get("REDIRECT_TO", "https://www.digitalocean.com"), code=301)
      
      # Main function that executes the Flask app
      if __name__ == '__main__':
          app.run(host="0.0.0.0", port=8080)
      

      Once you are done, save the file as app.py.

      Now that your app is written, let’s test it.

      Step 6 — Testing Your Microservice

      Now that your app is written, it is time to test it. In the terminal you opened in Visual Studio Code with the activated virtual environment, run the command:

      You should see Flask output that looks similar to this:

      Output

      * Serving Flask app 'app' (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 all addresses. * WARNING: This is a development server. Do not use it in a production deployment. * Running on https://256.333.112.1:8080/ (Press CTRL+C to quit)

      This means that your Flask app is running. Open a browser and navigate to localhost:8080. When you do you should see output happen in your terminal and be redirected to DigitalOcean’s website. This is because you have not specified anywhere for your Flask app to redirect to, so it is using the default.

      To stop your Flask app, click in the Visual Studio Code window to ensure it is active and then press CTRL+C. You’ll see the prompt stop and you’ll be presented with your terminal again.

      Next, run the following command to set your redirect to something else.

      • REDIRECT_TO="https://digitalocean.com/community/tutorials"

      Run your Flask app again using the command

      Go to your browser again and navigate to localhost:8080. You should then be directed to the DigitalOcean tutorials page.

      Note: If you plan on testing multiples redirects with the same container, you may want to use a form of incognito mode. Most modern browsers will cache a 301 redirect, so if you change the environment variable, you may end up at the same site and not see your changes reflected. Using an incognito window or clearing your cache will help with this.

      With this, your app is done and is ready to be built into a Docker image.

      Step 7 — Building and Running Your Microservice in Docker

      In this final step you’re going to package your Python app as a microservice using Docker and a Dockerfile. A Dockerfile is a list of build commands that Docker uses to create your image. These can be commands to install packages, copy files, and more.

      Open the Dockerfile you created in a previous step so you can edit it. In this file you’re going to specify the base image, tell Docker where you want the code to run, create an environment variable that holds the redirect target, copy over all the necessary files to the Docker image, install the necessary Python packages, and finally add the command that will be executed when the container is run.

      Add the following code to Dockerfile to do this.

      First, you need to specify the base image you want to use. The python base image will contain the latest version of Python.

      FROM python 
      

      Next, set your working directory. This is the default directory that Docker will run commands in and drop you into if you connect with ssh.

      WORKDIR /var/www/
      

      Set the REDIRECT_TO environment variable to the default location you want to redirect to. Here I’m setting it to DigitalOcean’s Community Tutorial site. This can be changed when you run the image via the command line.

      ENV REDIRECT_TO=https://digitalocean.com/community/tutorials
      

      Copy your app.py and requirements.txt into your Docker container, using fully qualified paths for the destination.

      COPY ./app.py /var/www/app.py
      COPY ./requirements.txt /var/www/requirements.txt
      

      Run the necessary command to install the Python library requirements within your Docker image.

      RUN pip install -r /var/www/requirements.txt
      

      Finally, set the image run command to run your app. This is the command that is run whenever anyone tries to run your Docker container.

      CMD python3 app.py
      

      The complete Dockerfile is listed below.

      # Choose your base image
      FROM python 
      
      # Set your working directory
      WORKDIR /var/www/
      
      # Set environment variable for redirect. Can be overwritten by Docker run command
      ENV REDIRECT_TO=https://digitalocean.com/community/tutorials
      
      # Copy the necessary files
      COPY ./app.py /var/www/app.py
      COPY ./requirements.txt /var/www/requirements.txt
      
      # Install the necessary packages
      RUN pip install -r /var/www/requirements.txt
      
      # Run the app
      CMD python3 app.py
      

      When you are done, save the file.

      Now you can build the Docker image locally for testing. Run the following command to build your image and tag it with the name myapp. The -t option applies the tag to the Docker image:

      Finally, it’s time to test your Docker image. In your Dockerfile above you set an environment variable REDIRECT_TO to point at a website. This will overwrite the default value in your code so when you run this container, whatever site you specified in the Dockerfile will be your new location.

      Note: If you are prompted by windows to grant permission to Docker to access the network, click Allow.

      To test your image, run the following command:

      • docker run -p 8080:8080 myapp

      While your image is running, navigate to a browser and type localhost:8080 in the navigation bar and you should be redirected to the site listed in the Dockerfile.

      Warning: Sometimes the WSL terminal doesn’t recognize CTRL + C as a way to stop your Docker image. In this instance you’ll need to open another terminal and search for your running Docker image using the command:

      This will show an output similar to this:

      Output

      CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 3f081712283e myapp "/bin/sh -c 'python3…" About a minute ago Up About a minute 0.0.0.0:8080->8080/tcp, :::8080->8080/tcp reverent_saha

      Take the container id, which in this example is 3f081712283e and use the docker kill command to stop it.

      Finally, let’s test changing the environment variable of the redirect in the docker run command.

      Type the following command to change the environment variable to the DigitalOcean cloud console page, https://cloud.digitalocean.com.

      • docker run -p 8080:8080 -e REDIRECT_TO=https://cloud.digitalocean.com myapp

      Now if you go to a browser and browse to localhost:8080 you will be redirected to the site specified on the command line.

      Conclusion

      You have successfully set up a developer environment on Windows using the WSL, Visual Studio Code, and Docker Desktop. You’ve demonstrated how to build, test, and package code on Windows, allowing you to have more options when it comes to developer environments.



      Source link