Flask Framework
1. What is Flask?
Flask is a lightweight and versatile Python web framework used to build web applications. It provides tools for routing, handling HTTP requests, and rendering templates. Flask is known for its simplicity, flexibility, and modular design.
2. Core Features
- Lightweight: Minimalistic, allowing developers to add only the components they need.
- Routing: Built-in support for mapping URLs to functions.
- Template Rendering: Uses the Jinja2 template engine for creating dynamic HTML content.
- Extensible: Allows easy integration with extensions like Flask-SQLAlchemy and Flask-WTF.
3. Basic Flask Application
A simple example of a Flask app that responds to requests at the root URL:
# Flask Basic App
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run()Explanation:
Flask(__name__): Creates the Flask application object.@app.route(): A decorator that maps a URL to the specified function.app.run(): Starts the server.
4. Routing in Flask
Routing allows mapping of URLs to specific functions in the application.
@app.route('/about')
def about():
return "This is the About page."
@app.route('/contact')
def contact():
return "This is the Contact page."Explanation:
@app.route('/about'): Maps the URL/aboutto theaboutfunction.@app.route('/contact'): Maps the URL/contactto thecontactfunction.
5. Dynamic Routing and Template Rendering
Flask supports dynamic URLs and renders templates using Jinja2.
from flask import render_template
@app.route('/greet/')
def greet(name):
return render_template('greet.html', name=name) Template (greet.html):
<!DOCTYPE html>
<html>
<head>
<title>Greeting</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
Explanation:
/greet/<name>: A dynamic URL where<name>is a variable passed to the function.render_template(): Renders thegreet.htmltemplate, passingnameas a context variable.{{ name }}: A Jinja2 placeholder replaced by the actual value ofname.
6. Handling HTTP Methods
Flask supports HTTP methods like GET and POST to handle user input and form submissions.
from flask import request
@app.route('/submit', methods=['POST'])
def submit():
data = request.form['data']
return f"Received: {data}"Explanation:
@app.route('/submit', methods=['POST']): Specifies that this route handles POST requests.request.form: Accesses form data submitted by the user.
7. Running the Application
- Save the Flask application in a Python file (e.g.,
app.py). - Run the application using
python app.py. - Access the application in a web browser at
http://localhost:5000.
8. Advantages of Flask
- Simple and easy to use, making it great for beginners.
- Highly flexible and supports extensions for advanced features.
- Suitable for both small-scale and large-scale applications.