Skip to main content

How to Build a Contact Form for SME Systems with Flask CKEditor (Part 5)

In this tutorial, we’ll walk through how to deploy a Flask web application that integrates CKEditor onto the PythonAnywhere cloud platform. You’ll learn how to move your project from a local development environment to a live server, configure the necessary settings, and ensure your rich text editor works smoothly in production. By the end, you’ll have a fully hosted Flask app that is accessible online, with CKEditor properly set up for handling dynamic content. 

Preliminary
Since the previous Python script will be deployed to the PythonAnywhere cloud hosting provider, no new files or folders need to be created for this tutorial. To understand the Python script, please refer to the previous tutorial.

PythonAnywhere offers two types of plans: a free plan and a paid plan. The free plan will host my web app at 'your-username.pythonanywhere.com' and two consoles with restricted outbound Internet access. However, the paid plan has 2 packages: one is for developers, and the other is custom. Please click here to review the features and price.


Step 1: PythonAnywhere web hosting configuration
First and foremost, please type the URL https://www.pythonanywhere.com/ in the browser. For the first time, I need to create an account and log in with the username/email and password that I used when signing up.

Once in the dashboard, in the top-right corner, I will click the 'Web' tab, and in the right sidebar, again, I click the '+Add a new web app' button. Then, it will remind me of the domain name. Since the current screen is a tutorial, I will ignore it and click the next button. 

The next screen required me to select a Python web framework, so I simply selected Flask and clicked the next button. Then, it asked me to select the Python and Flask versions. I click the Python 3.10 and Flask 2.1.2 versions. Of course, you need to follow your local computer version for the purpose of the Flask app's deployment. Finally, it will show the project path. I just accept it and click the next button to proceed. 




Step 2: Activate the required virtual environment, clone the repository and install the Python packages
Before I proceed, I need to click 'Console' in the top-right corner. Under the 'Start New Console' title, I will click 'Bash'; it serves the same function as the VS Code Python terminal. In the bash console, I will input as follows:
mkvirtualenv flaskenv --python=python3.10
Then, I will clone the GitHub repository. So I copied the URL from my repository and pasted it here:
git clone https://github.com/Kelvin-Data/pytest_flask_ckeditor
Finally, I will proceed to install the Python packages (similar to part 1):
pip install flask flask-wtf flask-ckeditor

Bash Console


Step 3: Set up the server and virtual environment path
I click on the 'File' tab in my top right corner. I discovered that the file folder name is "CKEditor_Sqlite" (highlighted in yellow). 


Therefore, now I'm back to the "Web" tab, and I have a few configurations here. 

I have changed both the source code and the working directory from 'mysite' to 'CKEditor_Sqlite,' as shown in the file folder above.

Meanwhile, in the WSGI configuration file folder, I also make the following changes:
(i) The folder name is 'CKEditor_Sqlite.'
(ii) import name is "app," which corresponds with our repository file name
Click the above save button. 

The last thing I need to do is to change the virtualenv to 'flaskenv,' which is step 1 above in the bash console. I have installed the relevant Python package.



Step 4: Set up a SQLite database
Since the GitHub repository only contains app.py, database.py, and form.py, it will render an error as it fails to locate the message.db. Therefore, I need to add a few lines of code to create the message.db connection.
import os
import sqlite3
from flask import g

# Get the absolute path of the current file (app.py)
# This ensures your app works no matter where you run it from
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# Create a path to the folder where the database will be stored
os.makedirs(db_dir, exist_ok=True)

# Full path to the SQLite database file
db_path = os.path.join(db_dir, "message.db")

# Function to get a database connection for the current request
def get_db:

    # 'g' is a special Flask object used to store data during a request
    # It ensures each request has its own database connection
    if 'db' not in g:    
    
        # Create a new SQLite connection and store it in 'g'
        g.db = sqlite3.connect(db_path)  
        
    # Return the database connection
    return g.db
    
# This function runs automatically after each request
@app.teardown_appcontext
def close_db(error):   

    # Remove the database connection from 'g' (if it exists)
    db = g.pop('db', None)  
    
    # If a connection was created, close it to free resources
    if db is not None:
        db.close()
Inside the message route, I change from
conn = sqlite3.connect("flask_ckeditor/message.db")
to below code as mentioned above
conn = sqlite3.connect(db_path)
Connect to a message database automatically. However, for this change to take effect, I need to update PythonAnywhere from the GitHub repository. Therefore, now I need to click the 'Console' tab, open a bash terminal, and create the following code:
cd CKEditor_Sqlite
git pull origin main
Finally, I need to return to the 'Web' tab again, and on the top, I notice a green button, and I click this button, 'Configuration KelvinLoh.pythonanywhere.com', and the web is now up and running

Final wrap-up: 
To wrap up, you’ve successfully deployed your Flask application with CKEditor to PythonAnywhere, making your project accessible on the web with full rich text editing functionality. This marks an important step in moving from development to production, allowing users to interact with your application in a real-world environment.

⬅ Previous Part                                                                                                                   ➡ Next Part

To view the full code, please click here

Comments

Popular Posts

How to Design a Location Tracking Module for Desktop Business Systems Using Python?

This tutorial will show you how to create an interactive map application that allows users to input geographic coordinates and visualize locations on an interactive map using Python's Tkinter GUI framework enhanced with TTKBootstrap styling and the TkinterMapView widget.  Preliminary   Before I begin, it is recommended to activate the virtual environment before installing the relevant dependencies. python -m venv venv venv\Scripts\activate pip install ttkbootstrap tkintermapview As usual, we need to import the relevant module and set the root values from tkinter import * import ttkbootstrap as tb import tkintermapview from ttkbootstrap.dialogs import Messagebox root = tb.Window(themename='darkly') root.title('Find My Map') root.geometry("1200x1200") I would like to divide it into three sections.  a) Input Panel Layout,  The headers are mainly a label with a map emoji.  The main layout contains labels and input fields for latitude and longitude, ...

How to Build a Contact Form for SME Systems with Flask CKEditor (Part 3)

  In the previous tutorial, I used TinyDB as our storage solution to keep application data in a simple JSON-based format. While TinyDB is lightweight and easy to use, many web applications require a more structured and scalable database system. In this tutorial, we will switch to SQLite , a powerful relational database that integrates well with Python and web frameworks. By using SQLite, you will learn how to store, manage, and query data in a more structured way for real-world applications. Preliminary Before I begin, please activate the virtual environment and install the required dependencies. Since SQLite is part of the Python standard library, it is pre-installed. python -m venv venv venv\Scripts\activate pip install flask Then, we need to set up the file and folder structure, as below: Question 1: What is SQLite? SQLite is a lightweight, serverless relational database that stores data in a single file on your computer. Unlike traditional database systems, it does ...

How to build a Desktop Business System for Audiobook Workflow Management with Python?

In this tutorial, we will build a simple audiobook player using Python and CustomTkinter. You will learn how to convert text into speech using gTTS and play it with PyGame. We will also implement play, pause, and stop controls, like those in a real audio player. By the end, you will have a clean and functional desktop audiobook app. Preliminary   Before I begin, it is recommended to activate the virtual environment before installing the relevant dependencies. python -m venv venv venv\Scripts\activate pip install customtkinter pillow gTTS pygame CTkMessagebox pypdf Then, the following steps include setting up the file structure, app.py, and two additional folders: the uploads and media folders. The media folder contains the icons necessary to build the app; there are read, pause, and stop icons, as shown on the diagram. Step 1: Build up the app interface I have 4 sections here: the header, upload area, text body, and button group.  (a) The header—this section is basicall...