Creating a Python Flask application to compare and rank multiple mobile phones is an exciting project! Below is a step-by-step guide to help you develop this application with an admin panel, comparison features, scoring system, and a minimalistic modern UI/UX.
Table of Contents
- Project Setup
- Database Design
- Creating the Flask Application
- Admin Panel Implementation
- User Interface Implementation
- Comparison Feature Implementation
- Scoring System Implementation
- Modern UI/UX Design
- Final Touches
1. Project Setup
Prerequisites:
- Python 3.7 or higher
- Virtual Environment (optional but recommended)
- Flask
- Flask extensions:
- Flask-Admin
- Flask-WTF
- Flask-Login
- SQLAlchemy
- Database: SQLite for simplicity or PostgreSQL/MySQL for production
- Front-end frameworks/libraries:
- Bootstrap 5 or Tailwind CSS for responsive design
- jQuery (optional)
Setup Steps:
-
Create a project directory:
mkdir phone_comparer
cd phone_comparer
-
Set up a virtual environment:
python3 -m venv venv
source venv/bin/activate
-
Install required packages:
pip install Flask Flask-Admin Flask-WTF Flask-Login Flask_SQLAlchemy
2. Database Design
Designing the database schema is crucial. We need tables to store:
- Users (for admin login)
- Phones (phone details)
- Specifications (detailed specs of each phone)
Database Models:
-
User Model:
id
username
password_hash
is_admin
-
Phone Model:
id
name
brand
image_url
release_date
-
Specification Model:
id
phone_id (ForeignKey to Phone)
spec_name
spec_value
3. Creating the Flask Application
Create a file named app.py.
Basic Flask App Structure:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key' # Replace with a secure secret key
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///phones.db'
db = SQLAlchemy(app)
login_manager = LoginManager(app)
# Import models and routes
from models import User, Phone, Specification
import routes
if __name__ == '__main__':
app.run(debug=True)
4. Admin Panel Implementation
Use Flask-Admin to create an admin interface.
Setting Up Flask-Admin:
Install Flask-Admin if not already installed:
pip install Flask-Admin
Define Models in models.py:
from app import db
from flask_login import UserMixin
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(150), nullable=False, unique=True)
password_hash = db.Column(db.String(128))
is_admin = db.Column(db.Boolean, default=False)
# Password methods omitted for brevity
class Phone(db.Model):
__tablename__ = 'phones'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(150), nullable=False)
brand = db.Column(db.String(100))
image_url = db.Column(db.String(250))
release_date = db.Column(db.Date)
specifications = db.relationship('Specification', backref='phone', lazy=True)
class Specification(db.Model):
__tablename__ = 'specifications'
id = db.Column(db.Integer, primary_key=True)
phone_id = db.Column(db.Integer, db.ForeignKey('phones.id'), nullable=False)
spec_name = db.Column(db.String(100))
spec_value = db.Column(db.String(200))
Initialize Admin in app.py:
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
admin = Admin(app, name='Phone Comparer Admin', template_mode='bootstrap4')
# Protect admin views
class AdminModelView(ModelView):
def is_accessible(self):
# Logic to check if user is admin
return current_user.is_authenticated and current_user.is_admin
def inaccessible_callback(self, name, **kwargs):
# Redirect to login page if user doesn't have access
return redirect(url_for('login', next=request.url))
admin.add_view(AdminModelView(Phone, db.session))
admin.add_view(AdminModelView(Specification, db.session))
Implement User Authentication:
Implement user login/logout routes and forms using Flask-Login and Flask-WTF.
5. User Interface Implementation
Templates and Static Files Structure:
- templates/
- layout.html (base template)
- index.html
- phone_list.html
- compare.html
- login.html
- static/
Base Template (layout.html):
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta tags and links to CSS/JS -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
<title>{% block title %}Phone Comparer{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
<script src="{{ url_for('static', filename='js/scripts.js') }}"></script>
</body>
</html>
Index Page (index.html):
{% extends "layout.html" %}
{% block title %}Home - Phone Comparer{% endblock %}
{% block content %}
<h1>Welcome to Phone Comparer</h1>
<a href="{{ url_for('phone_list') }}">Compare Phones</a>
{% endblock %}
6. Comparison Feature Implementation
Phone List Page with 'Add for Comparing' Feature (phone_list.html):
{% extends "layout.html" %}
{% block title %}Phone List{% endblock %}
{% block content %}
<h2>Select Phones to Compare</h2>
<form method="post" action="{{ url_for('compare') }}">
{% for phone in phones %}
<div class="phone-item">
<img src="{{ phone.image_url }}" alt="{{ phone.name }}">
<h3>{{ phone.name }}</h3>
<p>{{ phone.brand }}</p>
<input type="checkbox" name="phone_ids" value="{{ phone.id }}"> Add for comparing
</div>
{% endfor %}
<button type="submit">Compare Selected Phones</button>
</form>
{% endblock %}
Comparison Logic in routes.py:
from flask import render_template, request, redirect, url_for
from app import app, db
from models import Phone
@app.route('/phones', methods=['GET'])
def phone_list():
phones = Phone.query.all()
return render_template('phone_list.html', phones=phones)
@app.route('/compare', methods=['POST'])
def compare():
phone_ids = request.form.getlist('phone_ids')
if len(phone_ids) < 2:
# Flash message to select at least two phones
return redirect(url_for('phone_list'))
selected_phones = Phone.query.filter(Phone.id.in_(phone_ids)).all()
return render_template('compare.html', phones=selected_phones)
7. Scoring System Implementation
Implement a function that assigns scores to each feature based on available technology.
Scoring Logic:
- Define the latest technology features and assign scores.
- Compare each phone's specs against these features.
- Sum up the scores for each phone.
Example Scoring Function:
def calculate_scores(phones):
# Example technology standards
tech_standards = {
'RAM': {'High': 12, 'Medium': 8, 'Low': 4},
'Camera': {'High': 108, 'Medium': 64, 'Low': 12},
'Battery': {'High': 5000, 'Medium': 4000, 'Low': 3000},
# Add more specs as needed
}
phone_scores = {}
for phone in phones:
score = 0
for spec in phone.specifications:
if spec.spec_name == 'RAM':
# Compare RAM size and assign score
pass # Implement scoring logic
# Repeat for other specs
phone_scores[phone.id] = score
return phone_scores
Update Compare Route:
@app.route('/compare', methods=['POST'])
def compare():
phone_ids = request.form.getlist('phone_ids')
if len(phone_ids) < 2:
# Flash message to select at least two phones
return redirect(url_for('phone_list'))
selected_phones = Phone.query.filter(Phone.id.in_(phone_ids)).all()
scores = calculate_scores(selected_phones)
return render_template('compare.html', phones=selected_phones, scores=scores)
Comparison Page (compare.html):
{% extends "layout.html" %}
{% block title %}Compare Phones{% endblock %}
{% block content %}
<h2>Comparison Results</h2>
<table>
<thead>
<tr>
<th>Feature</th>
{% for phone in phones %}
<th>{{ phone.name }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
<!-- Iterate over specifications and display them -->
{% for spec_name in all_spec_names %}
<tr>
<td>{{ spec_name }}</td>
{% for phone in phones %}
<td>{{ phone.get_spec_value(spec_name) }}</td>
{% endfor %}
</tr>
{% endfor %}
<tr>
<td>Total Score</td>
{% for phone in phones %}
<td>{{ scores[phone.id] }}</td>
{% endfor %}
</tr>
</tbody>
</table>
{% endblock %}
8. Modern UI/UX Design
To achieve a minimal and modern UI/UX:
- Use a CSS Framework: Utilize Bootstrap 5 or Tailwind CSS for responsive and modern components.
- Consistent Color Scheme: Choose a minimalistic color palette.
- Responsive Design: Ensure the website is mobile-friendly.
Integrate Bootstrap (Example):
Include Bootstrap CSS and JS in layout.html:
<!-- In the <head> section -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Before the closing </body> tag -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
Custom Styles:
Create styles.css in static/css/ for additional custom styles.
9. Final Touches
Security Considerations:
- Input Validation: Ensure all user inputs are properly validated and escaped to prevent XSS and SQL injection.
- Secure Password Storage: Use werkzeug's
generate_password_hash and check_password_hash for password handling.
- User Authentication/Authorization: Protect admin routes and data.
Testing:
- Unit Tests: Write tests for your calculation functions and routes.
- Functional Tests: Manually test the UI to ensure all features work as expected.
Deployment:
- Production Server: Use a production-ready server like Gunicorn or uWSGI.
- Reverse Proxy: Set up Nginx as a reverse proxy.
- SSL/TLS Certificates: Use HTTPS for secure communication.
Summary
By following the steps above, you will create a Flask application with:
- An admin panel to add new phone details and images.
- A feature allowing users to select phones for comparison.
- A scoring system that evaluates phones based on predefined technology standards.
- A minimalistic and modern UI/UX powered by Bootstrap.
Additional Recommendations
- Optimize Images: Compress images to improve load times.
- Pagination: If you have many phones, implement pagination on the phone list page.
- Search and Filters: Add search functionality to find phones by name or filter by brand.
Feel free to ask if you have any questions or need further assistance with specific parts of the implementation!