SoFunction
Updated on 2025-03-04

Write a message book using Python and Flask

In this article, we will get started with Flask by creating a simple guestbook app. This project will help us understand the basic concepts and functions of Flask, such as routing, templates, form processing, etc. If you are a novice in Python or try to use Flask for the first time, don't worry, this article will take you through this project step by step.

1. Environmental preparation

First, you need to make sure that Python and pip are installed on your computer. Next, we need to install Flask. Run the following command on the command line:

pip install Flask

If you plan to use a database, you can choose SQLite (built in the Python standard library), or install a more powerful database such as MySQL or PostgreSQL. For simplicity, we use SQLite in this project.

2. Create Flask app

Create a new file in your working directory, named. This file will contain our Flask application code.

from flask import Flask, render_template, request, redirect, url_for
import sqlite3
 
app = Flask(__name__)
 
# Configure database connectionsDATABASE = ''
 
def get_db_connection():
    conn = (DATABASE)
    conn.row_factory = 
    return conn
 
def init_db():
    conn = get_db_connection()
    c = ()
    ('''CREATE TABLE IF NOT EXISTS messages (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    message TEXT NOT NULL,
                    timestamp TEXT NOT NULL
                )''')
    ()
    ()
 
# Initialize the databaseif __name__ == '__main__':
    init_db()

3. Create route and view functions

Next, we need to define some routes and view functions to handle user requests.

@('/')
def index():
    conn = get_db_connection()
    c = ()
    ('SELECT * FROM messages ORDER BY timestamp DESC')
    messages = ()
    ()
    return render_template('', messages=messages)

The above code defines a route /, and when the user accesses this URL, the index view function will be called. This function takes all messages from the database and sorts them in descending order, and then passes them to the template.

4. Create a template

In Flask, templates are used to generate HTML. Create a folder in your working directory named templates. Create a file in this folder named.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Message book</title>
    <link href="/bootstrap/4.5.2/css/" rel="stylesheet">
  </head>
  <body>
    <div class="container mt-5">
      <h1 class="mb-4">Message book</h1>
      <form method="post" action="/add_message">
        <div class="form-group">
          <label for="name">Name</label>
          <input type="text" class="form-control"  name="name" required>
        </div>
        <div class="form-group">
          <label for="message">message</label>
          <textarea class="form-control"  name="message" rows="3" required></textarea>
        </div>
        <button type="submit" class="btn btn-primary">submit</button>
      </form>
      <hr>
      <div class="list-group">
        {% for message in messages %}
          <a href="#" class="list-group-item list-group-item-action">
            <h5 class="mb-1">{{ message['name'] }}</h5>
            <p class="mb-1">{{ message['message'] }}</p>
            <small>{{ message['timestamp'] }}</small>
          </a>
        {% endfor %}
      </div>
    </div>
    <script src="/jquery-3.5."></script>
    <script src="/npm/@popperjs/[email protected]/dist/umd/"></script>
    <script src="/bootstrap/4.5.2/js/"></script>
  </body>
</html>

This template uses Bootstrap to beautify forms and comment lists. The action property of the form is set to /add_message, which means that when the user submits the form, a POST request will be sent to this URL.

5. Process form submission

Now, we need to define a view function to handle form submissions.

from datetime import datetime
 
@('/add_message', methods=['POST'])
def add_message():
    name = ['name']
    message = ['message']
    timestamp = ().isoformat()
 
    conn = get_db_connection()
    c = ()
    ('INSERT INTO messages (name, message, timestamp) VALUES (?, ?, ?)', (name, message, timestamp))
    ()
    ()
 
    return redirect(url_for('index'))

In this view function, we get the form data from it and insert it into the database. Finally, we use the redirect function to redirect the user to the homepage.

6. Run the application

Now you can run your Flask app. On the command line, navigate to the directory where your file is located and run the following command:

python 

By default, the Flask app runs on http://127.0.0.1:5000/. Open your browser, access this URL, and you should be able to see your Guestbook app.

7. Add styles and functions (optional)

While our Guestbook app is now working, you can make it more complete by adding some styles and features.

Verification and Error Handling: You can add some verification logic to ensure that the data entered by the user is valid. For example, you can check whether the name and message are empty or limit the length of the message.

Pagination: If you leave a lot of messages, you can add a pagination function to allow users to browse more messages.

User Authentication: You can add user authentication function to limit messages only registered users.

