Lec 03
Lec 03
Application Development
Unveiling the Power of Web Applications
Web apps like social networks, shopping carts, and online banking
enable interactivity beyond static brochures.
Users can actively input data, trigger real-time actions, and
collaborate with others.
2
Python - Your Gateway to Web Apps
3
Building Simple Web Applications
4
Exploring 3-Tier Architecture
5
Evolution of Digital Interactions
7
Diverse Realms of Web Applications
8
The Developer's Canvas: Create Interactive Experiences
9
Python's Advantages for Web Development
10
Popular Python Frameworks for Web Development
app = Flask(__name__)
@app.route('/')
def hello():
return 'Welcome to our Flask-powered web app!'
@app.route('/about')
def about():
return 'This is the About page.'
@app.route('/user/<username>')
def user_profile(username):
return f'Hello, {username}! This is your profile.'
11
What is Jinja2?
12
Key Features of Jinja2
14
Template Inheritance
15
Template Inheritance (cont.)
16
<!DOCTYPE html>
<html>
Example <head>
<title>Dynamic Web Page</title>
</head>
<body>
<h1>Welcome, {{ user_name }}!</h1>
from flask import Flask, render_template
<p>Your account balance: ${{ account_balance }}</p>
<h2>Your Shopping Cart:</h2>
app = Flask(__name__) <ul>
{% for item in shopping_cart %}
<li>{{ item }}</li>
@app.route('/')
{% endfor %}
def home(): </ul>
user_name = 'Alice' </body>
17
Building Blocks of Flask
# Generates URL for the user_profile route with the specified username
url = url_for('user_profile', username=username)
return f'Profile URL: {url}'
18
Python + APIs
import requests
response = requests.get('https://api.openweathermap.org/data/2.5/weather?
q=city_name&appid=your_api_key')
weather_data = response.json()
temperature = weather_data['main']['temp']
description = weather_data['weather'][0]['description']
19
Conclusion
20
Building Simple Web Applications
21
The Blueprint: Planning Your Web Application
22
User-Centered Design: Putting the User First
23
Wireframing Tools: Translating Ideas into Visual
Representations
24
Backend Development: The Backbone of Your Web
Application
25
Backend Development with Flask - Code Breakdown
27
from flask_sqlalchemy import SQLAlchemy
29
Code Example: HTML and CSS
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>
30
User Interactions with JavaScript and jQuery
31
Code Example: jQuery
$('#btn').click(function() {
alert("Button clicked!");
});
This code example shows how to use jQuery to add a click event
handler to a button. When the button is clicked, an alert
message will be displayed.
32
Bringing It All Together: Deploying Your Web Application
Once you have developed the frontend and backend of your web
application, you need to integrate them together.
You can then deploy your web application to servers or the
cloud.
It is important to get user feedback and iterate on your web
application to improve it over time.
33
Deployment Options for Web Applications
Heroku
AWS
Microsoft Azure
PythonAnywhere
These are just a few popular deployment options for web
applications. The best option for you will depend on your specific
needs and requirements.
34
Conclusion: Building Simple Web Applications with Python
and Flask
A blueprint can help you to align your vision for your web
application.
Python and Flask are popular choices for both backend and
frontend development.
Databases can be used to store data for your web application.
Once you have developed and deployed your web application, it
is important to get user feedback and iterate on it to improve it
over time.
35
Personal Budget Tracker Web App Example
36
Directory Structure
37
Setting Up the Environment
38
Creating the Flask Application
# app/__init__.py
Import Flask and
SQLAlchemy. from flask import Flask
from flask_sqlalchemy import SQLAlchemy
Create a Flask app
instance. # Create a Flask application instance
app = Flask(__name__)
Configure app settings
like SECRET_KEY. # Configure app settings
app.config['SECRET_KEY'] = 'your-secret-key'
Initialize the app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///budget.db'
SQLAlchemy database
instance. # Create a SQLAlchemy database instance
db = SQLAlchemy(app)
39
Defining Data Models
# app/models.py
Use SQLAlchemy to
define database models.
from datetime import datetime
Model classes represent from app import db
database tables.
# Define the Transaction data model
Define columns with class Transaction(db.Model):
types like String, """This class represents a transaction in the database."""
def __repr__(self):
"""Provide a human-readable representation of the model."""
return f"Transaction('{self.description}', '{self.amount}',
'{self.timestamp}')"
40
Creating Routes # app/routes.py
from flask import render_template, request, redirect, url_for
from app import app, db
from app.models import Transaction
Routes associate
URLs with view # Define route for the homepage
functions. @app.route('/')
def index():
return render_template('index.html')
Use the
@app.route() # Define route for adding transactions
decorator to @app.route('/add_transaction', methods=['GET', 'POST'])
def add_transaction():
define routes. if request.method == 'POST':
description = request.form['description']
Create routes for category = request.form['category']
adding, editing, amount = float(request.form['amount'])
transaction = Transaction(description=description, category=category, amount=amount)
and deleting db.session.add(transaction)
db.session.commit()
transactions return redirect(url_for('transactions'))
return render_template('add_transaction.html')
41
Building Templates
42
<!-- app/templates/index.html -->
{% extends 'layout.html' %}
Code Example
{% block content %}
<h1>Welcome to Personal Budget Tracker</h1>
<!-- app/templates/transactions.html -->
<p>Manage your personal finances and track expenses.</p> {% extends 'layout.html' %}
{% endblock %}
43
Styling with CSS
/* app/static/styles.css */ nav ul li {
CSS is used to /* Add your CSS styles here */ margin: 10px;
style the
}
appearance of body {
web pages. font-family: Arial, sans-serif;
margin: 0; /* Style the table */
CSS can be used padding: 0; table {
} border-collapse:
to control
typography, collapse;
/* Style the navigation bar */ width: 100%;
colors, layout, nav { }
and other visual background-color: #333;
color: white;
elements. } table, th, td {
Consistent CSS border: 1px solid black;
styling should be nav ul { padding: 8px;
list-style-type: none; }
used across all padding: 0;
templates. display: flex;
} th {
background-color:
#f2f2f2;
44 }
Running and Accessing Locally
Set the FLASK_APP environment variable to the name of your Flask app file (e.g. run.py).
export FLASK_APP=run.py
Run the flask run command to start the development server.
flask run
Access your app in a web browser at http://localhost:5000.
# run.py
45
Deploying to Production
46
3-Tier Architecture: A Blueprint for Scalable,
Secure, and Modular Web Applications
47
The Architecture of Layers
48
Presentation Tier
49
Logic Tier
50
Data Storage Tier
51
Benefits: Scalability
52
Benefits: Modularity
53
Benefits: Security
54
Key Takeaways
55
Conclusion
56