Mada za sehemu hiiDemonstrate mastery of web application development (Using PHP/Python; JavaScript; CSS, etc)Mada 7
- Describe the web application (Meaning, history and development, types, differences between website development and web application development, tags, Application Programming Interfacing - APIs)
- Create an interactive web pages (Use modern versions of PHP/Python, JavaScript, CSS, etc.) with appropriate responsive techniques
- Apply web API in rich web based application (Canvas API, Add canvas, Draw canvas, drag and drop API, Representation state transfer and CRUD operations)
- Create data-driven web based applications that speak to client or server storage systems and embed it with audio and video
- Create rich-based web applications that deliver similar features and functions as in desktop applications using modern libraries or frameworks
- Use CSS and modern HTML controls in rich based web applications
- Develop back-end using PHP/Python, JavaScript, CSS, etc (Back end should be handling user input, producing template output, storing information in databases and data stores, and building systems with secure user accounts)
Data-Driven Web Applications with Multimedia Integration
A data-driven web application is software that stores, retrieves, and manages information through databases or storage systems, delivering dynamic content to users. When you build such applications with embedded audio and video, you create interactive platforms—similar to YouTube for video streaming or Spotify for audio playback—that respond to user actions and persist data. This study note guides you through building a complete data-driven web application using HTML, CSS, JavaScript, Python (Flask), databases, and multimedia elements.
A data-driven web application differs from static websites because it changes content based on stored information. When users submit data—like posting a comment, uploading a file, or saving preferences—the application stores it and retrieves it later to personalise their experience.
Key Characteristics
- Dynamic content: Pages display information from databases, not fixed HTML files
- User interaction: Forms, buttons, and controls let users create, read, update, and delete data
- Persistence: Data survives browser sessions and device restarts
- Personalisation: Applications remember user preferences and history
For example, a student results portal at a Tanzanian secondary school displays marks that teachers upload. The same portal shows different information to each student based on their registration number stored in the database.
Before coding, you must design how your data will be organised. A database schema defines tables, fields, data types, and relationships between entities.
Steps to Design a Database Schema
-
Identify entities: Determine what objects your application manages (e.g., students, products, songs)
-
Define fields: List attributes for each entity (e.g., student: name, admission_number, subject_scores)
-
Choose data types: Select appropriate types (VARCHAR for text, INT for numbers, DATE for dates)
-
Establish relationships: Connect related entities (one student has many subject_scores)
Example: Simple Product Catalogue Schema
| Table: products | |
|---|---|
| id | INTEGER (Primary Key) |
| name | VARCHAR(100) |
| price | DECIMAL(10,2) |
| description | TEXT |
| image_url | VARCHAR(255) |
| created_at | TIMESTAMP |
This schema stores product information for an online shop. Each product has a unique ID, name, price in Tanzanian shillings, description, and an image link.
The backend handles data processing, database operations, and API creation. Flask is a lightweight Python framework suitable for beginners.
Setting Up Flask
from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///shop.db'
db = SQLAlchemy(app)
# Define Product model
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
price = db.Column(db.Float, nullable=False)
description = db.Column(db.Text)
# Create database tables
with app.app_context():
db.create_all()
@app.route('/')
def index():
products = Product.query.all()
return render_template('index.html', products=products)
@app.route('/api/products', methods=['GET'])
def get_products():
products = Product.query.all()
return jsonify([{
'id': p.id,
'name': p.name,
'price': p.price
} for p in products])
if __name__ == '__main__':
app.run(debug=True)
This code creates a Flask application that connects to a SQLite database, defines a Product model, and provides routes to display products and serve them as JSON data through an API.
The frontend uses HTML forms, JavaScript, and CSS to interact with users and communicate with the backend.
HTML Form for Adding Data
<form id="productForm">
<input type="text" id="name" placeholder="Product Name" required>
<input type="number" id="price" placeholder="Price (TZS)" required>
<textarea id="description" placeholder="Description"></textarea>
<button type="submit">Add Product</button>
</form>
<div id="productList"></div>
JavaScript to Handle Form Submission
document.getElementById('productForm').addEventListener('submit', async function(e) {
e.preventDefault();
const productData = {
name: document.getElementById('name').value,
price: document.getElementById('price').value,
description: document.getElementById('description').value
};
const response = await fetch('/api/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(productData)
});
if (response.ok) {
alert('Product added successfully!');
loadProducts(); // Refresh the product list
}
});
async function loadProducts() {
const response = await fetch('/api/products');
const products = await response.json();
const container = document.getElementById('productList');
container.innerHTML = products.map(p => `
<div class="product-card">
<h3>${p.name}</h3>
<p>${p.price} TZS</p>
</div>
`).join('');
}
This JavaScript prevents the default form submission, collects user input, sends it to the backend API using the fetch function, and updates the displayed list when successful.
CRUD represents the four fundamental operations that data-driven applications perform:
| Operation | HTTP Method | Description |
|---|---|---|
| Create | POST | Add new records to the database |
| Read | GET | Retrieve and display data |
| Update | PUT | Modify existing records |
| Delete | DELETE | Remove records |
Example: CRUD for a Student Record System
// CREATE - Add new student
async function addStudent(student) {
await fetch('/api/students', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(student)
});
}
// READ - Fetch all students
async function getStudents() {
const response = await fetch('/api/students');
return await response.json();
}
// UPDATE - Modify student marks
async function updateMarks(studentId, newMarks) {
await fetch(`/api/students/${studentId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ marks: newMarks })
});
}
// DELETE - Remove student record
async function deleteStudent(studentId) {
await fetch(`/api/students/${studentId}`, {
method: 'DELETE'
});
}
HTML5 provides built-in tags for embedding multimedia content directly into web pages without requiring plugins.
Adding Video
<video width="640" height="480" controls poster="thumbnail.jpg">
<source src="tutorial.mp4" type="video/mp4">
<source src="tutorial.webm" type="video/webm">
Your browser does not support the video tag.
</video>
Adding Audio
<audio controls>
<source src="lesson.mp3" type="audio/mpeg">
<source src="lesson.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
Dynamic Video Based on Database Data
async function loadLessonVideo(lessonId) {
const response = await fetch(`/api/lessons/${lessonId}`);
const lesson = await response.json();
const videoElement = document.getElementById('lessonVideo');
videoElement.src = lesson.video_url;
videoElement.poster = lesson.thumbnail;
document.getElementById('lessonTitle').textContent = lesson.title;
}
This function fetches lesson data from an API—including the video URL and thumbnail—and dynamically updates the video player to display the appropriate content.
Consider building a music library application where students can browse songs, listen to audio, watch music videos, and manage their playlist.
Backend (Flask)
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///music.db'
db = SQLAlchemy(app)
class Song(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
artist = db.Column(db.String(100))
audio_url = db.Column(db.String(255))
video_url = db.Column(db.String(255))
price_tzs = db.Column(db.Float)
@app.route('/api/songs', methods=['GET'])
def get_songs():
songs = Song.query.all()
return jsonify([{
'id': s.id,
'title': s.title,
'artist': s.artist,
'audio_url': s.audio_url,
'video_url': s.video_url,
'price_tzs': s.price_tzs
} for s in songs])
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)
Frontend HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Music Library</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>🎵 Campus Music Library</h1>
</header>
<main>
<section id="songList" class="song-grid"></section>
<section id="nowPlaying" class="player">
<h2>Now Playing</h2>
<h3 id="currentTitle"></h3>
<audio id="audioPlayer" controls></audio>
<video id="videoPlayer" controls width="100%"></video>
</section>
</main>
<script src="app.js"></script>
</body>
</html>
Frontend JavaScript
async function loadSongs() {
const response = await fetch('/api/songs');
const songs = await response.json();
const songList = document.getElementById('songList');
songList.innerHTML = songs.map(song => `
<div class="song-card" onclick="playSong(${song.id}, '${song.audio_url}', '${song.video_url}', '${song.title}')">
<h3>${song.title}</h3>
<p>Artist: ${song.artist}</p>
<p class="price">${song.price_tzs} TZS</p>
<button>Play</button>
</div>
`).join('');
}
function playSong(id, audioUrl, videoUrl, title) {
const audioPlayer = document.getElementById('audioPlayer');
const videoPlayer = document.getElementById('videoPlayer');
const currentTitle = document.getElementById('currentTitle');
currentTitle.textContent = title;
// Prefer video if available, otherwise play audio
if (videoUrl) {
videoPlayer.src = videoUrl;
videoPlayer.style.display = 'block';
audioPlayer.style.display = 'none';
videoPlayer.play();
} else if (audioUrl) {
audioPlayer.src = audioUrl;
audioPlayer.style.display = 'block';
videoPlayer.style.display = 'none';
audioPlayer.play();
}
}
loadSongs();
This complete example demonstrates a data-driven web application that fetches song information from a database, displays it in a responsive grid, and allows users to play audio or watch videos directly in the browser.
In Tanzania, a small video streaming business in Dar es Salaam could use these skills to create a local platform where vendors display product demonstration videos. For instance, a hardware shop owner could build a data-driven web app that stores product information in a database (using SQLite or MySQL), embeds video tutorials showing how to use tools like drills or generators, and allows customers to browse items and watch demonstrations before purchasing—similar to how Jumia shows product videos but focused on local merchants using Tanzanian shillings for pricing.
Swali
What is the primary purpose of a database schema in a data-driven web application?
Ingia ili kuwasilisha jibu lako na lihesabiwe katika umahiri wako.
Ingia ili kufanya mazoeziMwalimu
Umekwama? Niulize chochote kuhusu mada hii.
Ingia ili kumuuliza Mwalimu wa AI wa Sonza kuhusu swali hili.
Ingia ili kuuliza