0% found this document useful (0 votes)
15 views45 pages

PPFD 4

This document provides an introduction to Flask, a lightweight Python web framework, detailing its core components, installation, routing, app settings, and handling HTTP methods. It covers templates, static files, database connectivity, error handling, flash messages, email functionality, user authentication, and deployment strategies. The document serves as a comprehensive guide for developing web applications using Flask.

Uploaded by

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

PPFD 4

This document provides an introduction to Flask, a lightweight Python web framework, detailing its core components, installation, routing, app settings, and handling HTTP methods. It covers templates, static files, database connectivity, error handling, flash messages, email functionality, user authentication, and deployment strategies. The document serves as a comprehensive guide for developing web applications using Flask.

Uploaded by

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

Introduction to Flask and Web Development with Python

● Flask is a micro-web framework for Python, meaning it is lightweight, modular, and does not impose
many dependencies.
● It is designed for developers who prefer flexibility and control over web application development.
● Flask is based on two core components:
● Werkzeug: A WSGI (Web Server Gateway Interface) toolkit that provides request and response
handling.
● Jinja2: A templating engine used to render dynamic HTML templates.
● Flask is commonly referred to as "batteries not included" since it provides essential features but
leaves additional functionality (like authentication, database handling, etc.) to extensions.
Contd….

● Flask(__name__): Creates the Flask application.


● @app.route('/'): Defines a route for the home page (/ URL).
● debug=True: Enables debugging features like auto-reloading and error tracking.
Installation in a Virtual Environment

● A virtual environment is an isolated environment for Python projects, ensuring dependencies


for one project don't interfere with another.
● Flask is not included in the standard Python library, so it must be installed in the project
environment.
● By creating a virtual environment:
● You can maintain separate Python libraries for different projects.
● It prevents dependency conflicts between applications.

1. Install virtualenv:
Contd..
● Create and activate a virtual Environment

● Install Flask

● Deactivate the virtual environment:


Routing and App Settings
● Routing:
➔ Routing maps URLs to Python functions.
➔ In Flask, the @app.route() decorator is used to define URL endpoints.
➔ Flask supports dynamic routing by using variable placeholders in the URL (e.g., /user/<username>).

Examples:

● Static Route
Static Routes:
Explanation:

● @app.route('/'):
○ The @app.route decorator in Flask is used to define a URL route for your application.
○ The '/' route represents the root URL of the application (e.g., http://localhost:5000/ or the base of your
website).
● Function home():
○ The function home() is executed when a user visits the specified route (/).
○ It simply returns the text "Home Page", which will be displayed in the browser when accessing this
route.

Example Output:

If you visit http://localhost:5000/ in a browser, you will see:


Dynamic Route:
Example:

Explanation:

● @app.route('/user/<username>'):
○ The <username> inside the route is a dynamic segment.
○ Flask uses this segment to capture the value entered at the URL and passes it as an argument to the
function.
○ For example, if you visit http://localhost:5000/user/John, the value "John" will be passed as the
argument username.
Contd…
● Function user(username):
○ This function takes the captured username from the URL and uses it.
○ It returns a personalized greeting like "Hello, John!".

● String Interpolation (f-string):


○ The f"Hello, {username}!" syntax is a formatted string literal that dynamically
inserts the value of username into the response.
Example Output:
If you visit http://localhost:5000/user/Alice, the browser will display:
App Settings:
● Flask provides settings for configuring debugging, secret keys, and database URIs.
● app.run(debug=True) enables the debug mode, which automatically reloads the server on code
changes and shows detailed error messages.

● Example:
Full Flask Application Example
Here’s how you can combine both static and dynamic routes in a Flask app:
URL Building and HTTP Methods
● Flask provides tools for handling URL routing and HTTP methods effectively.
● URL Building:
URL building in Flask involves generating URLs for specific routes dynamically using the url_for()
function.

Why use URL Building?


● Hardcoding URLs can lead to errors, especially when the URL structure changes.
● url_for() dynamically generates URLs based on the function name of a route, making applications
easier to maintain.

● Syntax:
endpoint: The name of the function linked to a route.

values: Key-value pairs for dynamic segments of the route.


Contd..
Example: Output (Access /url_example):

Benefits:

1. Ensures route consistency across the


application.
2. Automatically includes query
parameters and avoids manual URL
assembly.
3. Useful in templates for generating links
dynamically.
HTTP Methods

● HTTP methods determine the type of operation performed when a client (a browser) interacts with
the server.
● Flask allows handling various HTTP methods (e.g., GET, POST, PUT, DELETE) via the methods
argument in the @app.route() decorator.
Method Purpose Use Case

