Navigation

What is Flask? Core Features Basic Flask Application Routing in Flask Dynamic Routing and Template Rendering Handling HTTP Methods Running the Application Advantages of Flask

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


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:


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:


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:


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:


7. Running the Application

  1. Save the Flask application in a Python file (e.g., app.py).
  2. Run the application using python app.py.
  3. Access the application in a web browser at http://localhost:5000.

8. Advantages of Flask