One place for hosting & domains

      Web

      How To Use and Validate Web Forms with Flask-WTF


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

      Introduction

      Web forms, such as text fields and text areas, give users the ability to send data to your application, whether that’s a drop-down or a radio button that the application will use to perform an action, or to send large areas of text to be processed or displayed. For example, in a social media application, you might give users a box where they can add new content to their pages.

      Flask is a lightweight Python web framework that provides useful tools and features for creating web applications in the Python Language. To render and validate web forms in a safe and flexible way in Flask, you’ll use Flask-WTF, which is a Flask extension that helps you use the WTForms library in your Flask application.

      WTForms is a Python library that provides flexible web form rendering. You can use it to render text fields, text areas, password fields, radio buttons, and others. WTForms also provides powerful data validation using different validators, which validate that the data the user submits meets certain criteria you define. For example, if you have a required field, you can ensure data the user submits is provided, or has a certain length.

      WTForms also uses a CSRF token to provide protection from CSRF attacks, which are attacks that allows the attacker to execute unwanted actions on a web application in which the user is authenticated. A successful CSRF attack can force the user to perform state-changing requests like transferring funds to the attacker’s bank account in a banking application, changing the user’s email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.

      In this tutorial, you’ll build a small web application that demonstrates how to render and validate web forms using Flask-WTF. The application will have a page for displaying courses that are stored in a Python list, and the index page will have a form for entering the course title, its description, price, availability, and level (beginner, intermediate, or advanced).

      Prerequisites

      Step 1 — Installing Flask and Flask-WTF

      In this step, you’ll install Flask and Flask-WTF, which also installs the WTForms library automatically.

      With your virtual environment activated, use pip to install Flask and Flask-WTF:

      • pip install Flask Flask-WTF

      Once the installation is successfully finished, you’ll see a line similar to the following at the end of the output:

      Output

      Successfully installed Flask-2.0.2 Flask-WTF-1.0.0 Jinja2-3.0.3 MarkupSafe-2.0.1 WTForms-3.0.0 Werkzeug-2.0.2 click-8.0.3 itsdangerous-2.0.1

      As you can see, the WTForms library was also installed as a dependency of the Flask-WTF package. The rest of the packages are Flask dependencies.

      Now that you’ve installed the required Python packages, you’ll set up a web form next.

      Step 2 — Setting up Forms

      In this step, you’ll set up a web form using fields and validators you’ll import from the WTForms library.

      You’ll set up the following fields:

      • Title: A text input field for the course title.
      • Description: A text area field for the course description.
      • Price: An integer field for the price of the course.
      • Level: A radio field for the course level with three choices: Beginner, Intermediate, and Advanced.
      • Available: A checkbox field that indicates whether the course is currently available.

      First, open a new file called forms.py in your flask_app directory. This file will have the forms you’ll need in your application:

      This file will have a class that represents your web form. Add the following imports at the top:

      flask_app/forms.py

      from flask_wtf import FlaskForm
      from wtforms import (StringField, TextAreaField, IntegerField, BooleanField,
                           RadioField)
      from wtforms.validators import InputRequired, Length
      
      

      To build a web form, you will create a subclass of the FlaskForm base class, which you import from the flask_wtf package. You also need to specify the fields you use in your form, which you will import from the wtforms package.

      You import the following fields from the WTForms library:

      In the line from wtforms.validators import InputRequired, Length, you import validators to use on the fields to make sure the user submits valid data. InputRequired is a validator you’ll use to ensure the input is provided, and Length is for validating the length of a string to ensure it has a minimum number of characters, or that it doesn’t exceed a certain length.

      Next, add the following class after the import statements:

      flask_app/forms.py

      
      class CourseForm(FlaskForm):
          title = StringField('Title', validators=[InputRequired(),
                                                   Length(min=10, max=100)])
          description = TextAreaField('Course Description',
                                      validators=[InputRequired(),
                                                  Length(max=200)])
          price = IntegerField('Price', validators=[InputRequired()])
          level = RadioField('Level',
                             choices=['Beginner', 'Intermediate', 'Advanced'],
                             validators=[InputRequired()])
          available = BooleanField('Available', default="checked")
      

      Save and close the file.

      In this CourseForm class, you inherit from the FlaskForm base class you imported earlier. You define a collection of form fields as class variables using the form fields you imported from the WTForms library. When you instantiate a field, the first argument is the field’s label.

      You define the validators for each field by passing a list of the validators you import from the wtforms.validators module. The title field, for example, has the string 'Title' as a label, and two validators:

      • InputRequired: To indicate that the field should not be empty.
      • Length: Takes two arguments; min is set to 10 to make sure that the title is at least 10 characters long, and max is set to 100 to ensure it doesn’t exceed 100 characters.

      The description text area field has an InputRequired validator and a Length validator with the max parameter set to 200, with no value for the min parameter, which means the only requirement is that it doesn’t exceed 200 characters.

      Similarly you define a required integer field for the price of the course called price.

      The level field is a radio field with multiple choices. You define the choices in a Python list and pass it to the choices parameter. You also define the field as required using the InputRequired validator.

      The available field is a check box field. You set a default 'checked' value by passing it to the default parameter. This means the check box will be checked when adding new courses unless the user unchecks it, meaning courses are available by default.

      For more on how to use the WTForms library, see the Crash Course page on the WTForms documentation. See the Fields page for more fields, and the Validators page for more validators to validate form data.

      You’ve configured your web form in a forms.py file. Next, you’ll create a Flask application, import this form, and display its fields on the index page. You’ll also display a list of courses on another page.

      Step 3 — Displaying the Web Form and Courses

      In this step, you’ll create a Flask application, display the web form you created in the previous step on the index page, and also create a list of courses and a page for displaying the courses on it.

      With your programming environment activated and Flask installed, open a file called app.py for editing inside your flask_app directory:

      This file will import the necessary class and helpers from Flask, and the CourseForm from the forms.py file. You’ll build a list of courses, then instantiate the form and pass it to a template file. Add the following code to app.py:

      flask_app/app.py

      from flask import Flask, render_template, redirect, url_for
      from forms import CourseForm
      
      app = Flask(__name__)
      app.config['SECRET_KEY'] = "https://www.digitalocean.com/community/tutorials/your secret key'
      
      
      courses_list = [{
          'title': 'Python 101',
          'description': 'Learn Python basics',
          'price': 34,
          'available': True,
          'level': 'Beginner'
          }]
      
      
      @app.route('/', methods=('GET', 'POST'))
      def index():
          form = CourseForm()
          return render_template('index.html', form=form)
      

      Save and close the file.

      Here you import the following from Flask:

      • The Flask class to create a Flask application instance.
      • The render_template() function to render the index template.
      • The redirect() function to redirect the user to the courses page once a new course is added.
      • The url_for() function for building URLs.

      First you import the CourseForm() class from the forms.py file, then you create a Flask application instance called app.

      You set up a secret key configuration for WTForms to use when generating a CSRF token to secure your web forms. The secret key should be a long random string. See Step 3 of How To Use Web Forms in a Flask Application for more information on how to obtain a secret key.

      Then you create a list of dictionaries called courses_list, which currently has one dictionary with a sample course titled 'Python 101'. Here, you use a Python list as a data store for demonstration purposes. In a real world scenario, you’ll use a database such as SQLite. See How To Use an SQLite Database in a Flask Application to learn how to use a database to store your courses’ data.

      You create a / main route using the app.route() decorator on the index() view function. It accepts both GET and POST HTTP methods in the methods parameter. GET methods are for retrieving data, and POST requests are for sending data to the server, through a web form for example. For more, see How To Use Web Forms in a Flask Application.

      You instantiate the CourseForm() class that represents the web form and save the instance in a variable called form. You then return a call to the render_template() function, passing it a template file called index.html and the form instance.

      To display the web form on the index page, you will first create a base template, which will have all the basic HTML code other templates will also use to avoid code repetition. Then you’ll create the index.html template file you rendered in your index() function. To learn more about templates, see How to Use Templates in a Flask Application.

      Create a templates folder in your flask_app directory where Flask searches for templates, then open a template file called base.html, which will be the base template for other templates:

      • mkdir templates
      • nano templates/base.html

      Add the following code inside the base.html file to create the base template with a navbar and a content block:

      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('index') }}">FlaskApp</a>
              <a href="#">About</a>
          </nav>
          <hr>
          <div class="content">
              {% block content %} {% endblock %}
          </div>
      </body>
      </html>
      

      This base template has all the HTML boilerplate you’ll need to reuse in your other templates. The title block will be replaced to set a title for each page, and the content block will be replaced with the content of each page. The navigation bar has two links, one for the index page where you use the url_for() helper function to link to the index() view function, and the other for an About page if you choose to include one in your application.

      Save and close the file.

      Next, open a template called index.html. This is the template you referenced in the app.py file:

      • nano templates/index.html

      This file will have the web form you passed to the index.html template via the form variable. Add the following code to it:

      flask_app/templates/index.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Add a New Course {% endblock %}</h1>
      
          <form method="POST" action="/">
              {{ form.csrf_token }}
              <p>
                  {{ form.title.label }}
                  {{ form.title(size=20) }}
              </p>
      
              {% if form.title.errors %}
                  <ul class="errors">
                      {% for error in form.title.errors %}
                          <li>{{ error }}</li>
                      {% endfor %}
                  </ul>
              {% endif %}
      
              <p>
                  {{ form.description.label }}
              </p>
              {{ form.description(rows=10, cols=50) }}
      
              {% if form.description.errors %}
                  <ul class="errors">
                      {% for error in form.description.errors %}
                          <li>{{ error }}</li>
                      {% endfor %}
                  </ul>
              {% endif %}
      
              <p>
                  {{ form.price.label }}
                  {{ form.price() }}
              </p>
      
              {% if form.price.errors %}
                  <ul class="errors">
                      {% for error in form.price.errors %}
                          <li>{{ error }}</li>
                      {% endfor %}
                  </ul>
              {% endif %}
      
              <p>
                  {{ form.available() }} {{ form.available.label }}
              </p>
      
              {% if form.available.errors %}
                  <ul class="errors">
                      {% for error in form.available.errors %}
                          <li>{{ error }}</li>
                      {% endfor %}
                  </ul>
              {% endif %}
      
              <p>
                  {{ form.level.label }}
                  {{ form.level() }}
              </p>
      
              {% if form.level.errors %}
                  <ul class="errors">
                      {% for error in form.level.errors %}
                          <li>{{ error }}</li>
                      {% endfor %}
                  </ul>
              {% endif %}
      
              <p>
                  <input type="submit" value="Add">
              </p>
          </form>
      
      {% endblock %}
      

      Save and close the file.

      You extend the base template, and set a title in an <h1> tag. Then you render the web form fields inside a <form> tag, setting its method to POST and the action to the / main route, which is the index page. You first render the CSRF token WTForms uses to protect your form from CSRF attacks using the line {{ form.csrf_token }}. This token gets sent to the server with the rest of the form data. Remember to always render this token to secure your forms.

      You render each field using the syntax form.field() and you render its label using the syntax form.field.label. You can pass arguments to the field to control how it is displayed. For example, you set the size of the title input field in {{ form.title(size=20) }}, and you set the numbers of rows and columns for the description text area via the parameters rows and cols the same way you would do normally in HTML. You can use the same method to pass additional HTML attributes to a field such as the class attribute to set a CSS class.

      You check for validation errors using the syntax if form.field.errors. If a field has errors, you loop through them with a for loop and display them in a list below the field.

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

      • export FLASK_APP=app
      • export FLASK_ENV=development

      Next, run the application:

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

      http://127.0.0.1:5000/
      

      You’ll see the web form displayed on the index page:

      Index Page

      Try to submit the form without filling in the title. You’ll see an error message informing you that the title is required. Experiment with the form by submitting invalid data (such as a short title less than 10 characters long, or a description over 200 characters long) to see other error messages.

      Filling the form with valid data does nothing so far because you don’t have code that handles form submission. You’ll add the code for that later.

      For now, you need a page to display the courses you have in your list. Later, handling the web form data will add a new course to the list and redirect the user to the courses page to see the new course added to it.

      Leave the development server running and open another terminal window.

      Next, open app.py to add the courses route:

      Add the following route at the end of the file:

      flask_app/app.py

      # ...
      
      @app.route('/courses/')
      def courses():
          return render_template('courses.html', courses_list=courses_list)
      

      Save and close the file.

      This route renders a template called courses.html, passing it the courses_list list.

      Then create the courses.html template to display courses:

      • nano templates/courses.html

      Add the following code to it:

      flask_app/templates/courses.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Courses {% endblock %}</h1>
          <hr>
          {% for course in courses_list %}
              <h2> {{ course['title'] }} </h2>
              <h4> {{ course['description'] }} </h4>
              <p> {{ course['price'] }}$ </p>
              <p><i>({{ course['level'] }})</i></p>
              <p>Availability:
                  {% if course['available'] %}
                      Available
                  {% else %}
                      Not Available
                  {% endif %}</p>
              <hr>
          {% endfor %}
      {% endblock %}
      

      Save and close the file.

      You set a title and loop through the items of the courses_list list. You display the title in an <h2> tag, the description in an <h4> tag, and the price and course level in a <p> tag.
      You check whether the course is available using the condition if course['available']. You display the text “Available” if the course is available, and the text “Not Available” if it’s not available.

      Use your browser to go to the courses page:

      http://127.0.0.1:5000/courses/
      

      You’ll see a page with one course displayed, because you only have one course in your course list so far:

      Courses Page

      Next, open base.html to add a link to the courses page in the navigation bar:

      Edit it 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("index') }}">FlaskApp</a>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for("courses') }}">Courses</a>
              <a href="#">About</a>
          </nav>
          <hr>
          <div class="content">
              {% block content %} {% endblock %}
          </div>
      </body>
      </html>
      

      Save and close the file.

      Refresh the index page, and you’ll see a new Courses link in the navigation bar.

      You’ve created the pages you need for your application: An index page with a web form for adding new courses and a page for displaying the courses you have in your list.

      To make the application functional, you need to handle the web form data when the user submits it by validating it and adding it to the courses list. You’ll do this next.

      Step 4 — Accessing Form Data

      In this step, you’ll access data the user submits, validate it, and add it to the list of courses.

      Open app.py to add code for handling the web form data inside the index() function:

      Edit the index() function to look as follows:

      flask_app/app.py

      # ...
      @app.route('/', methods=('GET', 'POST'))
      def index():
          form = CourseForm()
          if form.validate_on_submit():
              courses_list.append({'title': form.title.data,
                                   'description': form.description.data,
                                   'price': form.price.data,
                                   'available': form.available.data,
                                   'level': form.level.data
                                   })
              return redirect(url_for('courses'))
          return render_template('index.html', form=form)
      

      Save and close the file.
      Here, you call the validate_on_submit() method on the form object, which checks that the request is a POST request, and runs the validators you configured for each field. If at least one validator returns an error, the condition will be False, and each error will be displayed below the field that caused it.

      If the submitted form data is valid, the condition is True, and the code below the if statement will be executed. You build a course dictionary, and use the append method to add the new course to the courses_list list. You access the value of each field using the syntax form.field.data. After you add the new course dictionary to the courses list, you redirect the user to the Courses page.

      With the development server running, visit the index page:

      http://127.0.0.1:5000/
      

      Fill the form with valid data and submit it. You’ll be redirected to the Courses page, and you’ll see the new course displayed on it.

      Conclusion

      You made a Flask application that has a web form you built using the Flask-WTF extension and the WTForms library. The form has several types of fields to receive data from the user, validate it using special WTForms validators, and add it to a data store.

      If you would like to read more about Flask, check out the other tutorials in the How To Create Web Sites with Flask series.



      Source link

      How To Move an Nginx Web Root to a New Location on Ubuntu 20.04


      Introduction

      On Ubuntu, the Nginx web server stores its documents in /var/www/html, which is typically located on the root filesystem with the rest of the operating system. Sometimes, though, it’s helpful to move the document root to another location, such as a separate mounted filesystem. For example, if you serve multiple websites from the same Nginx instance, putting each site’s document root on its own volume allows you to scale in response to the needs of a specific site or client.

      In this guide, you will move an Nginx document root to a new location.

      Prerequisites

      To complete this guide, you will need:

      We will use the domain name your_domain in this tutorial, but you should substitute this with your own domain name.

      • A new location for your document root. In this tutorial, we will use the /mnt/volume-nyc3-01 directory for our new location. If you are using Block Storage on DigitalOcean, this guide will show you how to create and attach your volume. Your new document root location is configurable based on your needs, however. If you are moving your document root to a different storage device, you will want to select a location under the device’s mount point.

      Step 1 — Copying Files to the New Location

      On a fresh installation of Nginx, the document root is located at /var/www/html. By following the prerequisite guides, however, you created a new document root, /var/www/your_domain/html. You may have additional document roots as well. In this step, we will establish the location of our document roots and copy the relevant files to their new location.

      You can search for the location of your document roots using grep. Let’s search in the /etc/nginx/sites-enabled directory to limit our focus to active sites. The -R flag ensures that grep will print both the line with the root directive and the full filename in its output:

      • grep -R "root" /etc/nginx/sites-enabled

      If you followed the prerequisite tutorials on a fresh server, the result will look like this:

      Output

      /etc/nginx/sites-enabled/your_domain: root /var/www/your_domain/html; /etc/nginx/sites-enabled/default: root /var/www/html; /etc/nginx/sites-enabled/default: # deny access to .htaccess files, if Apache's document root /etc/nginx/sites-enabled/default:# root /var/www/your_domain;

      If you have pre-existing setups, your results may differ from what’s shown here. In either case, you can use the feedback from grep to make sure you’re moving the desired files and updating the appropriate configuration files.

      Now that you’ve confirmed the location of your document root, you can copy the files to their new location with rsync. Using the -a flag preserves the permissions and other directory properties, while -v provides verbose output so you can follow the progress of the sync:

      Note: Be sure there is no trailing slash on the directory, which may be added if you use tab completion. When there’s a trailing slash, rsync will dump the contents of the directory into the mount point instead of transferring it into a containing html directory.

      • sudo rsync -av /var/www/your_domain/html /mnt/volume-nyc3-01

      You will see output like the following:

      Output

      sending incremental file list created directory /mnt/volume-nyc3-01 html/ html/index.html sent 318 bytes received 39 bytes 714.00 bytes/sec total size is 176 speedup is 0.49

      With our files in place, let’s move on to modifying our Nginx configuration to reflect these changes.

      Step 2 — Updating the Configuration Files

      Nginx makes use of both global and site-specific configuration files. For background about the hierarchy of configuration files, take a look at “How To Configure The Nginx Web Server On a Virtual Private Server”. We will modify the server block file for our your_domain project: /etc/nginx/sites-enabled/your_domain.

      Note: Remember to replace your_domain with your domain name, and remember that you will be modifying the server block files that were output when you ran the grep command in Step 1.

      Start by opening /etc/nginx/sites-enabled/your_domain in an editor:

      • sudo nano /etc/nginx/sites-enabled/your_domain

      Find the line that begins with root and update it with the new root location. In our case this will be /mnt/volume-nyc3-01/html:

      /etc/nginx/sites-enabled/your_domain

      server {
      
              root /mnt/volume-nyc3-01/html;
              index index.html index.htm index.nginx-debian.html;
              . . .
      }
      . . .
      

      Keep an eye out for any other places that you see the original document root path outputted by grep in Step 1, including in aliases or rewrites. You will also want to update these to reflect the new document root location.

      When you’ve made all of the necessary changes, save and close the file.

      Step 3 — Restarting Nginx

      Once you’ve finished making the configuration changes, you can restart Nginx and test the results.

      First, make sure the syntax is correct:

      If everything is in order, it should return:

      Output

      nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

      If the test fails, track down and fix the problems.

      Once the test passes, restart Nginx:

      • sudo systemctl restart nginx

      When the server has restarted, visit your affected sites and ensure they’re working as expected. Once you’re comfortable that everything is in order, don’t forget to remove the original copy of the data:

      • sudo rm -Rf /var/www/your_domain/html

      You have now successfully moved your Nginx document root to a new location.

      Conclusion

      In this tutorial, we covered how to change the Nginx document root to a new location. This can help you with basic web server administration, like effectively managing multiple sites on a single server. It also allows you to take advantage of alternative storage devices such as network block storage, which can be helpful in scaling a web site as its needs change.

      If you’re managing a busy or growing web site, you might be interested in learning how to set up Nginx with HTTP/2 to take advantage of its high transfer speed for content.



      Source link

      How To Use Web Forms 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

      Web forms, such as text fields and text areas, give users the ability to send data to your application to use it to perform an action, or to send larger areas of text to the application. For example, in a social media application, you might give users a box where they can add new content to their pages. Another example is a login page, where you would give the user a text field to enter their username and a password field to enter their password. The server (your Flask application in this case) uses the data the user submits and either signs them in if the data is valid, or responds with a message like Invalid credentials! to inform the user that the data they submitted is not correct.

      Flask is a lightweight Python web framework that provides useful tools and features for creating web applications in the Python Language. In this tutorial, you’ll build a small web application that demonstrates how to use web forms. The application will have a page for displaying messages that are stored in a Python list, and a page for adding new messages. You’ll also use message flashing to inform users of an error when they submit invalid data.

      Prerequisites

      Step 1 — Displaying Messages

      In this step, you’ll create a Flask application with an index page for displaying messages that are stored in a list of Python dictionaries.

      First open a new file called app.py for editing:

      Add the following code inside the app.py file to create a Flask server with a single route:

      flask_app/app.py

      from flask import Flask, render_template
      
      app = Flask(__name__)
      
      messages = [{'title': 'Message One',
                   'content': 'Message One Content'},
                  {'title': 'Message Two',
                   'content': 'Message Two Content'}
                  ]
      
      @app.route('/')
      def index():
          return render_template('index.html', messages=messages)
      

      Save and close the file.

      In this file, you first import the Flask class and the render_template() function from the flask package. You then use the Flask class to create a new application instance called app, passing the special __name__ variable, which is needed for Flask to set up some paths behind the scenes. Rendering templates is covered in the tutorial How To Use Templates in a Flask Application.

      You then create a global Python list called messages, which has Python dictionaries inside it. Each dictionary has two keys: title for the title of the message, and content for the message content. This is a simplified example of a data storage method; in a real-world scenario, you’d use a database that permanently saves the data and allows you to manipulate it more efficiently.

      After creating the Python list, you use the @app.route() decorator to create a view function called index(). In it, you return a call to the render_template() function, which indicates to Flask that the route should display an HTML template. You name this template index.html (you’ll create it later), and you pass a variable called messages to it. This variable holds the messages list you previously declared as a value and makes it available to the HTML template. View functions are covered in the tutorial How To Create Your First Web Application Using Flask and Python 3.

      Next, create a templates folder in your flask_app directory where Flask searches for templates, then open a template file called base.html, which will have code that other templates will inherit to avoid code repetition:

      • mkdir templates
      • nano templates/base.html

      Add the following code inside the base.html file to create the base template with a navbar and a content block:

      flask_app/templates/base.html

      
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>{% block title %} {% endblock %} - FlaskApp</title>
          <style>
              .message {
                  padding: 10px;
                  margin: 5px;
                  background-color: #f3f3f3
              }
              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('index') }}">FlaskApp</a>
              <a href="#">About</a>
          </nav>
          <hr>
          <div class="content">
              {% block content %} {% endblock %}
          </div>
      </body>
      </html>
      

      Save and close the file.

      This base template has all the HTML boilerplate you’ll need to reuse in your other templates. The title block will be replaced to set a title for each page, and the content block will be replaced with the content of each page. The navigation bar has two links, one for the index page where you use the url_for() helper function to link to the index() view function, and the other for an About page if you choose to include one in your application.

      Next, open a template called index.html. This is the template you referenced in the app.py file:

      • nano templates/index.html

      Add the following code to it:

      flask_app/templates/index.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Messages {% endblock %}</h1>
          {% for message in messages %}
              <div class="message">
                  <h3>{{ message['title'] }}</h3>
                  <p>{{ message['content'] }}</p>
              </div>
          {% endfor %}
      {% endblock %}
      

      Save and close the file.

      In this code, you extend the base.html template and replace the contents of the content block. You use an <h1> heading that also serves as a title.

      You use a Jinja for loop in the line {% for message in messages %} to go through each message in the messages list. You use a <div> tag to contain the message’s title and content. You display the title in an <h3> heading and the content in a <p> tag.

      While in your flask_app directory with your virtual environment activated, tell Flask about the application (app.py in this case) using the FLASK_APP environment variable:

      Then set the FLASK_ENV environment variable to development to run the application in development mode and get access to the debugger. For more information about the Flask debugger, see How To Handle Errors in a Flask Application. Use the following commands to do this (on Windows, use set instead of export):

      • export FLASK_ENV=development

      Next, run the application:

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

      http://127.0.0.1:5000/
      

      You’ll see the messages in the messages list displayed on the index page:

      Index Page

      Now that you have set up your web application and displayed the messages, you’ll need a way to allow users to add new messages to the index page. This is done through web forms, which you’ll set up in the next step.

      Step 2 — Setting Up Forms

      In this step, you will create a page in your application that allows users to add new messages into the list of messages via a web form.

      Leave the development server running and open a new terminal window.

      First, open your app.py file:

      Add the following route to the end of the file:

      flask_app/app.py

      # ...
      
      @app.route('/create/', methods=('GET', 'POST'))
      def create():
          return render_template('create.html')
      

      Save and close the file.

      This /create route has the methods parameter with the tuple ('GET', 'POST') to accept both GET and POST requests. GET and POST are HTTP methods. By default, only GET requests are accepted, which are used to retrieve data, such as asking the server for an index page or an About page. POST requests are used to submit data to a specific route, which often changes the data on the server.

      In this example, you will ask for the create page using a GET request. The Create page will have a web form with input fields and a Submit button. When a user fills in the web form and clicks the Submit button, a POST request gets sent to the /create route. There you handle the request, validate the submitted data to ensure the user has not submitted an empty form, and add it to the messages list.

      The create() view function currently does only one thing: render a template called create.html when it receives a regular GET request. You will now create this template, then edit the function to handle POST requests in the next step.

      Open a new template file called create.html:

      • nano templates/create.html

      Add the following code to it:

      flask_app/templates/create.html

      {% extends 'base.html' %}
      
      {% block content %}
          <h1>{% block title %} Add a New Message {% endblock %}</h1>
          <form method="post">
              <label for="title">Title</label>
              <br>
              <input type="text" name="title"
                     placeholder="Message title"
                     value="https://www.digitalocean.com/community/tutorials/{{ request.form['title'] }}"></input>
              <br>
      
              <label for="content">Message Content</label>
              <br>
              <textarea name="content"
                        placeholder="Message content"
                        rows="15"
                        cols="60"
                        >{{ request.form['content'] }}</textarea>
              <br>
              <button type="submit">Submit</button>
          </form>
      {% endblock %}
      
      

      Save and close the file.

      In this code, you extend the base.html template and replace the content block with an <h1> heading that serves as a title for the page. In the <form> tag, you set the method attribute to post so the form data gets sent to the server as a POST request.

      In the form, you have a text input field named title; this is the name you’ll use on the application to access the title form data. You give the <input> tag a value of {{ request.form['title'] }}. This is useful to restore the data the user enters so it does not get lost when things go wrong. For example, if the user forgets to fill in the required content text area, a request gets sent to the server and an error message will come back as a response, but the data in the title will not be lost because it will be saved on the request global object, and can be accessed via request.form['title'].

      After the title input field, you add a text area named content with the value {{ request.form['content'] }} for the same reasons mentioned previously.

      Last, you have a Submit button at the end of the form.

      Now, with the development server running, use your browser to navigate to the /create route:

      http://127.0.0.1:5000/create
      

      You will see an “Add a New Message” page with an input field for a message title, a text area for the message’s content, and a Submit button.

      Add a new message

      This form submits a POST request to your create() view function. However, there is no code to handle a POST request in the function yet, so nothing happens after filling in the form and submitting it. In the next step, you’ll handle the incoming POST request when a form is submitted. You’ll check whether the submitted data is valid (not empty), and add the message title and content to the messages list.

      Step 3 — Handling Form Requests

      In this step, you will handle form requests on the application side. You’ll access the form data the user submits via the form you created in the previous step and add it to the list of messages. You’ll also use message flashing to inform users when they submit invalid data. The flash message will only be shown once and will disappear on the next request (if you navigate to another page for example).

      Open the app.py file for editing:

      First, you’ll import the following from the Flask framework:

      • The global request object to access incoming request data that will be submitted via the HTML form you built in the last step.
      • The url_for() function to generate URLs.
      • The flash() function to flash a message when a request is processed (to inform the user that everything went well, or to inform them of an issue if the submitted data is not valid).
      • The redirect() function to redirect the client to a different location.

      Add these imports to the first line in the file:

      flask_app/app.py

      from flask import Flask, render_template, request, url_for, flash, redirect
      
      # ...
      

      The flash() function stores flashed messages in the client’s browser session, which requires setting a secret key. This secret key is used to secure sessions, which allow Flask to remember information from one request to another, such as moving from the new message page to the index page. The user can access the information stored in the session, but cannot modify it unless they have the secret key, so you must never allow anyone to access your secret key. See the Flask documentation for sessions for more information.

      The secret key should be a long random string. You can generate a secret key using the os module with the os.urandom() method, which returns a string of random bytes suitable for cryptographic use. To get a random string using it, open a new terminal and open the Python interactive shell using the following command:

      In the Python interactive shell, import the os module from the standard library and call the os.urandom() method as follows:

      • import os
      • os.urandom(24).hex()

      You’ll get a string similar to the following:

      Output

      'df0331cefc6c2b9a5d0208a726a5d1c0fd37324feba25506'

      You can use the string you get as your secret key.

      To set the secret key, add a SECRET_KEY configuration to your application via the app.config object. Add it directly following the app definition before defining the messages variable:

      flask_app/app.py

      
      # ...
      app = Flask(__name__)
      app.config['SECRET_KEY'] = 'your secret key'
      
      
      messages = [{'title': 'Message One',
                   'content': 'Message One Content'},
                  {'title': 'Message Two',
                   'content': 'Message Two Content'}
                  ]
      # ...
      

      Next, modify the create() view function to look exactly as follows:

      flask_app/app.py

      # ...
      
      @app.route('/create/', methods=('GET', 'POST'))
      def create():
          if request.method == 'POST':
              title = request.form['title']
              content = request.form['content']
      
              if not title:
                  flash('Title is required!')
              elif not content:
                  flash('Content is required!')
              else:
                  messages.append({'title': title, 'content': content})
                  return redirect(url_for('index'))
      
          return render_template('create.html')
      

      In the if statement you ensure that the code following it is only executed when the request is a POST request via the comparison request.method == 'POST'.

      You then extract the submitted title and content from the request.form object that gives you access to the form data in the request. If the title is not provided, the condition if not title would be fulfilled. In that case, you display a message to the user informing them that the title is required using the flash() function. This adds the message to a flashed messages list. You will later display these messages on the page as part of the base.html template. Similarly, if the content is not provided, the condition elif not content will be fulfilled. If so, you add the 'Content is required!' message to the list of flashed messages.

      If the title and the content of the message are properly submitted, you use the line messages.append({'title': title, 'content': content}) to add a new dictionary to the messages list, with the title and content the user provided. Then you use the redirect() function to redirect users to the index page. You use the url_for() function to link to the index page.

      Save and close the file.

      Now, navigate to the /create route using your web browser:

      http://127.0.0.1:5000/create
      

      Fill in the form with a title of your choice and some content. Once you submit the form, you will see the new message listed on the index page.

      Lastly, you’ll display flashed messages and add a link for the “New Message” page to the navigation bar in the base.html template to have easy access to this new page. Open the base template file:

      Edit the file by adding a new <a> tag after the FlaskApp link in the navigation bar inside the <nav> tag. Then add a new for loop directly above the content block to display the flashed messages below the navigation bar. These messages are available in the special get_flashed_messages() function Flask provides. Then add a class attribute called alert to each message and give it some CSS properties inside the <style> tag:

      flask_app/templates/base.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>{% block title %} {% endblock %} - FlaskApp</title>
          <style>
              .message {
                  padding: 10px;
                  margin: 5px;
                  background-color: #f3f3f3
              }
              nav a {
                  color: #d64161;
                  font-size: 3em;
                  margin-left: 50px;
                  text-decoration: none;
              }
      
              .alert {
                  padding: 20px;
                  margin: 5px;
                  color: #970020;
                  background-color: #ffd5de;
              }
      
          </style>
      </head>
      <body>
          <nav>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for("index') }}">FlaskApp</a>
              <a href="https://www.digitalocean.com/community/tutorials/{{ url_for("create') }}">Create</a>
              <a href="#">About</a>
          </nav>
          <hr>
          <div class="content">
              {% for message in get_flashed_messages() %}
                  <div class="alert">{{ message }}</div>
              {% endfor %}
              {% block content %} {% endblock %}
          </div>
      </body>
      </html>
      

      Save and close the file, and then reload https://127.0.0.1:5000 in your browser. The navigation bar will now have a “Create” item that links to the /create route.

      To see how flash messages work, go to the “Create” page, and click the Submit button without filling the two fields. You’ll receive a message that looks like this:

      No title no content flash message

      Go back to the index page and you’ll see that the flashed messages below the navigation bar disappear, even though they are displayed as part of the base template. If they weren’t flashed messages, they would be displayed on the index page too, because it also inherits from the base template.

      Try submitting the form with a title but no content. You’ll see the message “Content is required!”. Click the FlaskApp link in the navigation bar to go back to the index page, then click the Back button to come back to the Create page. You’ll see that the message content is still there. This only works if you click the Back button, because it saves the previous request. Clicking the Create link in the navigation bar will send a new request, which clears the form, and as a result, the flashed message will disappear.

      You now know how to receive user input, how to validate it, and how to add it to a data source.

      Note:
      The messages you add to the messages list will disappear whenever the server is stopped, because Python lists are only saved in memory, to save your messages permanently, you will need to use a database like SQLite. Check out How To Use the sqlite3 Module in Python 3 to learn how to use SQLite with Python.

      Conclusion

      You created a Flask application where users can add messages to a list of messages displayed on the index page. You created a web form, handled the data the user submits via the form, and added it to your messages list. You also used flash messages to inform the user when they submit invalid data.

      If you would like to read more about Flask, check out the other tutorials in the Flask series.



      Source link