0% found this document useful (0 votes)
13 views56 pages

Lec 03

The document provides an overview of web application development using Python. It discusses how web applications have evolved from static pages to dynamic sites that enable user interactivity and collaboration. It also describes popular Python frameworks like Flask and Django that help optimize the development process, and how technologies like APIs and templating engines can be integrated. Additionally, it covers common web application architectures and design patterns.

Uploaded by

keivan2612
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views56 pages

Lec 03

The document provides an overview of web application development using Python. It discusses how web applications have evolved from static pages to dynamic sites that enable user interactivity and collaboration. It also describes popular Python frameworks like Flask and Django that help optimize the development process, and how technologies like APIs and templating engines can be integrated. Additionally, it covers common web application architectures and design patterns.

Uploaded by

keivan2612
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
You are on page 1/ 56

Getting Started with Web

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

 Python's simplicity enables efficient coding of logic.


 Frameworks like Flask and Django optimize development.
 Templating engines separate presentation and logic.
 Python integrates APIs like weather, maps, etc.

 APIs (Application Programming Interfaces) are sets of rules and


specifications that allow different software applications to
communicate with each other. For example, a weather API can be
used to retrieve real-time weather data, or a map API can be used to
display interactive maps.
 By using APIs, Python developers can easily integrate additional
functionality into their web applications without having to write all of
the code themselves. This can save a lot of time and effort, and it can
also help to improve the quality and reliability of the web application.

3
Building Simple Web Applications

 Involves Python backend, HTML/CSS frontend, integration via


templating
 Backend handles server-side logic and data storage
 Frontend focuses on UI/UX - layouts, styling, responsiveness
 Templating engines are used to separate presentation and logic in web
applications. They allow developers to create dynamic HTML pages that
are populated with data from the backend.

4
Exploring 3-Tier Architecture

 Separates UI, logic, data tiers for efficiency and scalability


 UI tier displays content to users
 Logic tier handles business logic
 Data tier manages database
 Benefits:
 Improved efficiency: The 3-tier architecture allows for separation of concerns, which
can lead to improved efficiency. For example, developers can focus on developing
the presentation tier without having to worry about the underlying logic or data
storage.
 Scalability: The 3-tier architecture is highly scalable. Individual tiers can be scaled
up or down independently to meet the needs of the application.
 Security: The 3-tier architecture can improve security by isolating the data tier from
the other tiers. This makes it more difficult for attackers to gain access to sensitive
data.
 The 3-tier architecture is a well-established and widely used architecture
for web applications. It offers a number of benefits, including improved
efficiency, scalability, and security.

5
Evolution of Digital Interactions

 Early static pages were digital brochures.


 Web apps enable two-way communication and
collaboration.
 Modern web apps are increasingly # Static page
personalized and interactive. <h1>About</h1>
<p>We are a company...</p>
 They are being used to deliver new and
innovative services, such as:
 Online shopping # Web app
<h1>Welcome {{name}}</h1>
 Social media <p>Suggested products:</p>
 Online banking {% for product in suggested_products %}
{{product}}
 Streaming services {% endfor %}
 Cloud computing
 Artificial intelligence
 Web applications are constantly evolving to
meet the needs of users in new ways. They
are becoming more personalized, interactive,
and powerful. Web applications are now used
to deliver a wide range of services, from
online shopping to artificial intelligence.6
Interactivity Redefined

 Users actively engage rather than passively consume


 Real-time, adaptive experiences

# Get user input


age =int(input("Enter your age: "))

# Show age-appropriate content


if age < 18:
show_content("teen")
else:
show_content("adult")

7
Diverse Realms of Web Applications

 Social platforms, marketplaces, productivity tools, etc


 Creativity and innovation drive possibilities

8
The Developer's Canvas: Create Interactive Experiences

 Code your vision into reality


 Frontend/backend collaboration streamlines workflows
 Create engaging UIs and streamline processes

9
Python's Advantages for Web Development

 Readability enables efficient coding and easy maintenance


 Easy to add logic based on user input
 Integrates well with popular frameworks and APIs

name = input("Enter your name: ")


print(f"Hello {name}!")

10
Popular Python Frameworks for Web Development

 Flask: Lightweight and modular framework with a simple API


 Django: Robust framework with built-in components for common
