Flask is a lightweight and powerful web framework for Python that enables developers to build web applications quickly and efficiently. It is known for its simplicity, flexibility, and ease of use, making it a popular choice for both beginners and experienced developers.
Why Use Flask?
Flask offers several advantages that make it an excellent choice for web development:
- Lightweight and Minimal: Unlike Django, Flask provides only the essential tools, allowing developers to build applications with greater flexibility.
- Easy to Learn: Its simple syntax makes it beginner-friendly.
- Built-in Development Server: Helps in testing applications quickly.
- Extensible: Supports plugins and third-party extensions.
- RESTful Support: Ideal for building APIs and microservices.
Installing Flask
To get started, install Flask using pip
:
pip install Flask
Once installed, you can verify it by running:
import flask
print(flask.__version__)
Creating Your First Flask Application
Step 1: Setting Up a Basic Flask App
Create a file app.py
and add the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
Step 2: Running the Application
Run the script using:
python app.py
You will see output similar to:
* Running on http://127.0.0.1:5000/
Open the URL in your browser, and you will see “Hello, Flask!” displayed.
Understanding Flask Routes
In Flask, routes define how URLs map to functions. The @app.route()
decorator is used to bind a URL to a view function.
Example: Multiple Routes
@app.route('/')
def home():
return "Welcome to the Homepage!"
@app.route('/about')
def about():
return "This is the About Page."
Now, accessing /about
will return “This is the About Page.”
Rendering HTML with Flask
Instead of returning plain text, Flask allows rendering HTML templates using Jinja2.
Step 1: Creating a templates
Folder
Flask looks for HTML templates in a folder named templates
. Create a file named index.html
inside a templates
directory:
<!DOCTYPE html>
<html>
<head>
<title>Flask App</title>
</head>
<body>
<h1>Welcome to Flask!</h1>
</body>
</html>
Step 2: Rendering the Template
Modify app.py
to use render_template
:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
Now, visiting the homepage will render the HTML page.
Handling Dynamic URLs
Flask allows passing dynamic parameters in URLs.
Example: Dynamic Routes
@app.route('/user/<name>')
def user(name):
return f"Hello, {name}!"
Visiting /user/John
will display “Hello, John!”
Flask Forms and Request Handling
Flask provides support for handling form submissions using request
.
Example: Handling a Form Submission
Create form.html
inside templates
:
<form action="/submit" method="post">
<input type="text" name="username" placeholder="Enter your name">
<input type="submit" value="Submit">
</form>
Modify app.py
to handle form data:
from flask import request
@app.route('/submit', methods=['POST'])
def submit():
name = request.form['username']
return f"Hello, {name}!"
Now, submitting the form will greet the user.
Building a REST API with Flask
Flask can be used to build RESTful APIs using Flask-RESTful
.
Step 1: Install Flask-RESTful
bashCopyEditpip install flask-restful
Step 2: Create a Simple API
from flask import Flask, jsonify
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {"message": "Hello, API!"}
api.add_resource(HelloWorld, '/api')
if __name__ == '__main__':
app.run(debug=True)
Accessing /api
returns:
{"message": "Hello, API!"}
Flask with Database (SQLite)
Flask supports databases using Flask-SQLAlchemy
.
Step 1: Install SQLAlchemy
pip install flask-sqlalchemy
Step 2: Configure Database
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
@app.route('/add/<name>')
def add_user(name):
user = User(name=name)
db.session.add(user)
db.session.commit()
return f"User {name} added!"
Running this will create database.db
and add users dynamically.
Flask Deployment
To deploy Flask applications:
- Use Gunicorn for production servers. bashCopyEdit
pip install gunicorn gunicorn -w 4 app:app
- Deploy on Heroku, AWS, or DigitalOcean.
- Use Docker for containerization.