[go: up one dir, main page]

0% found this document useful (0 votes)
12 views16 pages

Flask

Uploaded by

billiyamuna15
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)
12 views16 pages

Flask

Uploaded by

billiyamuna15
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/ 16

Alright let’s go deep into Flask Introduction in very simple English so you have plenty of theory

to explain in class.

Flask Introduction (Detailed for Beginners)

What is Flask?

• Flask is a web framework written in Python.

• A web framework is like a set of ready-made tools and rules that help you build websites and
web applications faster.

• Instead of writing everything from scratch (handling requests, responses, servers, etc.), Flask
already has these things built-in.

Example:

• Without Flask → you’d have to manually create a web server in Python (very hard and long).

• With Flask → just a few lines of code can create a running website.

Why is Flask called “lightweight”?

• Flask gives you only the basics (routes, templates, JSON handling).

• It does not force you to use specific databases or structures.

• You can add only the tools you need (like authentication, databases, etc.) through
extensions.

• This makes Flask very flexible and easy for beginners.

Flask vs. Django (for comparison)

• Flask → Small, simple, flexible. Best for small to medium apps, learning, APIs, and projects.

• Django → Big, heavy, comes with everything (database handling, admin panel, security). Best
for large applications.

So, if you are a beginner, Flask is easier to start with.

What can you build with Flask?

• Simple websites (blogs, portfolios, landing pages).

• Web applications (student portal, online shopping cart).

• REST APIs (for mobile apps, data sharing between systems).

• Machine Learning model deployment (serve ML models as APIs).


History of Flask

• Created by Armin Ronacher in 2010.

• It was first made as a joke project (“April Fool’s joke”), but later became very popular.

• Now it’s one of the most widely used Python web frameworks.

Why learn Flask?

1. Beginner-friendly → very simple code to start.

2. Python-based → easy if you already know Python.

3. Flexible → use it for small apps or extend it for bigger apps.

4. Large community → many tutorials, documentation, and help online.

5. Good for careers → many companies use Flask for APIs and microservices.

How Flask Works (Basic Idea)

1. A browser (like Chrome) sends a request → e.g., open http://127.0.0.1:5000/hello.

2. Flask receives that request.

3. Flask checks which route (/hello) matches this request.

4. Flask runs the Python function linked to that route.

5. That function sends back a response (text, HTML, or JSON).

6. The browser shows it to the user.

So Flask acts like a middleman between the browser and your Python code.

Flask Key Features

• Simple to use.

• Built-in web server for development.

• Routes using @app.route.

• Template system (Jinja2) to return HTML pages.

• Can return text, HTML, or JSON.

• Support for forms and handling user input.

• Can be extended with libraries for databases, authentication, etc.


In short:
Flask is a lightweight, beginner-friendly Python web framework that helps you build websites and
APIs quickly. It is flexible, widely used, and perfect for learning web development.

Perfect Let’s go deep into “Install Flask (pip install flask)” in simple English so you can explain it
in detail to students.

Installing Flask

1. What does “installing” mean?

• When you install Flask, you are downloading a package (a set of Python files) from the
internet and adding it to your computer’s Python environment.

• After installation, you can import Flask in Python and use it to build web apps.

Think of it like adding a new tool to your Python toolbox.

2. What is pip?

• pip stands for “Pip Installs Packages” (or “Pip Installs Python”).

• It is Python’s package manager.

• Just like we install apps on a mobile phone from Play Store/App Store,
we use pip to install Python libraries (like Flask, NumPy, Pandas).

Example:

• On your phone: Install WhatsApp

• In Python: pip install flask

3. How to Install Flask?

Open your Command Prompt / Terminal and type:

pip install flask

• pip → the tool to install Python libraries.

• install → tells pip to install something.

• flask → the name of the package we want.

After pressing Enter, pip will:

1. Connect to the Python Package Index (PyPI) (an online storehouse of Python packages).