tasks
 Streamline and structure development with Python frameworks
from flask import Flask

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?

 Jinja2 is a modern and designer-friendly templating engine for


Python.
 It's widely used for rendering dynamic content in web
applications and is the default templating engine for several
Python web frameworks, including Flask and Django.
 Jinja2 templates are plain text files with placeholders for dynamic
data, which are replaced with actual values during runtime.

12
Key Features of Jinja2

 Variable Substitution: Jinja2


allows you to insert dynamic data
into HTML templates using
<h1>Welcome, {{ user_name }}!</h1>
placeholders enclosed in double <p>Your account balance: ${{ account_balance }}</p>

curly braces. For example:


 Control Structures: Jinja2
supports control structures that
enable you to manipulate the
rendering of content based on <ul>
conditions or iterate over data {% for item in shopping_cart %}
<li>{{ item }}</li>
collections. {% endfor %}
</ul>
 Example: Rendering a Shopping
Cart
{% if is_logged_in %}
<p>Welcome back, {{ user_name }}!</p>
{% else %}
 Example: Conditional Rendering <p>Please log in to access your account.</p>
{% endif %}
13
Control Structures Syntax

 Jinja2 uses specific syntax for control structures. The {% ... %}


syntax denotes control statements, while {{ ... }} is used for
rendering variables.
 {% for ... %}: Initiates a for loop to iterate over a data collection.
 {% endfor %}: Marks the end of a for loop.
 {% if ... %}: Starts an if statement to conditionally render content.
 {% else %}: Specifies the content to render if the if condition is not met.
 {% endif %}: Concludes an if statement.

14
Template Inheritance

 Template inheritance is a powerful feature in Jinja2, allowing developers to create a base


template with common structural elements, such as the header and footer, and extend it in child
templates with specific content.
 It enables a clear separation between the common structure and the unique content of web
pages, enhancing code organization and reusability.
Base Template (base.html):
Extending the Base Template (home.html):
<!DOCTYPE html>
<html> {% extends 'base.html' %}
<head>
<title>{% block title %}My Web App{% endblock %}</title>
</head> {% block title %}Home{% endblock %}
<body>
<header>
<h1>My Web App</h1> {% block content %}
</header>
<main> <p>Welcome to our home page!</p>
{% block content %}{% endblock %} {% endblock %}
</main>
<footer>
&copy; 2023 My Web App
</footer>
</body>
</html>

15
Template Inheritance (cont.)

 In the base template, the {%  In the child template, the {%


block %} tags define extends 'base.html' %} tag indicates
that it extends the base.html
placeholders for content that template.
child templates can fill with  The {% block title %} and {% block
specific data. content %} tags provide content
 The {% block title %} tag that replaces the corresponding
sets a default title of "My placeholders in the base template.
Web App," which can be  The content within the {% block title
%} tag sets the title of the page to
overridden by child
"Home," overriding the default title
templates. from the base template.
 The {% block content %} tag  The content within the {% block
defines a placeholder for the content %} tag provides specific
main content. content for the home page.

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>

account_balance = 1000 </html>

shopping_cart = ['Item 1', 'Item 2', 'Item 3']


return render_template('home.html', user_name=user_name,
account_balance=account_balance, shopping_cart=shopping_cart)

17
Building Blocks of Flask

 Routing directs requests to specific @app.route('/')


handlers def home():
return 'Welcome to the home
 Templates generate dynamic HTML page!'
@app.route('/user/<username>')
responses def user_profile(username):
return render_template('profile.html',
 Request/response handling provides a username=username)
high-level abstraction for interacting with
from flask import request, make_response
HTTP

@app.route('/greet', methods=['GET', 'POST'])


 URL Building: Flask includes a url_for def greet():
function that generates URLs for your user_name = request.form.get('name')
response = make_response(f"Hello, {user_name}!")
routes.
@app.route('/user/<username>') response.headers['Content-Type'] = 'text/plain'
def user_profile(username): return response

# 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

 The Requests library enables easy integration with external APIs


 Get real-time data such as weather, maps, and social media feeds
 Enhance app functionality with features like user authentication,
payment processing, and search

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']

