Exploring Front-End Technologies Compatible with Python Back Ends

Over the last 10 years or so, Python has become my go-to language. I’ve used Python to build out commercial products, my own version of Rainmeter, desktop customization utilities, bots that index Discord, server and systems monitoring apps, and the list goes on.

When I first started, and without knowing it, I consistently used “client-server architecture” or what some may refer to as “two-tier architecture” — a design pattern that separates the user interface and client-side logic from the server-side operations and data management.

In this article, I’ll discuss the front-end technologies I’ve used with Python backends. If I had to choose a front end, React.js would be my top pick, while Django and Angular would be my last choices.

The examples below use an SQLite database named backendDB.db, which contains a table called greeting. This table has two fields: greeting, which contains the value “Happy coding!”, and author, which contains the value “C. C. Python Programming”. Use the python code below to quickly standup the database.

import sqlite3

# Connect to the SQLite database (or create it if it doesn't exist)
connection = sqlite3.connect('backendDB.db')

try:
    # Create a cursor object to interact with the database
    cursor = connection.cursor()

    # Create the greeting table
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS greeting (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            greeting TEXT NOT NULL,
            author TEXT NOT NULL
        )
    ''')

    # Insert the data into the greeting table
    cursor.execute('''
        INSERT INTO greeting (greeting, author)
        VALUES (?, ?)
    ''', ('Happy coding!', 'C. C. Python Programming'))

    # Commit the changes to the database
    connection.commit()

    print("Table created and data inserted successfully.")

except sqlite3.Error as e:
    print(f"An error occurred: {e}")

finally:
    # Close the database connection
    if connection:
        connection.close()

HTML, CSS, and JavaScript

The Foundation of Web Development

  • HTML (HyperText Markup Language) is the standard markup language used to create web pages. It structures the content on the web.
  • CSS (Cascading Style Sheets) is used to style and layout web pages.
  • JavaScript is a scripting language that enables interactive web pages.

These three technologies form the foundation of web development. Python can be used as the backend language to handle server-side operations, data processing, and database interactions, while HTML, CSS, and JavaScript handle the presentation layer and user interactions.

HTML Integration with Python

Python frameworks such as Flask and Django are designed to serve HTML content and manage HTTP requests. Flask, for instance, is a micro web framework that allows developers to build web applications quickly. Django, on the other hand, is a feature-rich framework that includes ORM (Object-Relational Mapping), authentication, and other built-in functionalities. Both frameworks allow you to render HTML templates, apply CSS styles, and add JavaScript functionalities.

Here’s an example of using Flask to fetch data from a SQLite database and display it in an HTML template:

Backend (Flask)

from flask import Flask, render_template
import sqlite3

app = Flask(__name__)

def get_greeting():
    try:
        connection = sqlite3.connect('backendDB.db')
        cursor = connection.cursor()
        cursor.execute("SELECT greeting, author FROM greeting")
        data = cursor.fetchone()
        return data
    except Exception as e:
        print(f"An error occurred: {e}")
        return None
    finally:
        if connection:
            connection.close()

@app.route('/')
def home():
    data = get_greeting()
    return render_template('index.html', greeting=data[0], author=data[1])

if __name__ == '__main__':
    app.run(debug=True)

Frontend (HTML — index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Greeting</title>
</head>
<body>
    <h1>{{ greeting }}</h1>
    <p>{{ author }}</p>
</body>
</html>

In this example, Flask serves an HTML template (index.html), which displays data retrieved from a SQLite database. The get_greeting function handles database operations, ensuring the connection is closed properly using try-except-finally.

Running the Code:

  • Ensure Flask is Running:
  • First, make sure the Flask server is running. Open a terminal and navigate to your Flask project directory.
  • Run the Flask server with: python app.py

Open the HTML File:

  • Open index.html in VS Code.

View in Browser:

  • Right-click on index.html and select Open with Live Server (if you have the Live Server extension installed).
  • Alternatively, you can open the file directly in a browser by right-clicking the file in VS Code and selecting Reveal in File Explorer (or Show in Finder on macOS), then double-click the file to open it in your default web browser.

No additional packages needed for the HTML example. Just ensure you have Flask running to serve the HTML file.


React.js

A Powerful Front-End Library

React.js is a popular JavaScript library for building user interfaces, especially single-page applications. Developed by Facebook, React allows developers to create reusable UI components, making development more efficient and maintainable.

Integration with Python

React can be integrated with a Python backend using RESTful APIs. The Python backend (using Flask) serves as the API endpoint, handling data requests and processing, while React handles the front-end rendering.

Backend (Flask)

from flask import Flask, jsonify
import sqlite3

app = Flask(__name__)

def get_greeting():
    try:
        connection = sqlite3.connect('backendDB.db')
        cursor = connection.cursor()
        cursor.execute("SELECT greeting, author FROM greeting")
        data = cursor.fetchone()
        return {"greeting": data[0], "author": data[1]}
    except Exception as e:
        return {"error": str(e)}
    finally:
        if connection:
            connection.close()

@app.route('/api/greeting')
def greeting_api():
    data = get_greeting()
    return jsonify(data)

if __name__ == '__main__':
    app.run(debug=True)

Frontend (React)

import React, { useEffect, useState } from 'react';

function App() {
    const [data, setData] = useState({ greeting: '', author: '' });

    useEffect(() => {
        fetch('/api/greeting')
            .then(response => response.json())
            .then(data => setData(data));
    }, []);

    return (
        <div>
            <h1>{data.greeting}</h1>
            <p>{data.author}</p>
        </div>
    );
}

export default App;

In this example, Flask serves a JSON response, which can be fetched and displayed by a React component.

Running the Code:

Install Dependencies:

  • Open a terminal and navigate to your React project directory.
  • Install the required packages with: npm install or yarn install.

Packages Needed:

  • react: The core React library.
  • react-dom: The package for DOM-specific methods.
  • react-scripts: Provides scripts and configuration for Create React App (if you used Create React App to set up the project).
npm install react react-dom react-scripts

Or

yarn add react react-dom react-scripts

Start the React Development Server:

  • Run the development server with: npm start or yarn start.

View in Browser:

  • The React application should automatically open in your default web browser at http://localhost:3000. If it doesn’t open automatically, you can manually navigate to this URL.

Vue.js

A Progressive JavaScript Framework

Vue.js is a progressive JavaScript framework for building user interfaces. It is designed to be incrementally adoptable, meaning you can use as much or as little of Vue as you need. Vue is known for its simplicity and flexibility.

Integration with Python

Similar to React, Vue.js can communicate with a Python backend via RESTful APIs. Vue can be used to create interactive components that fetch data from the backend and dynamically update the UI.

Backend (Flask)

from flask import Flask, jsonify
import sqlite3

app = Flask(__name__)

def get_greeting():
    try:
        connection = sqlite3.connect('backendDB.db')
        cursor = connection.cursor()
        cursor.execute("SELECT greeting, author FROM greeting")
        data = cursor.fetchone()
        return {"greeting": data[0], "author": data[1]}
    except Exception as e:
        return {"error": str(e)}
    finally:
        if connection:
            connection.close()

@app.route('/api/greeting')
def greeting_api():
    data = get_greeting()
    return jsonify(data)

if __name__ == '__main__':
    app.run(debug=True)

Frontend (Vue)

<template>
  <div>
    <h1>{{ greeting }}</h1>
    <p>{{ author }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      greeting: '',
      author: ''
    }
  },
  created() {
    fetch('/api/greeting')
      .then(response => response.json())
      .then(data => {
        this.greeting = data.greeting;
        this.author = data.author;
      });
  }
}
</script>

In Vue, you can fetch data from this API and display it in a component.

Running the Code:

Install Dependencies:

  • Open a terminal and navigate to your Vue project directory.
  • Install the required packages with: npm install or yarn install.

Packages Needed:

  • vue: The core Vue.js library.
npm install vue

Or

yarn add vue

Start the Vue Development Server:

  • Run the development server with: npm run serve or yarn serve.

View in Browser:

  • The Vue application should automatically open in your default web browser at http://localhost:8080. If it doesn’t open automatically, you can manually navigate to this URL.

Angular

A Full-Fledged Front-End Framework

Angular is a platform and framework for building single-page client applications using HTML and TypeScript. Developed by Google, Angular provides a comprehensive solution that includes a robust set of tools for building, testing, and maintaining large applications.

Integration with Python

Angular can also be integrated with a Python backend through RESTful APIs. The backend handles data operations, while Angular provides a rich front-end experience.

Backend (Flask)

from flask import Flask, jsonify
import sqlite3

app = Flask(__name__)

def get_greeting():
    try:
        connection = sqlite3.connect('backendDB.db')
        cursor = connection.cursor()
        cursor.execute("SELECT greeting, author FROM greeting")
        data = cursor.fetchone()
        return {"greeting": data[0], "author": data[1]}
    except Exception as e:
        return {"error": str(e)}
    finally:
        if connection:
            connection.close()

@app.route('/api/greeting')
def greeting_api():
    data = get_greeting()
    return jsonify(data)

if __name__ == '__main__':
    app.run(debug=True)

Frontend (Angular)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private apiUrl = '/api/greeting';

  constructor(private http: HttpClient) {}

  getData(): Observable<any> {
    return this.http.get<any>(this.apiUrl);
  }
}

In your Angular component:

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  template: '<h1>{{ greeting }}</h1><p>{{ author }}</p>',
})
export class AppComponent implements OnInit {
  greeting: string;
  author: string;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService.getData().subscribe(data => {
      this.greeting = data.greeting;
      this.author = data.author;
    });
  }
}

Running the Code:

Install Dependencies:

  • Open a terminal and navigate to your Angular project directory.
  • Install the required packages with: npm install.

Packages Needed:

  • @angular/core: Core Angular library.
  • @angular/cli: Angular CLI for project management and development.
  • @angular/common: Common Angular utilities.
  • @angular/compiler: Angular template compiler.
  • @angular/forms: Angular forms handling.
  • @angular/platform-browser: Angular utilities for browser support.
  • @angular/platform-browser-dynamic: Angular utilities for dynamic browser support.
  • @angular/router: Angular routing library.
  • rxjs: Reactive programming library used by Angular.
  • zone.js: Angular’s change detection library.
npm install @angular/core @angular/cli @angular/common @angular/compiler @angular/forms @angular/platform-browser @angular/platform-browser-dynamic @angular/router rxjs zone.js

Or

yarn add @angular/core @angular/cli @angular/common @angular/compiler @angular/forms @angular/platform-browser @angular/platform-browser-dynamic @angular/router rxjs zone.js

Start the Angular Development Server:

  • Run the development server with: ng serve.

View in Browser:

  • The Angular application should automatically open in your default web browser at http://localhost:4200. If it doesn’t open automatically, you can manually navigate to this URL.

Thank you for following along with this tutorial. We hope you found it helpful and informative. If you have any questions, or if you would like to suggest new Python code examples or topics for future tutorials/articles, please feel free to join and comment. Your feedback and suggestions are always welcome!

You can find the same tutorial on Medium.com

Leave a Reply