Routing is a fundamental concept in Flask. It maps URLs to Python functions, allowing you to define the behavior of your application for different endpoints. In an ecommerce backend, you might have routes for handling product listings, user authentication, and order processing.
from flask import Flask
app = Flask(__name__)
# Route to display all products
@app.route('/products', methods=['GET'])
def get_products():
# Logic to retrieve all products from the database
return 'List of all products'
# Route to create a new order
@app.route('/orders', methods=['POST'])
def create_order():
# Logic to create a new order in the database
return 'Order created successfully'
if __name__ == '__main__':
app.run(debug=True)
Flask provides easy - to - use tools for handling HTTP requests and sending responses. You can access data sent by the client in the request (such as form data or JSON payloads) and return appropriate responses, including status codes and content types.
from flask import Flask, request, jsonify
app = Flask(__name__)
# Route to handle product creation
@app.route('/products', methods=['POST'])
def create_product():
data = request.get_json()
if data and 'name' in data and 'price' in data:
# Logic to save the product to the database
return jsonify({'message': 'Product created successfully'}), 201
return jsonify({'error': 'Invalid data'}), 400
if __name__ == '__main__':
app.run(debug=True)
For an ecommerce backend, you need to store and retrieve data such as products, users, and orders. Flask can be integrated with various databases like SQLite, MySQL, and PostgreSQL. SQLAlchemy is a popular SQL toolkit and Object - Relational Mapping (ORM) library that can be used with Flask to simplify database operations.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///ecommerce.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('/products', methods=['GET'])
def get_products():
products = Product.query.all()
product_list = [{'id': p.id, 'name': p.name, 'price': p.price} for p in products]
return jsonify(product_list)
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)
Flask can be used to build endpoints for creating, reading, updating, and deleting (CRUD) products. This includes handling product details such as name, description, price, and inventory levels.
You can implement user registration, login, and password reset functionality. Additionally, you can use Flask extensions like Flask - Login to manage user sessions and restrict access to certain endpoints based on user roles (e.g., admin users can manage products, regular users can place orders).
Flask can handle the entire order lifecycle, from creating an order when a user checks out to updating the order status as it progresses through payment, fulfillment, and shipping.
Create a virtual environment and install Flask and other necessary packages.
python -m venv venv
source venv/bin/activate # On Windows, use venv\Scripts\activate
pip install flask flask - sqlalchemy
Create classes that represent the tables in your database using SQLAlchemy.
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(120), nullable=False)
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)
class Order(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False)
quantity = db.Column(db.Integer, nullable=False)
Define routes for different functionalities such as user registration, product listing, and order creation.
from flask import Flask, request, jsonify
from models import db, User, Product, Order
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///ecommerce.db'
db.init_app(app)
@app.route('/users', methods=['POST'])
def create_user():
data = request.get_json()
if data and 'username' in data and 'password' in data:
new_user = User(username=data['username'], password=data['password'])
db.session.add(new_user)
db.session.commit()
return jsonify({'message': 'User created successfully'}), 201
return jsonify({'error': 'Invalid data'}), 400
@app.route('/products', methods=['GET'])
def get_products():
products = Product.query.all()
product_list = [{'id': p.id, 'name': p.name, 'price': p.price} for p in products]
return jsonify(product_list)
@app.route('/orders', methods=['POST'])
def create_order():
data = request.get_json()
if data and 'user_id' in data and 'product_id' in data and 'quantity' in data:
new_order = Order(user_id=data['user_id'], product_id=data['product_id'], quantity=data['quantity'])
db.session.add(new_order)
db.session.commit()
return jsonify({'message': 'Order created successfully'}), 201
return jsonify({'error': 'Invalid data'}), 400
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)
Building an ecommerce backend with Flask offers a great combination of simplicity and flexibility. By understanding the core concepts, typical usage scenarios, avoiding common pitfalls, and following best practices, you can create a robust and scalable ecommerce backend. Flask’s rich ecosystem of extensions and the large Python community make it a reliable choice for developing modern ecommerce applications.