print(f"Current temperature: {temperature}°C, Description: {description}")

19
Conclusion

 Web applications enable interactive experiences that connect


users with information and services
 Python frameworks bridge ideas to reality by providing a
structured and streamlined development environment
 Elegant code and structure lead to maintainable and scalable
applications

20
Building Simple Web Applications

21
The Blueprint: Planning Your Web Application

 Outline the structure, features, and user interactions of your web


application.
 Create wireframes and mockups to visualize your ideas.
 Ensure that your blueprint aligns with your overall vision for the
web application.

22
User-Centered Design: Putting the User First

 Understand the needs and expectations of your target audience.


 Design your web application to be user-friendly and satisfying to
use.

23
Wireframing Tools: Translating Ideas into Visual
Representations

 Use wireframing tools to create visual representations of your


web application's screens and flows.
 Popular wireframing tools include Adobe XD, Sketch, and
Balsamiq.

24
Backend Development: The Backbone of Your Web
Application

 The backend is the server-side component of a web application.


It handles data storage, processing, and logic.
 Python and Flask are popular choices for backend development,
as they offer a powerful and flexible platform.
 Routing, view functions, and database integration are key
concepts in backend development.

25
Backend Development with Flask - Code Breakdown

 Step 1: from flask import Flask


from flask import Flask
 Imports the Flask class from the flask module.
app = Flask(__name__)
 Flask is essential for creating web applications. @app.route('/')
 Step 2: app = Flask(__name__) def home():
return "Welcome to our simple web
 Creates an instance of the Flask class. app!"
 __name__ identifies the current module and sets
the root path for the application.
 Step 3: @app.route('/')
 A Flask decorator that associates a URL route
with a view function.
 Associates the root URL '/' with the home
function.
 Step 4: def home():
 Defines the view function home, executed when
users access the root URL.
 Step 5: return 'Welcome to our simple web
app!'
 Specifies the content to display in the user's
browser when they visit the root URL.
26
Database Integration: Storing and Retrieving Data

 Databases store application data, from user profiles to task lists.


 Flask seamlessly integrates with various databases.
 Tools like SQLAlchemy manage data models and relationships for
efficient storage and retrieval.

27
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__) Code Example:


app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///myapp.db'
db = SQLAlchemy(app) SQLAlchemy
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
 Step 4: db = SQLAlchemy(app)
username = db.Column(db.String(80), unique=True, nullable=False)
 Creates an instance of the
SQLAlchemy class, bridging the
# Creating a new user
new_user = User(username='john_doe') application and the database.
db.session.add(new_user)
db.session.commit()  Step 5: class User(db.Model):
 Step 1: from flask_sqlalchemy import  Defines a User class that inherits
SQLAlchemy from db.Model.
 Imports the SQLAlchemy class from the  Represents a table in the
flask_sqlalchemy module. database, with each instance
 SQLAlchemy provides high-level APIs for corresponding to a row.
working with databases.
 Steps 6-7: id and username
 Step 2: app = Flask(__name__)
Columns
 Creates a Flask instance, similar to the previous
code.  Define columns for the User
 Step 3: table, specifying their types and
app.config['SQLALCHEMY_DATABASE_URI'] = constraints.
'sqlite:///myapp.db'  Steps 8-10: Adding a New User
 Configures the database URI for the Flask  Create a new User instance,
application. stage it for insertion into the
 Specifies the use of an SQLite database named database, and commit the
myapp.db in the same directory. changes.
28
Frontend Development: The Face of Your Web Application

 The frontend is the client-side component of a web application. It


is responsible for rendering the user interface and handling user
interactions.
 HTML, CSS, and JavaScript are the core technologies used in
frontend development.
 HTML structures the content of a web page, CSS styles the
content, and JavaScript adds interactivity.

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

 JavaScript is a powerful programming language that can be used


to add interactivity to web applications.
 jQuery is a popular JavaScript library that simplifies DOM
manipulation and makes it easier to create dynamic and
responsive user interfaces.

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

 app/ contains routes, models, templates, and static files.


 run.py launches the Flask app.
 config.py has app configuration settings.
 requirements.txt lists the project's Python dependencies.

37
Setting Up the Environment

1)Create and activate a virtual environment.