Delete and edit messages: You can add the functions of deletion and edit messages.

Deployment: You can deploy your app to one server so that others can access it.

8. Example: Add verification and error handling

Here is a simple example showing how to add validation and error handling when form is submitted.

from flask import flash
 
@('/add_message', methods=['POST'])
def add_message():
    name = ['name'].strip()
    message = ['message'].strip()
 
    if not name or not message:
        flash('Neither name nor message is empty.  ', 'error')
        return redirect(url_for('index'))
 
    if len(message) > 500:
        flash('The message cannot exceed 500 characters.  ', 'error')
        return redirect(url_for('index'))
 
    timestamp = ().isoformat()
 
    conn = get_db_connection()
    c = ()
    ('INSERT INTO messages (name, message, timestamp) VALUES (?, ?, ?)', (name, message, timestamp))
    ()
    ()
 
    flash('The message has been added successfully.  ', 'success')
    return redirect(url_for('index'))

In this example, we use the strip() method to remove the spaces before and after the user input and check whether the name and message are empty. We also checked the length of the message and if it exceeds 500 characters, an error message will be displayed. We use the flash function to display these messages, which will be obtained in the template through the get_flashed_messages() function.

In the template, you can add the following code to display these messages:

{% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
    <div class="alert alert-info alert-dismissible fade show" role="alert">
      {% for category, message in messages %}
        <strong>{{ () }}!</strong> {{ message }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      {% endfor %}
    </div>
  {% endif %}
 
{% endwith %}

Add the above code to the <body> tag of your template, usually before <div class="container mt-5"> so that the Flash message will appear at the top of the page. This code block uses the with statement of the Jinja2 template engine to create a local scope, where the messages variable contains the Flash messages and their categories obtained through get_flashed_messages(with_categories=true). Then, use a loop to iterate through the messages and display different styles based on the category (such as 'error' or 'success').

The complete template should look like this (only display the key parts):

&lt;!doctype html&gt;
&lt;html lang="en"&gt;
  &lt;head&gt;
    &lt;!-- Omit previous header information --&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;!-- Flash Message display area --&gt;
    {% with messages = get_flashed_messages(with_categories=true) %}
      {% if messages %}
        &lt;div class="alert alert-info alert-dismissible fade show" role="alert"&gt;
          {% for category, message in messages %}
            &lt;strong&gt;{{ () }}!&lt;/strong&gt; {{ message }}
            &lt;button type="button" class="close" data-dismiss="alert" aria-label="Close"&gt;
              &lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt;
            &lt;/button&gt;
          {% endfor %}
        &lt;/div&gt;
      {% endif %}
    {% endwith %}
    
    &lt;!-- Omit previous guestbook containers and forms --&gt;
    
    &lt;!-- Omit previous script references --&gt;
  &lt;/body&gt;
&lt;/html&gt;

In this way, when the user submits the form, if the verification fails, the corresponding error message will be displayed. If the verification is successful, a success message will be displayed and the user will be redirected back to the homepage.

9. Further optimization

Although our guestbook application already has basic functions, there are still many areas that can be optimized, such as:

CSS Style: You can customize CSS Styles to make your app more in line with your brand or theme.

JavaScript: Using JavaScript can enhance the user experience, such as form verification, dynamic loading of more messages, etc.

Security: Consider using libraries like Flask-WTF or Flask-Security to enhance form validation and security.

Test: Write unit tests to make sure your code works properly in different situations.

Deployment: Use WSGI servers such as Gunicorn, uWSGI to deploy your application, and use Nginx or Apache as the reverse proxy.

10. Deploy to production environment

When you are ready to deploy your application to a production environment, you can consider the following steps:

Select a server: Choose a reliable server provider, such as AWS, Google Cloud, Heroku, etc.

Configuration environment: Install necessary software and libraries on the server, such as Python, Flask, database, etc.

Set up a virtual environment: Use venv or virtualenv to create and manage Python virtual environments.

Deploy your code: Upload your code to the server and configure the WSGI server to run your Flask application.

Configure database: Configure database connections in production environments and ensure that database migrations have been applied.

Test: Test your application in production to ensure everything works properly.

Monitoring and Maintenance: Use monitoring tools to track application performance and stability and perform regular maintenance and updates.

This is the end of this article about writing a guestbook using Python and Flask. For more related content in Python Flask guestbook, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!