Flask is a lightweight Python web framework used to build web applications, websites and APIs. It provides the basic tools needed to handle web requests and create dynamic web applications.
Flask is a Python web framework that helps developers create web applications and APIs.
A Flask application can receive a request from a browser, execute Python code and return a response.
Browser
|
| HTTP Request
↓
Flask Application
|
| Python Code
↓
HTTP Response
|
↓
Browser
Flask can be installed using pip.
pip install flask
You can also use:
python -m pip install flask
Create a Python file named app.py.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask!"
if __name__ == "__main__":
app.run()
Run the program:
python app.py
The development server will start and provide a local address that you can open in a browser.
from flask import Flask
The Flask class is imported from the Flask package.
The application object is then created:
app = Flask(__name__)
This object represents the Flask application.
A route connects a URL path to a Python function.
@app.route("/")
def home():
return "Welcome to my website"
When a browser requests the root URL, Flask calls the
home() function.
A Flask application can contain multiple routes.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Home Page"
@app.route("/about")
def about():
return "About Page"
@app.route("/contact")
def contact():
return "Contact Page"
if __name__ == "__main__":
app.run()
Each URL is connected to a different Python function.
Debug mode provides useful development features such as automatic reloading and detailed error information.
app.run(debug=True)
A Flask route can return HTML content.
@app.route("/")
def home():
return """
<h1>Welcome to Flask</h1>
<p>This is my first Flask application.</p>
"""
For larger web pages, Flask commonly uses the Jinja template engine.
HTML templates are normally stored inside a folder named
templates.
Example project structure:
project/
│
├── app.py
│
└── templates/
└── home.html
The render_template() function is used to render an HTML
template.
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("home.html")
Python values can be passed to a template.
@app.route("/")
def home():
name = "Rahul"
return render_template(
"home.html",
student=name
)
Inside home.html:
<h1>Welcome {{ student }}</h1>
Jinja uses double curly braces to display variables.
<h1>{{ name }}</h1>
<p>Course: {{ course }}</p>
Flask passes the values from Python to the template.
Jinja templates can contain conditional logic.
{% if age >= 18 %}
<p>You are an adult.</p>
{% else %}
<p>You are a minor.</p>
{% endif %}
A Jinja for loop can display items from a Python list.
{% for student in students %}
<p>{{ student }}</p>
{% endfor %}
The students list can be supplied by the Flask application.
Dynamic URL parameters can be defined inside a route.
@app.route("/user/<name>")
def user(name):
return "Hello " + name
For example:
/user/Rahul
The value Rahul is passed to the name parameter.
Flask supports converters that allow route parameters to be interpreted as particular types.
@app.route("/student/<int:id>")
def student(id):
return f"Student ID: {id}"
The int converter expects the URL value to be an integer.
A route can specify which HTTP methods it accepts.
from flask import Flask, request
app = Flask(__name__)
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
return "Login submitted"
return "Login form"
The request.form object can be used to access submitted form
data.
from flask import Flask, request
app = Flask(__name__)
@app.route("/login", methods=["POST"])
def login():
username = request.form.get("username")
return "Welcome " + username
Using get() is useful because it returns None when
the key is not present instead of raising a key error.
Query parameters can be accessed through request.args.
from flask import Flask, request
app = Flask(__name__)
@app.route("/search")
def search():
keyword = request.args.get("q")
return "Search: " + str(keyword)
A URL such as:
/search?q=python
provides python as the value of q.
Flask can return JSON data from a route.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/api/student")
def student():
data = {
"id": 1,
"name": "Rahul",
"course": "Python"
}
return jsonify(data)
Flask can be used to build REST-style APIs.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/api/students")
def students():
data = [
{
"id": 1,
"name": "Rahul"
},
{
"id": 2,
"name": "Priya"
}
]
return jsonify(data)
if __name__ == "__main__":
app.run()
The redirect() function can redirect a user to another URL.
from flask import Flask, redirect
app = Flask(__name__)
@app.route("/old")
def old_page():
return redirect("/new")
@app.route("/new")
def new_page():
return "New Page"
The url_for() function generates a URL for a Flask endpoint.
from flask import Flask, url_for
app = Flask(__name__)
@app.route("/")
def home():
print(url_for("about"))
return "Home"
@app.route("/about")
def about():
return "About"
Using endpoint names makes URL generation easier to maintain.
CSS, JavaScript and image files are commonly stored in a
static directory.
project/
│
├── app.py
│
├── static/
│ ├── style.css
│ └── script.js
│
└── templates/
└── home.html
A template can reference a static file using url_for().
<link rel="stylesheet"
href="{{ url_for('static', filename='style.css') }}">
Flask applications can connect to databases such as SQLite, MySQL and PostgreSQL.
A typical application may use Flask for the web layer and a database for storing application data.
Browser
↓
Flask
↓
Python Code
↓
Database
↓
Flask
↓
Browser
A simple Flask project can be organized like this:
myproject/
│
├── app.py
│
├── templates/
│ ├── home.html
│ ├── about.html
│ └── login.html
│
└── static/
├── css/
│ └── style.css
├── js/
│ └── script.js
└── images/
For larger applications, it is common to create the Flask application inside a function rather than creating it directly at module level.
from flask import Flask
def create_app():
app = Flask(__name__)
@app.route("/")
def home():
return "Hello Flask"
return app
This approach can make larger projects easier to configure and test.
Flask can be used as the backend of a full-stack application.
Frontend
HTML + CSS + JavaScript
↓
Flask Backend
↓
Python
↓
MySQL / SQLite
↓
Data
Flask can provide APIs or render HTML pages while the database stores application information.
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
name = "Rahul"
return render_template(
"home.html",
student=name
)
@app.route("/about")
def about():
return "About Page"
if __name__ == "__main__":
app.run(debug=True)
The corresponding home.html file can contain:
<!DOCTYPE html>
<html>
<head>
<title>Flask App</title>
</head>
<body>
<h1>Welcome {{ student }}</h1>
</body>
</html>
Flask(__name__) creates the application object.@app.route() maps a URL to a Python function.render_template() renders HTML templates.request provides access to incoming request data.request.form reads form data.request.args reads query parameters.jsonify() can create JSON responses.redirect() redirects users to another URL.url_for() generates URLs for endpoints.templates folder stores HTML templates.static folder stores CSS, JavaScript and image files.Question: Which decorator is commonly used to connect a URL to a Flask function?