PPFD 4
PPFD 4
● 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….
1. Install virtualenv:
Contd..
● Create and activate a virtual Environment
● Install Flask
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:
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!".
● 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.
● Syntax:
endpoint: The name of the function linked to a route.
Benefits:
● 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
How it Works:
DELETE Request:
curl -X DELETE
http://localhost:5000/resource
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.
● 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.
Output:
File Organization:
Dynamic URLs:
Template Inheritance:
● Use a base template for common layouts like headers and footers.
Minification:
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.
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:
Dynamic Content:
Secure Storage:
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).
Explanation:
● @app.errorhandler(404): Captures
any 404 Not Found errors.
● render_template('404.html'): displays
a custom 404 error page.
Flash messages are a way to show temporary notifications to users, such as success, error, or warning
messages.
Key Functions
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
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 :-
Handling Exceptions Use @app.errorhandler for Handle 404 or log errors using
HTTP errors and try...except logging.
for application errors.
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
Installation:
Example: Authenticating Users
Step 1: Set up the Flask Application:
Example Contd…
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.
Configure Nginx or Apache as a reverse proxy to forward requests to the Flask application.
Example (Nginx):
3. Deployment Platforms
● Heroku:
1. Install Heroku CLI.
2. Create a Procfile:
1. Deploy:
Contd…
● 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
Platforms Heroku, AWS, Docker, and other cloud services provide easy
deployment.