Welcome to your first steps into the world of Flask! Flask is a lightweight and powerful web framework for Python that makes it easy to build web applications. In this guide, we'll walk through the essential concepts of Flask in simple terms with examples and explanations for beginners.
π§ Introduction to Flask Framework
Flask is a micro web framework written in Python. Itβs called βmicroβ because it doesnβt require particular tools or libraries. It gives you the flexibility to choose your components.
Why Flask?
- Simple and easy to learn
- Great for small to medium-sized applications
- Large community and lots of extensions
Installation
To install Flask, use pip:
pip install flask
ποΈ Understanding a Simple Flask App Skeleton
Hereβs the basic structure of a Flask app:
from flask import Flask
app = Flask(__name__) # Create a Flask app instance
@app.route('/') # Define a route for the home page
def home():
return "Hello, Flask!" # Return a simple response
if __name__ == '__main__':
app.run(debug=True) # Run the app in debug mode
Explanation:
-
Flask(__name__): Initializes the app.__name__helps Flask locate resources. -
@app.route('/'): Maps the URL/to thehome()function. -
home(): Returns a response when the route is accessed. -
app.run(debug=True): Starts the server and shows errors in the browser.
π Integrating HTML with Flask Web App
Flask can render HTML templates using the render_template() function.
Folder Structure:
project/
βββ app.py
βββ templates/
βββ index.html
app.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html') # Renders the HTML file
templates/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Flask App</title>
</head>
<body>
<h1>Welcome to Flask!</h1>
</body>
</html>
Explanation:
- Flask looks for HTML files in the
templates/folder. -
render_template()loads and displays the HTML file.
π Working with HTTP Verbs: GET and POST
Flask supports different HTTP methods like GET and POST to handle form data.
Example:
from flask import Flask, request
app = Flask(__name__)
@app.route('/form', methods=['GET', 'POST'])
def form():
if request.method == 'POST':
name = request.form['name'] # Get data from form
return f"Hello, {name}!"
return '''
<form method="post">
Name: <input type="text" name="name">
<input type="submit">
</form>
'''
Explanation:
-
GET: Loads the form. -
POST: Submits the form and processes the data.
π Building Dynamic URLs, Variable Rules, and Jinja2 Template Engine
Dynamic URLs:
@app.route('/user/<username>')
def show_user(username):
return f"User: {username}"
Explanation:
-
<username>is a variable in the URL. - Flask passes it to the function as an argument.
Jinja2 Template Engine
Jinja2 lets you embed Python-like expressions in HTML.
Example profile.html:
<h1>Hello, {{ name }}!</h1>
app.py:
@app.route('/hello/<name>')
def hello(name):
return render_template('profile.html', name=name)
Explanation:
-
{{ name }}is replaced with the actual value passed from Flask.
π Working with REST APIs and HTTP Verbs PUT and DELETE
Flask makes it easy to build RESTful APIs using different HTTP methods.
Example:
from flask import Flask, request, jsonify
app = Flask(__name__)
data = {}
@app.route('/item/<key>', methods=['PUT'])
def put_item(key):
value = request.json.get('value') # Get JSON data
data[key] = value
return jsonify({key: value})
@app.route('/item/<key>', methods=['DELETE'])
def delete_item(key):
if key in data:
del data[key]
return jsonify({'message': 'Deleted'})
return jsonify({'error': 'Not found'}), 404
Explanation:
-
PUT: Adds or updates data. -
DELETE: Removes data if it exists.
β Summary
| Concept | Description |
|---|---|
| Flask | Micro web framework for Python |
| App Skeleton | Basic structure with routes |
| HTML Integration | Use render_template and templates/ folder |
| GET/POST | Handle form data and user input |
| Dynamic URLs | Use <variable> in routes |
| Jinja2 | Template engine for dynamic HTML |
| REST APIs | Build endpoints with PUT and DELETE |
Top comments (0)