GET Retrieve data from the Fetching a webpage or


server (default method). data.

POST Send data to the server to Submitting a form.


create or update resources.

PUT Update an existing Editing a record


resource.

DELETE Remove a resource from Deleting a database entry.


the server.
Example 1: Handling GET and POST Methods

GET Request: Visit http://localhost:5000/ in your


browser (default is GET).

● Output: This is a GET request

POST Request: Use tools like Postman or curl:

Output: This is a POST request


Example 2: Form Submission with POST

How it Works:

1. On GET request, it displays the form.


2. On POST request, it retrieves the input
value from the form and displays a
personalized greeting.
Example 3: Using PUT and DELETE

PUT Request: Use curl or Postman:

curl -X PUT http://localhost:5000/resource

● Output: Resource updated!

DELETE Request:

curl -X DELETE
http://localhost:5000/resource

● Output: Resource deleted!


Combining URL Building with HTTP Methods
Example: Login Form

1. The form dynamically generates the


action URL using url_for('login').
2. Handles both GET (display form)
and POST (process login).
Templates and Static Files
1. Templates in Flask
What Are Templates?
● Templates are HTML files used to dynamically generate content for web pages.
● Flask uses Jinja2, a templating engine, to embed Python-like expressions into HTML files.
● Templates allow passing data from the server to the client dynamically.

Concepts in Templates
1. Dynamic Content: Use placeholders (like {{ variable }}) to insert Python variables into HTML.
2. Control Statements: Use Jinja2 syntax for if conditions, for loops, etc.
3. Template Inheritance Create a base HTML structure and extend it in child templates to reuse common
elements.
How Templates Work
● Flask looks for templates in a folder named templates by default.
● The render_template() function is used to load and render templates with dynamic data.

Example of Using Templates:


Static Files in Flask

● Static files are resources like CSS, JavaScript, images, fonts, or other assets that do not change
dynamically.
● Flask serves static files from a folder named static by default.

How Static Files Work


● Static files are stored in the static folder.
● Use the url_for() function to generate URLs for static files dynamically.

Example: Using static Files:


Contd…
Code (app.py): Template (home.html):
Static files

CSS File (style.css): JavaScript File (script.js):

Output:

● The web page displays:


1. Styled text from style.css.
2. The Flask logo from images/.
3. A console log message from
script.js in the browser's
developer tools.
Combining Templates and Static Files

Flask integrates templates and static files seamlessly. Here's how:

Example: A Complete Flask Web Page Templates/Home.html:


Practices for Templates and Static Files

File Organization:

● Keep templates in the templates folder.


● Keep CSS, JS, and images in respective subfolders under static.

Dynamic URLs:

● Always use url_for() for linking static files or routes.

Template Inheritance:

● Use a base template for common layouts like headers and footers.

Minification:

● Minify CSS and JavaScript files to optimize performance.


Flask App with Database Connectivity in Python

Flask can be used to connect to databases like SQLite, MySQL, or PostgreSQL to store, retrieve,
update, and delete data. Flask provides support for database operations using libraries like sqlite3,
SQLAlchemy (ORM), or connectors like mysql-connector-python for MySQL.

Steps to Connect Flask with a Database

1. Set Up the Database:


○ Create a database (e.g., SQLite, MySQL, etc.) and define its schema.
2. Install Required Libraries:
○ Use the appropriate database library (sqlite3, mysql-connector-python, or psycopg2 for
PostgreSQL).
3. Configure Database in Flask:
○ Add database configurations in the Flask app.
4. Perform CRUD Operations:
○ Create, read, update, and delete data using SQL queries or an ORM.
Example 1: Flask with SQLite (Basic)
Folder Structure: Code Example:app.py
Example contd…
index.html:
Explanation of Example 1

1. Database Initialization:
○ The init_db() function ensures the database and the
users table are created if they don’t already exist.
○ The database file is database.db.
2. Routes:
○ /:
■ Fetches all users from the database and displays
them on the webpage.
■ Executes an SQL SELECT query to retrieve the
data.
○ /add:
■ Handles the form submission for adding a new
user.
■ Inserts the data into the database using an SQL
INSERT query.
■ Redirects back to the home page.
3. Templates:
○ The index.html template dynamically displays all users
fetched from the database using Jinja2 syntax ({% for
user in users %}).
Advantages of Using Databases in Flask Apps

Data Persistence:

● Stores data that persists beyond the application's runtime.

Dynamic Content:

● Dynamically generates web pages based on database content.

Secure Storage:

● Stores user information securely with encryption.


Handling Exceptions and Errors in Flask