2. Download the Flask package.


3. Install it into your system’s Python environment.

4. How to Check if Flask is Installed?

Type:

pip show flask

This will show version, location, and details.

Or open Python and try:

import flask

print(flask.__version__)

If it shows a version number (like 3.0.3), Flask is installed.

5. Virtual Environment (Optional but Good Practice)

• Sometimes, different projects need different versions of Flask.

• To avoid conflicts, we create a virtual environment (a separate folder with its own Python &
packages).

• Steps:

# create virtual environment

python -m venv myenv

# activate it (Windows)

myenv\Scripts\activate

# activate it (Mac/Linux)

source myenv/bin/activate

# install flask inside the env

pip install flask

This keeps Flask separate for each project, like having separate boxes for different tools.

6. Why Do We Need Flask Installed?

• Without installing Flask, Python doesn’t know what “Flask” is.


• When you write:

from flask import Flask

Python looks for the Flask package. If it’s not installed, you’ll get an error:

ModuleNotFoundError: No module named 'flask'

So, installation is the first step before building any Flask project.

In simple words:
Installing Flask with pip install flask is like downloading and adding Flask to your Python toolbox, so
you can use it to create web applications.

Perfect let’s go deep into “First Flask App (app.py)” in simple English so beginners can clearly
understand the concept and the code.

First Flask App (app.py)

1. What is app.py?

• app.py is just a Python file where we write our Flask code.

• By convention, many developers name the main file app.py or main.py.

• This file will create and run the Flask web application.

You can think of app.py as the heart of your web project.

2. Minimum Flask App Code

Here’s the simplest Flask app:

from flask import Flask # 1

app = Flask(__name__) #2

@app.route("/") #3

def home(): #4

return "Hello, Flask!" # 5

if __name__ == "__main__": # 6

app.run(debug=True) #7
3. Line by Line Explanation

Line 1:

from flask import Flask

• This means: “Import the Flask class from the flask library.”

• Just like in math we do import math to use math functions, here we import Flask to build
apps.

Line 2:

app = Flask(__name__)

• We are creating a Flask app object.

• Flask(__name__) tells Flask where to look for files (like templates, static files).

• Think of app as the main controller that manages routes, requests, and responses.

Line 3–5:

@app.route("/")

def home():

return "Hello, Flask!"

• @app.route("/") → defines a route.

o / means the homepage of the website.

• def home(): → a function that will run when someone visits /.

• return "Hello, Flask!" → sends back text to the browser.

If you open http://127.0.0.1:5000/, you’ll see “Hello, Flask!”

Line 6–7:

if __name__ == "__main__":

app.run(debug=True)

• This is Python’s way of saying: “Run this file directly.”

• app.run() → starts a small web server on your computer.

• debug=True →

o Shows detailed error messages if something goes wrong.


o Automatically restarts the server if you change your code (no need to restart
manually).

4. Running the App

1. Save the file as app.py.

2. In terminal, type:

3. python app.py

4. You’ll see something like:

5. * Running on http://127.0.0.1:5000/

6. Open your browser → go to that link → you’ll see Hello, Flask!

5. What Did We Just Do?

• We created a Flask object (app).

• We defined a route (/) that returns a message.

• We ran a development server that responds to requests.

This is the smallest working web app possible in Flask.

6. Analogy (Simple Example)

• Think of Flask app like a restaurant:

o app = Flask(__name__) → opening the restaurant.

o @app.route("/") → the menu (decides what to serve when someone asks for /).

o def home() → the chef (decides what to return).

o app.run() → starts the restaurant service so customers (browsers) can visit.

In short:
Your first Flask app (app.py) creates a Flask object, sets up a route for /, and runs a local server.
When you visit the address in the browser, Flask shows the response defined in your Python
function.

Great let’s go deep into Flask Routes (@app.route) in simple English so beginners can
understand the concept fully.
Flask Routes (@app.route)

