Flask is a micro - framework, which means it provides only the essential components for building a web application. Here are some core concepts:
Routes are used to map URLs to Python functions. When a user visits a specific URL, Flask calls the corresponding function and returns the response.
from flask import Flask
# Create a Flask application instance
app = Flask(__name__)
# Define a route for the root URL
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
In this example, the @app.route('/')
decorator binds the hello_world
function to the root URL (/
). When a user visits the root URL of the application, the hello_world
function is called, and it returns the string 'Hello, World!'
.
Flask uses Jinja2 as its templating engine. Templates allow you to separate the presentation logic from the business logic.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
In the templates
directory, you can create an index.html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF - 8">
<title>My Flask App</title>
</head>
<body>
<h1>Welcome to my Flask application!</h1>
</body>
</html>
Flask provides objects to handle incoming requests and send responses. The request
object contains information about the incoming HTTP request, such as form data, query parameters, etc.
from flask import Flask, request
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
username = request.form.get('username')
password = request.form.get('password')
return f'Username: {username}, Password: {password}'
if __name__ == '__main__':
app.run(debug=True)
A blogging platform is a classic Flask project idea. You can implement features like user registration, post creation, editing, and deletion, and categorization of posts.
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///blog.db'
db = SQLAlchemy(app)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
@app.route('/')
def index():
posts = Post.query.all()
return render_template('index.html', posts=posts)
@app.route('/create', methods=['GET', 'POST'])
def create():
if request.method == 'POST':
title = request.form.get('title')
content = request.form.get('content')
new_post = Post(title=title, content=content)
db.session.add(new_post)
db.session.commit()
return redirect(url_for('index'))
return render_template('create.html')
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)
An e - commerce store allows users to browse products, add them to the cart, and checkout. You can integrate payment gateways like PayPal or Stripe.
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///store.db'
db = SQLAlchemy(app)
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
price = db.Column(db.Float, nullable=False)
@app.route('/')
def index():
products = Product.query.all()
return render_template('index.html', products=products)
@app.route('/add_to_cart/<int:product_id>')
def add_to_cart(product_id):
product = Product.query.get(product_id)
# Here you can implement cart logic
return redirect(url_for('index'))
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)
A task management system helps users organize their tasks. You can implement features like task creation, marking tasks as completed, and categorizing tasks.
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///tasks.db'
db = SQLAlchemy(app)
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
completed = db.Column(db.Boolean, default=False)
@app.route('/')
def index():
tasks = Task.query.all()
return render_template('index.html', tasks=tasks)
@app.route('/add_task', methods=['POST'])
def add_task():
title = request.form.get('title')
new_task = Task(title=title)
db.session.add(new_task)
db.session.commit()
return redirect(url_for('index'))
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)
A social media app allows users to create profiles, post updates, follow other users, and like and comment on posts.
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///social.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), unique=True, nullable=False)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship('User', backref=db.backref('posts', lazy=True))
@app.route('/')
def index():
posts = Post.query.all()
return render_template('index.html', posts=posts)
@app.route('/create_post', methods=['POST'])
def create_post():
content = request.form.get('content')
user = User.query.first() # For simplicity, using the first user
new_post = Post(content=content, user=user)
db.session.add(new_post)
db.session.commit()
return redirect(url_for('index'))
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)
unittest
or pytest
to write unit and integration tests for your Flask application. This helps catch bugs early and ensures the stability of your application.Flask is a powerful and versatile web framework that offers numerous opportunities for building projects to enhance your portfolio. By exploring different project ideas such as blogging platforms, e - commerce stores, task management systems, and social media apps, you can showcase your skills in web development, Python programming, and database management. However, it’s important to be aware of common pitfalls and follow best practices to build secure, scalable, and maintainable applications.