Flask provides mechanisms to gracefully handle errors and exceptions. This is critical for building robust
applications and providing user-friendly feedback.

Concepts

1. HTTP Error Handlers: Handle specific HTTP errors (e.g., 404, 500).

1. Custom Exception Handling: Define and handle your application-specific exceptions.

1. Logging: Capture exceptions and log them for debugging.


Example: handling a 404 error.
404 error:

Explanation:

● @app.errorhandler(404): Captures
any 404 Not Found errors.

● render_template('404.html'): displays
a custom 404 error page.

● debug=True: Shows detailed error


pages during development but should
be disabled in production.
Flash Messages in Flask

Flash messages are a way to show temporary notifications to users, such as success, error, or warning
messages.

Key Functions

● flask.flash(message): Creates a flash message.


● flask.get_flashed_messages(): Retrieves and displays flash messages.

Steps to Use Flash Messages

1. Enable sessions in Flask by setting a SECRET_KEY.


2. Use flash() to create a message.
3. Display messages in the template using get_flashed_messages().
Example: Flash Messages
Flash Message HTML Template (index.html):

Explanation:

● flash(message, category): Creates a flash message with an optional category (e.g., success, error).
● get_flashed_messages(): Retrieves all flash messages and their categories for display in the template.
Working with Mails in Flask

Flask provides support for sending emails using the Flask-Mail extension. This is useful for features like account
activation, password reset, or notifications.

Installation
pip install Flask-Mail

Setting Up Flask-Mail

1. Configuration: Add mail server details to your Flask app.

1. Create a Mail Instance: Use the Mail class from Flask-Mail.

1. Send Emails: Use the send method to send emails.


Example: Sending Emails

Explanation:

1. Mail Configuration:
○ MAIL_SERVER: The SMTP server (e.g.,
smtp.gmail.com for Gmail).
○ MAIL_PORT: The port for the SMTP server
(587 for TLS).
○ MAIL_USE_TLS: Enables Transport Layer
Security.
○ MAIL_USERNAME and
MAIL_PASSWORD: Your email credentials.
2. Message Object:
○ sender: Email address sending the email.
○ recipients: List of recipient email addresses.
○ body: The email content.
Contd…
Summary :-

Feature Description Example

Handling Exceptions Use @app.errorhandler for Handle 404 or log errors using
HTTP errors and try...except logging.
for application errors.

Flash Messages Use flash() for temporary Notify users about


notifications; display using successful actions or errors.
get_flashed_messages().

Sending Emails Configure Flask-Mail to send Send account activation


emails via SMTP. Supports links, password resets, or
plain text and HTML emails. notifications.
Authenticating and Authorizing Users with Flask-Login

Authentication (verifying the identity of a user) and authorization (granting access based on roles) are
fundamental for secure web applications. Flask provides the Flask-Login extension to manage these
functionalities.

Features of Flask-Login

● User Session Management: Handles login/logout and session persistence.


● User Loader: Keeps track of the currently logged-in user.
● Login Required Decorator: Protects routes from unauthorized access.

Installation:
Example: Authenticating Users
Step 1: Set up the Flask Application:
Example Contd…

Step 2: Create the User Model


Contd..
Step 3: Define Routes:
Step 4: Templates
Login.html:

home.html:
Deploying a Flask Application to a Web Server

Deployment makes your application accessible to users over the internet. Common steps involve using
production-grade servers and services.

Steps for Deployment

1. Use a Production WSGI Server

● Flask's built-in development server (app.run()) is not suitable for production.


● Use Gunicorn (Linux) or Waitress (Windows).

Example (Linux with Gunicorn):

pip install gunicorn

gunicorn -w 4 -b 0.0.0.0:8000 app:app

● -w 4: Number of worker processes.


● -b: Bind to a specific address and port.
Contd…
2. Use a Reverse Proxy:

Configure Nginx or Apache as a reverse proxy to forward requests to the Flask application.

Example (Nginx):

1. Install Nginx: sudo apt install nginx

2. Configure a server block:


Contd…

3. Deployment Platforms

● Heroku:
1. Install Heroku CLI.
2. Create a Procfile:

1. Deploy:
Contd…

● AWS Elastic Beanstalk: Use Flask with a pre-configured Python environment.


● Docker: Containerize your application and deploy to cloud platforms.

4. Serve Static Files

● Ensure that static files (CSS, JavaScript) are properly served by the web server.
● Place static assets in a /static folder in your Flask project.

Feature Description

Flask-Login Simplifies authentication, session management, and protecting routes.

Deployment It involves using production-grade WSGI servers and reverse proxies.

Platforms Heroku, AWS, Docker, and other cloud services provide easy
deployment.

You might also like