1. What is a Route?

• A route is like a path or address on your website.

• Example:

o https://www.google.com/ → homepage

o https://www.google.com/search → search page

o https://www.google.com/maps → maps page

Each page on a website has its own route (path).

2. Flask and Routes

• In Flask, we use @app.route("...") to define which Python function should run when a user
visits a specific route.

• The route and the function are connected.

• When someone visits that route, Flask calls the function and returns the result to the
browser.

3. Example of a Route

from flask import Flask

app = Flask(__name__)

@app.route("/")

def home():

return "Welcome to the Home Page!"

@app.route("/about")

def about():

return "This is the About Page."

Explanation:

• @app.route("/") → homepage route (default).

• home() → function that returns text.


• @app.route("/about") → about page route.

• about() → function that runs when /about is visited.

4. How It Works (Step by Step)

1. You type http://127.0.0.1:5000/ in your browser.

2. Flask sees the / route and calls the home() function.

3. The function returns "Welcome to the Home Page!".

4. Flask sends this back to your browser.

5. You see the message on the screen.

If you type http://127.0.0.1:5000/about, Flask runs about() instead.

5. Routes Can Have Multiple Pages

You can add as many routes as you want:

@app.route("/contact")

def contact():

return "Contact us at support@example.com"

Now, visiting /contact will show this message.

6. Dynamic Routes (with variables)

Sometimes routes need to change depending on the user.


Example:

@app.route("/user/<name>")

def user(name):

return f"Hello, {name}!"

Visiting /user/Nazeer → shows Hello, Nazeer!


Visiting /user/Ali → shows Hello, Ali!

7. Key Points About Routes

• Routes always start with /.

• Each route is connected to one function.

• That function must return something (text, HTML, or JSON).


• You can have many routes in the same Flask app.

8. Real-World Analogy

Think of a house with many doors:

• / → main entrance (homepage).

• /about → second door (about page).

• /contact → third door (contact page).

When someone opens a door (route), Flask decides what to show inside (function result).

In short:

• A route is the web address of a page.

• @app.route connects a URL path to a Python function.

• The function decides what to return when that route is visited.

Perfect let’s dive into Returning HTML/Text with Flask in simple English, with lots of theory and
examples for beginners.

Returning HTML/Text with Flask

1. What does “returning” mean?

• When someone opens a page on your Flask app, Flask must send back a response to the
browser.

• That response can be:

o Plain text → simple words like "Hello Flask!"

o HTML → structured code that the browser renders as a web page

Example:

• Return text → browser just shows words.

• Return HTML → browser displays styled headings, paragraphs, etc.

2. Returning Plain Text

This is the simplest case.

from flask import Flask


app = Flask(__name__)

@app.route("/hello")

def hello():

return "Hello, Flask!"

Explanation:

• Visiting /hello → browser will only show plain text: Hello, Flask!

• No formatting, just simple text.

3. Returning HTML Code

Flask can also return HTML directly from the function.

@app.route("/html")

def html_page():

return "<h1>Welcome to Flask</h1><p>This is an HTML page.</p>"

Explanation:

• <h1> ... </h1> → big bold heading.

• <p> ... </p> → paragraph text.

• Browser understands HTML and formats it nicely.

So, the result looks like:


Welcome to Flask (big bold text)
This is an HTML page. (normal text)

4. Difference Between Text and HTML

Plain Text HTML

Just raw text Structured with tags

No styling Can use headings, colors, links, images

Output looks basic Output looks like a web page

Example:

• Text: "Hello, Flask!"

• HTML: "<h1>Hello, Flask!</h1>" (shows as a big heading).


5. Why Do We Return HTML?

• Because all websites are built with HTML.

• Returning text is only good for testing.

• Returning HTML lets us build real web pages.

6. Returning Multi-Line HTML (Better Way)

