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)
Back-end Development for Web Applications
The back-end is the "brain" of a web application, handling server-side logic, data management, and user authentication. When you use a web application like an online result portal or an e-commerce site, the back-end processes your requests, stores your information, and delivers the appropriate content. This study note teaches you how to build a functional back-end that handles user input, produces dynamic template output, stores data in databases, and implements secure user accounts.

Web applications follow a client-server model where responsibilities are divided between two layers:
- Client (Front-end): The interface users interact with through a browser. It sends requests to the server and displays the received data.
- Server (Back-end): The backend processes requests, performs computations, manages data in databases, and returns responses to the client.
How Client and Server Communicate
Communication happens using HTTP (Hypertext Transfer Protocol), which defines methods for formatting and transmitting messages:
| HTTP Method | Purpose | Example |
|---|---|---|
| GET | Retrieve data from the server | Loading a page, fetching user profile |
| POST | Create new data on the server | Submitting a registration form |
| PUT | Update existing data completely | Replacing all user profile details |
| DELETE | Remove data from the server | Deleting a comment or account |
When you submit a form on a Tanzanian e-learning platform, the browser sends an HTTP POST request containing your input data to the server, which processes it and stores it in a database.
For back-end development, you need a server-side programming language and framework. This guide uses Flask (Python) because it is beginner-friendly and widely used.
Installing Python and Flask
- Install Python: Download from python.org
- Install Flask using pip (Python's package manager):
pip install flask
Creating Your First Flask Application
Create a file named app.py:
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
# Sample data storage (in place of a database for demonstration)
users = []
@app.route('/')
def home():
return render_template('index.html', users=users)
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
# Handle user input from form
username = request.form.get('username')
email = request.form.get('email')
password = request.form.get('password')
# Store user data
users.append({
'username': username,
'email': email,
'password': password # In production, always hash passwords!
})
return redirect(url_for('home'))
return render_template('register.html')
if __name__ == '__main__':
app.run(debug=True)
User input reaches the back-end through HTML forms and API requests. The server must validate and process this data securely.
Processing Form Data
When a user submits a form, the data is sent via POST or GET parameters:
# Reading form data
username = request.form.get('username') # From POST body
search_query = request.args.get('q') # From URL query string (GET)
Input Validation
Always validate user input to prevent security issues:
def validateRegistration(username, email, password):
errors = []
if len(username) < 3:
errors.append("Username must be at least 3 characters")
if '@' not in email:
errors.append("Invalid email format")
if len(password) < 6:
errors.append("Password must be at least 6 characters")
return errors
Input Sanitization
Sanitize inputs to prevent SQL injection and XSS attacks:
import html
# Escape special characters to prevent XSS
safe_username = html.escape(request.form.get('username'))
Templates allow you to create dynamic HTML pages where content changes based on user data or database records.
Using Jinja2 Template Engine (Flask)
Create a folder named templates and add index.html:
<!DOCTYPE html>
<html>
<head>
<title>User Portal</title>
<style>
body { font-family: Arial; padding: 20px; }
.user-card { border: 1px solid #ccc; padding: 10px; margin: 10px 0; }
</style>
</head>
<body>
<h1>Registered Users</h1>
{% if users %}
{% for user in users %}
<div class="user-card">
<strong>{{ user.username }}</strong><br>
<small>{{ user.email }}</small>
</div>
{% endfor %}
{% else %}
<p>No users registered yet.</p>
{% endif %}
<a href="/register">Register New User</a>
</body>
</html>
The {% for %} and {% if %} tags are Jinja2 template directives that insert dynamic content.
For persistent data storage, connect your back-end to a database system.
Database Connection with SQLite (Python)
import sqlite3
def init_db():
conn = sqlite3.connect('app.db')
c = conn.cursor()
# Create users table
c.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY,
username TEXT NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL)''')
conn.commit()
conn.close()
def add_user(username, email, password):
conn = sqlite3.connect('app.db')
c = conn.cursor()
c.execute("INSERT INTO users (username, email, password) VALUES (?, ?, ?)",
(username, email, password))
conn.commit()
conn.close()
def get_all_users():
conn = sqlite3.connect('app.db')
c = conn.cursor()
c.execute("SELECT * FROM users")
users = c.fetchall()
conn.close()
return users
Using ORM (Object Relational Mapping)
ORMs like SQLAlchemy simplify database operations by mapping Python objects to database tables:
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), nullable=False)
password = db.Column(db.String(120), nullable=False)
# Create tables
with app.app_context():
db.create_all()
# Add a new user
new_user = User(username='john', email='john@example.com', password='password123')
db.session.add(new_user)
db.session.commit()
Authentication and authorization are essential for protecting user accounts.
Password Hashing
Never store passwords in plain text. Use hashing libraries:
from werkzeug.security import generate_password_hash, check_password_hash
# When registering
hashed_password = generate_password_hash(password)
user.password = hashed_password
# When logging in
if check_password_hash(user.password, input_password):
# Login successful
pass
Session Management
Track logged-in users using sessions:
from flask import Flask, session, redirect, url_for
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
app.secret_key = 'your-secret-key-change-in-production'
# Configure Flask-Login
login_manager = LoginManager()
login_manager.init_app(app)
class User(UserMixin):
def __init__(self, id, username):
self.id = id
self.username = username
@login_manager.user_loader
def load_user(user_id):
# Fetch user from database
return User(user_id, "username")
@app.route('/login', methods=['POST'])
def login():
# Verify credentials
if verified:
login_user(user)
return redirect(url_for('dashboard'))
@app.route('/dashboard')
@login_required
def dashboard():
return f"Welcome, {current_user.username}!"
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('home'))
Authorization Levels
Control what authenticated users can do:
from functools import wraps
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.is_admin:
return "Access denied", 403
return f(*args, **kwargs)
return decorated_function
@app.route('/admin')
@login_required
@admin_required
def admin_panel():
return "Admin Dashboard"
REST APIs allow other applications to interact with your back-end using standard HTTP methods.
Creating API Endpoints
from flask import jsonify, request
# GET - Retrieve all users
@app.route('/api/users', methods=['GET'])
def get_users():
users = User.query.all()
return jsonify([{
'id': u.id,
'username': u.username,
'email': u.email
} for u in users])
# POST - Create a new user
@app.route('/api/users', methods=['POST'])
def create_user():
data = request.get_json()
new_user = User(
username=data['username'],
email=data['email'],
password=data['password']
)
db.session.add(new_user)
db.session.commit()
return jsonify({'message': 'User created'}), 201
# PUT - Update a user
@app.route('/api/users/<int:id>', methods=['PUT'])
def update_user(id):
user = User.query.get(id)
data = request.get_json()
user.username = data.get('username', user.username)
db.session.commit()
return jsonify({'message': 'User updated'})
# DELETE - Remove a user
@app.route('/api/users/<int:id>', methods=['DELETE'])
def delete_user(id):
user = User.query.get(id)
db.session.delete(user)
db.session.commit()
return jsonify({'message': 'User deleted'})
API Response Status Codes
| Code | Meaning |
|---|---|
| 200 | OK - Request succeeded |
| 201 | Created - Resource successfully created |
| 400 | Bad Request - Invalid input |
| 401 | Unauthorized - Authentication required |
| 403 | Forbidden - No permission |
| 404 | Not Found - Resource doesn't exist |
| 500 | Server Error - Something went wrong |
This example demonstrates all back-end concepts together.
Directory Structure
project/
├── app.py
├── templates/
│ ├── index.html
│ ├── login.html
│ ├── register.html
│ └── dashboard.html
└── static/
└── style.css
Complete Application (app.py)
from flask import Flask, render_template, request, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.db'
db = SQLAlchemy(app)
# Database Model
class Student(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
index_number = db.Column(db.String(20), unique=True, nullable=False)
password = db.Column(db.String(200), nullable=False)
results = db.relationship('Result', backref='student', lazy=True)
class Result(db.Model):
id = db.Column(db.Integer, primary_key=True)
subject = db.Column(db.String(50), nullable=False)
score = db.Column(db.Integer, nullable=False)
student_id = db.Column(db.Integer, db.ForeignKey('student.id'), nullable=False)
# Initialize database
with app.app_context():
db.create_all()
# Routes
@app.route('/')
def home():
return render_template('index.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
name = request.form['name']
index_number = request.form['index_number']
password = generate_password_hash(request.form['password'])
student = Student(name=name, index_number=index_number, password=password)
db.session.add(student)
db.session.commit()
flash('Registration successful! Please login.')
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
index_number = request.form['index_number']
password = request.form['password']
student = Student.query.filter_by(index_number=index_number).first()
if student and check_password_hash(student.password, password):
session['student_id'] = student.id
session['name'] = student.name
return redirect(url_for('dashboard'))
else:
flash('Invalid index number or password')
return render_template('login.html')
@app.route('/dashboard')
def dashboard():
if 'student_id' not in session:
return redirect(url_for('login'))
student = Student.query.get(session['student_id'])
results = Result.query.filter_by(student_id=student.id).all()
# Calculate average
avg = sum(r.score for r in results) / len(results) if results else 0
return render_template('dashboard.html', student=student, results=results, average=avg)
@app.route('/add_result', methods=['POST'])
def add_result():
if 'student_id' not in session:
return redirect(url_for('login'))
subject = request.form['subject']
score = int(request.form['score'])
result = Result(subject=subject, score=score, student_id=session['student_id'])
db.session.add(result)
db.session.commit()
return redirect(url_for('dashboard'))
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('home'))
if __name__ == '__main__':
app.run(debug=True)
Dashboard Template (dashboard.html)
<!DOCTYPE html>
<html>
<head>
<title>Student Dashboard</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<nav>
<h2>🎓 Student Portal</h2>
<a href="/logout">Logout</a>
</nav>
<div class="container">
<h1>Welcome, {{ student.name }}</h1>
<p>Index Number: {{ student.index_number }}</p>
<div class="results-section">
<h3>Your Results</h3>
{% if results %}
<table>
<tr>
<th>Subject</th>
<th>Score</th>
</tr>
{% for result in results %}
<tr>
<td>{{ result.subject }}</td>
<td>{{ result.score }}</td>
</tr>
{% endfor %}
</table>
<p class="average">Average: {{ "%.1f"|format(average) }}</p>
{% else %}
<p>No results yet.</p>
{% endif %}
</div>
<div class="add-result">
<h3>Add New Result</h3>
<form action="/add_result" method="POST">
<input type="text" name="subject" placeholder="Subject" required>
<input type="number" name="score" placeholder="Score (0-100)" min="0" max="100" required>
<button type="submit">Add Result</button>
</form
## Real-life application
In Tanzania, back-end development powers the local web platforms people rely on every day — school fee portals, online shops, and mobile-money dashboards. For example, a developer building a system for a Dar es Salaam pharmacy would write the back-end in Python (Django) or PHP to log staff in securely, store stock and sales in a database, and generate a page that flags which medicines are running low — letting the owner reorder before stock runs out and settle supplier invoices in Tanzanian shillings on time.
Swali
Which HTTP method is used to create new data on a server?
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