2)Install Flask, SQLAlchemy, and any other dependencies listed in
requirements.txt.

python3 -m venv venv


source venv/bin/activate
pip install flask sqlalchemy

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)

# Import routes and models


from app import routes, models

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."""

Integer, and Float.


id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String(100), nullable=False)
category = db.Column(db.String(50), nullable=False)
amount = db.Column(db.Float, nullable=False)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)

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')

# Define route for displaying transactions


@app.route('/transactions')
def transactions():
transactions = Transaction.query.order_by(Transaction.timestamp.desc()).all()
return render_template('transactions.html', transactions=transactions)

41
Building Templates

 HTML templates are <!-- app/templates/layout.html -->


<!DOCTYPE html>
used to create <html>
consistent pages. <head>
<title>Personal Budget Tracker</title>
 Jinja syntax can be <link rel="stylesheet" href="{{ url_for('static',
used to dynamically filename='styles.css') }}">
insert data into </head>
<body>
templates. <nav>
<ul>
 Templates can <li><a href="{{ url_for('index') }}">Home</a></li>
inherit and extend a <li><a href="{{ url_for('add_transaction') }}">Add
base layout Transaction</a></li>
template. <li><a href="{{ url_for('transactions') }}">Transaction
History</a></li>
</ul>
</nav>
{% block content %}{% endblock %}
</body>
</html>

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 %}

<!-- app/templates/add_transaction.html --> {% block content %}


<h1>Transaction History</h1>
{% extends 'layout.html' %}
<table>
<tr>
{% block content %} <th>Description</th>
<h1>Add Transaction</h1> <th>Category</th>
<form method="POST" action="/add_transaction"> <th>Amount</th>
<label for="description">Description:</label> <th>Timestamp</th>
<input type="text" id="description" name="description" </tr>
{% for transaction in transactions %}
required> <tr>
<label for="category">Category:</label> <td>{{ transaction.description }}</td>
<input type="text" id="category" name="category" required> <td>{{ transaction.category }}</td>
<label for="amount">Amount:</label> <td>${{ transaction.amount }}</td>
<input type="number" id="amount" name="amount" required> <td>{{ transaction.timestamp.strftime('%Y-
<button type="submit">Add Transaction</button> %m-%d %H:%M:%S') }}</td>
</form> {% endblock %}
{% 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

from app import app


@app.before_first_request
def create_tables():
db.create_all()
if __name__ == '__main__':
app.run(debug=True)

45
Deploying to Production

 There are many different platforms that can be used to deploy


Flask apps to production, such as Heroku, AWS, and Azure.
 Each platform has its own specific instructions for deploying
Flask apps.
 Once your app is deployed, it will be accessible to the public over
the internet.

46
3-Tier Architecture: A Blueprint for Scalable,
Secure, and Modular Web Applications

47
The Architecture of Layers

 Presentation tier: User interfaces


 Logic tier: Business logic and functionality
 Data storage tier: Data persistence

48
Presentation Tier

 Responsible for user interface (UI) and user experience (UX)


 Uses technologies such as HTML, CSS, and client-side JavaScript
 Provides visual elements and user interaction

49
Logic Tier

 Handles business logic and core functions


 Processes user requests
 Orchestrates interactions between different tiers

50
Data Storage Tier

 Manages data persistence


 Uses technologies such as databases and file systems
 Provides efficient storage and retrieval of data

51
Benefits: Scalability

 Each tier can be scaled independently


 Load can be distributed across servers
 Performance can be maintained during traffic spikes

52
Benefits: Modularity

 Layers can be developed and tested separately


 Changes to one tier have minimal impact on other tiers
 Maintainability is enhanced

53
Benefits: Security

 Access controls can be implemented at different layers


 The logic tier validates requests
 Centralized security mechanisms can be used

54
Key Takeaways

 Scalability, modularity, and security are key benefits of 3-tier


architecture
 Clear separation of concerns is essential
 3-tier architecture enables applications to evolve gracefully

55
Conclusion

 3-tier architecture provides a blueprint for efficient, robust, and


secure web applications
 Embracing the presentation, logic, and data tiers can help you
build applications that thrive in the dynamic landscape of the
web

56

You might also like