You can use triple quotes (""") to return multiple lines:

@app.route("/multi")

def multi():

return """

<html>

<head><title>Flask Page</title></head>

<body>

<h1>Hello from Flask!</h1>

<p>This is a multi-line HTML page.</p>

</body>

</html>

"""

This looks more like a proper web page.

7. Why Not Put All HTML in Python?

• For small apps, it’s fine.

• But real websites have large HTML files → mixing them inside Python makes code messy.

• That’s why Flask also uses templates (separate HTML files stored in templates/ folder).

• But at beginner level, returning simple HTML from functions is enough to learn.

8. Real-World Analogy

• Returning plain text → like sending someone an SMS: just words.

• Returning HTML → like sending a greeting card: it has design, colors, structure.
In short:

• Flask functions return a response to the browser.

• The response can be plain text or HTML.

• Text is simple, but HTML makes real web pages.

• For small demos → return HTML inside Python. For big apps → use templates.

Perfect let’s go step by step into “Returning JSON with jsonify()” in simple English, with lots of
beginner-friendly theory, examples, and analogies.

Returning JSON with jsonify()

1. First, What is JSON?

• JSON = JavaScript Object Notation.

• It is a data format used to send information between computers, websites, and apps.

• Looks like a Python dictionary but written in a standard way that all programming languages
understand.

Example of JSON:

"name": "Nazeer",

"age": 22,

"is_student": true

2. Why Do We Need JSON in Flask?

• Websites and mobile apps often need to exchange data.

• Example:

o A mobile app sends login details to a server.

o The server (Flask) checks them and returns JSON (success or failure).

• JSON is lightweight, easy to read, and universal.

In short: JSON is the language of data exchange between apps.

3. What is jsonify()?
• Flask provides a built-in function called jsonify().

• It converts Python data (like dictionaries or lists) into JSON format automatically.

• Also, it sets the Content-Type header to "application/json" so the browser or API client
knows it’s JSON.

4. Example: Returning JSON in Flask

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/api/hello")

def api_hello():

return jsonify({"message": "Hello Flask!"})

Explanation:

• jsonify({"message": "Hello Flask!"}) → converts Python dictionary into JSON.

• Visiting /api/hello will return:

"message": "Hello Flask!"

5. Line-by-Line Explanation

1. from flask import Flask, jsonify

o Import Flask and jsonify.

2. app = Flask(__name__)

o Create the Flask app.

3. @app.route("/api/hello")

o Define the route /api/hello.

4. def api_hello(): return jsonify({"message": "Hello Flask!"})

o When user visits /api/hello, Flask returns JSON instead of plain text.

6. Returning More Complex JSON


You can return lists, nested dictionaries, etc.

@app.route("/api/user")

def user():

return jsonify({

"name": "Ali",

"age": 21,

"skills": ["Python", "Flask", "SQL"]

})

Output JSON:

"name": "Ali",

"age": 21,

"skills": ["Python", "Flask", "SQL"]

7. Why Use jsonify() Instead of return?

• You could return a string:

return '{"message": "Hello"}'

But problems:

• You must type JSON manually.

• No automatic header (Content-Type: application/json).

• Harder to manage for big data.

jsonify() does all of this automatically .

8. Real-World Example

• You order food on Swiggy/Zomato.

• The app asks the server → “Show me restaurant list.”

• The server (maybe built with Flask) returns data in JSON format:

{"name": "Pizza Hut", "rating": 4.2},

{"name": "Dominos", "rating": 4.0}


]

• The app displays it nicely in your phone.

Behind the scenes, Flask is returning JSON.

9. Real-World Analogy

• Returning text/HTML → like giving someone a printed brochure (human-readable).

• Returning JSON → like giving another computer a spreadsheet of data (machine-readable).

In short:

• JSON = format for data exchange (like a universal dictionary).

• jsonify() = Flask helper to return JSON easily and correctly.

• Used in APIs and mobile/web app communication.

You might also like