Spaces:
Sleeping
Sleeping
File size: 20,523 Bytes
727af35 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 7c11adf f2671e4 727af35 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 727af35 751d8f1 f2671e4 751d8f1 727af35 751d8f1 f2671e4 751d8f1 f2671e4 751d8f1 727af35 751d8f1 727af35 751d8f1 727af35 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 | from flask import Flask, render_template, request, redirect, url_for, flash, jsonify, session
import sqlite3
import os
from datetime import datetime
from werkzeug.security import check_password_hash, generate_password_hash
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.secret_key = "fruit_veg_secret_key"
# Create directories
def create_directories():
if not os.path.exists('static/images'):
os.makedirs('static/images')
# Create directories at startup
create_directories()
# Database initialization
def init_db():
conn = sqlite3.connect('fruitsveggies.db')
cursor = conn.cursor()
# Create admin users table
cursor.execute('''
CREATE TABLE IF NOT EXISTS admin_users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
phone TEXT NOT NULL UNIQUE,
password TEXT NOT NULL
)
''')
cursor.execute('''
PRAGMA table_info(users)
''')
columns = [column[1] for column in cursor.fetchall()]
if 'address' not in columns:
cursor.execute('''
ALTER TABLE users ADD COLUMN address TEXT
''')
# Check if admin user exists, if not create a default one
cursor.execute("SELECT COUNT(*) FROM admin_users")
count = cursor.fetchone()[0]
if count == 0:
# Create default admin user: username 'admin', password 'admin123'
hashed_password = generate_password_hash('admin123')
cursor.execute("INSERT INTO admin_users (username, password) VALUES (?, ?)",
('admin', hashed_password))
# Create products table
cursor.execute('''
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT NOT NULL,
price REAL NOT NULL,
image TEXT NOT NULL,
category TEXT NOT NULL
)
''')
# Create orders table
cursor.execute('''
CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
customer_name TEXT NOT NULL,
mobile TEXT NOT NULL,
address TEXT NOT NULL,
payment_method TEXT NOT NULL,
order_date TIMESTAMP NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL,
FOREIGN KEY (product_id) REFERENCES products (id)
)
''')
# Check if products already exist to avoid duplicates
cursor.execute("SELECT COUNT(*) FROM products")
count = cursor.fetchone()[0]
if count == 0:
# Vegetables data
vegetables = [
('Carrot', 'Fresh organic carrots rich in vitamin A', 1.99, 'carrot.jpg', 'vegetable'),
('Broccoli', 'Nutritious green broccoli florets', 2.49, 'broccoli.jpg', 'vegetable'),
('Spinach', 'Leafy green spinach packed with iron', 1.79, 'spinach.jpg', 'vegetable'),
('Potato', 'Russet potatoes perfect for baking or mashing', 0.99, 'potato.jpg', 'vegetable'),
('Tomato', 'Ripe red tomatoes grown locally', 1.49, 'tomato.jpg', 'vegetable'),
('Cucumber', 'Crisp cucumbers perfect for salads', 1.29, 'cucumber.jpg', 'vegetable'),
('Bell Pepper', 'Sweet bell peppers in various colors', 1.89, 'bell_pepper.jpg', 'vegetable'),
('Onion', 'Yellow onions for cooking and flavoring', 0.89, 'onion.jpg', 'vegetable'),
('Zucchini', 'Fresh green zucchini for grilling or sautéing', 1.59, 'zucchini.jpg', 'vegetable'),
('Eggplant', 'Large purple eggplants for roasting', 2.29, 'eggplant.jpg', 'vegetable')
]
# Fruits data
fruits = [
('Apple', 'Crisp sweet apples from local orchards', 1.29, 'apple.jpg', 'fruit'),
('Banana', 'Ripe yellow bananas rich in potassium', 0.59, 'banana.jpg', 'fruit'),
('Orange', 'Juicy oranges packed with vitamin C', 0.99, 'orange.jpg', 'fruit'),
('Strawberry', 'Sweet red strawberries, locally grown', 3.99, 'strawberry.jpg', 'fruit'),
('Grapes', 'Seedless green grapes in bunches', 2.99, 'grapes.jpg', 'fruit'),
('Watermelon', 'Sweet and refreshing watermelon slices', 4.99, 'watermelon.jpg', 'fruit'),
('Pineapple', 'Tropical sweet pineapple', 3.49, 'pineapple.jpg', 'fruit'),
('Mango', 'Sweet and fragrant mangoes', 1.99, 'mango.jpg', 'fruit'),
('Blueberry', 'Antioxidant-rich blueberries', 4.49, 'blueberry.jpg', 'fruit'),
('Kiwi', 'Tangy green kiwi fruit rich in vitamin C', 0.79, 'kiwi.jpg', 'fruit')
]
# Insert vegetables and fruits into products table
cursor.executemany("INSERT INTO products (name, description, price, image, category) VALUES (?, ?, ?, ?, ?)", vegetables + fruits)
conn.commit()
conn.close()
# Initialize database on startup
init_db()
# Routes
@app.route('/')
def home():
conn = sqlite3.connect('fruitsveggies.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# Get categories for filter
cursor.execute("SELECT DISTINCT category FROM products")
categories = [dict(row) for row in cursor.fetchall()]
# Get all products (or filtered by category if provided)
category = request.args.get('category', None)
if category:
cursor.execute("SELECT * FROM products WHERE category = ?", (category,))
else:
cursor.execute("SELECT * FROM products")
products = [dict(row) for row in cursor.fetchall()]
conn.close()
return render_template('index.html', products=products, categories=categories, selected_category=category)
@app.route('/product/<int:product_id>')
def product_detail(product_id):
conn = sqlite3.connect('fruitsveggies.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT * FROM products WHERE id = ?", (product_id,))
product = dict(cursor.fetchone())
conn.close()
return render_template('product_detail.html', product=product)
@app.route('/place_order', methods=['POST'])
def place_order():
if request.method == 'POST':
try:
name = request.form['name']
mobile = request.form['mobile']
address = request.form['address']
payment_method = request.form['payment_method']
product_id = request.form['product_id']
quantity = request.form['quantity']
conn = sqlite3.connect('fruitsveggies.db')
cursor = conn.cursor()
# Insert the order
cursor.execute(
"INSERT INTO orders (customer_name, mobile, address, payment_method, order_date, product_id, quantity) VALUES (?, ?, ?, ?, ?, ?, ?)",
(name, mobile, address, payment_method, datetime.now(), product_id, quantity)
)
conn.commit()
conn.close()
return redirect(url_for('order_success'))
except Exception as e:
flash(f"Error placing order: {str(e)}")
return redirect(url_for('product_detail', product_id=product_id))
# Admin routes
@app.route('/admin', methods=['GET', 'POST'])
def admin_login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
conn = sqlite3.connect('fruitsveggies.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT * FROM admin_users WHERE username = ?", (username,))
user = cursor.fetchone()
conn.close()
if user and check_password_hash(user['password'], password):
session['admin_logged_in'] = True
session['admin_username'] = username
return redirect(url_for('admin_dashboard'))
else:
flash('Invalid credentials')
return render_template('admin/login.html')
@app.route('/admin/logout')
def admin_logout():
session.pop('admin_logged_in', None)
session.pop('admin_username', None)
return redirect(url_for('admin_login'))
def admin_required(f):
def decorated_function(*args, **kwargs):
if not session.get('admin_logged_in'):
return redirect(url_for('admin_login'))
return f(*args, **kwargs)
decorated_function.__name__ = f.__name__
return decorated_function
@app.route('/admin/dashboard')
@admin_required
def admin_dashboard():
return render_template('admin/dashboard.html')
@app.route('/admin/products')
@admin_required
def admin_products():
conn = sqlite3.connect('fruitsveggies.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT * FROM products ORDER BY category, name")
products = [dict(row) for row in cursor.fetchall()]
conn.close()
return render_template('admin/products.html', products=products)
@app.route('/admin/add_product', methods=['GET', 'POST'])
@admin_required
def add_product():
if request.method == 'POST':
name = request.form['name']
description = request.form['description']
price = float(request.form['price'])
category = request.form['category']
# Handle image upload
image = request.files['image']
if image and image.filename:
filename = secure_filename(image.filename)
image.save(os.path.join('static/images', filename))
else:
filename = 'default.jpg' # Default image if none provided
conn = sqlite3.connect('fruitsveggies.db')
cursor = conn.cursor()
cursor.execute(
"INSERT INTO products (name, description, price, image, category) VALUES (?, ?, ?, ?, ?)",
(name, description, price, filename, category)
)
conn.commit()
conn.close()
flash('Product added successfully')
return redirect(url_for('admin_products'))
return render_template('admin/add_product.html')
@app.route('/admin/edit_product/<int:product_id>', methods=['GET', 'POST'])
@admin_required
def edit_product(product_id):
conn = sqlite3.connect('fruitsveggies.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
if request.method == 'POST':
name = request.form['name']
description = request.form['description']
price = float(request.form['price'])
category = request.form['category']
# Handle image upload
image = request.files['image']
if image and image.filename:
filename = secure_filename(image.filename)
image.save(os.path.join('static/images', filename))
# Update product with new image
cursor.execute(
"UPDATE products SET name = ?, description = ?, price = ?, image = ?, category = ? WHERE id = ?",
(name, description, price, filename, category, product_id)
)
else:
# Update product without changing image
cursor.execute(
"UPDATE products SET name = ?, description = ?, price = ?, category = ? WHERE id = ?",
(name, description, price, category, product_id)
)
conn.commit()
flash('Product updated successfully')
return redirect(url_for('admin_products'))
# Get product for editing
cursor.execute("SELECT * FROM products WHERE id = ?", (product_id,))
product = dict(cursor.fetchone())
conn.close()
return render_template('admin/edit_product.html', product=product)
@app.route('/admin/delete_product/<int:product_id>', methods=['POST'])
@admin_required
def delete_product(product_id):
conn = sqlite3.connect('fruitsveggies.db')
cursor = conn.cursor()
# First get the image filename to delete it from the filesystem
cursor.execute("SELECT image FROM products WHERE id = ?", (product_id,))
image = cursor.fetchone()[0]
# Delete the product
cursor.execute("DELETE FROM products WHERE id = ?", (product_id,))
conn.commit()
conn.close()
# Delete the image file if it exists and is not a default
if image != 'default.jpg':
image_path = os.path.join('static/images', image)
if os.path.exists(image_path):
os.remove(image_path)
flash('Product deleted successfully')
return redirect(url_for('admin_products'))
@app.route('/admin/orders')
@admin_required
def admin_orders():
conn = sqlite3.connect('fruitsveggies.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('''
SELECT
o.id,
o.customer_name,
o.mobile,
o.address,
o.payment_method,
o.order_date,
o.quantity,
p.name AS product_name,
p.category,
p.price
FROM orders o
JOIN products p ON o.product_id = p.id
ORDER BY o.order_date DESC
''')
orders = []
for row in cursor.fetchall():
order = dict(row)
# Parse the order_date string into a datetime object
order_date_str = order['order_date']
try:
# Attempt to parse with microseconds
order_date = datetime.strptime(order_date_str, '%Y-%m-%d %H:%M:%S.%f')
except ValueError:
# Fallback to parsing without microseconds
order_date = datetime.strptime(order_date_str, '%Y-%m-%d %H:%M:%S')
order['order_date'] = order_date
orders.append(order)
conn.close()
return render_template('admin/orders.html', orders=orders)
@app.route('/order_success')
def order_success():
return render_template('order_success.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
phone = request.form['phone']
password = request.form['password']
conn = sqlite3.connect('fruitsveggies.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE phone = ?", (phone,))
user = cursor.fetchone()
conn.close()
if user and check_password_hash(user['password'], password):
session['user_logged_in'] = True
session['user_id'] = user['id']
session['user_name'] = user['name']
flash('Login successful!')
return redirect(url_for('home'))
else:
flash('Invalid phone number or password')
return render_template('login.html')
@app.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
phone = request.form['phone']
password = request.form['password']
confirm_password = request.form['confirm_password']
# Validate passwords match
if password != confirm_password:
flash('Passwords do not match')
return render_template('signup.html')
# Hash the password
hashed_password = generate_password_hash(password)
conn = sqlite3.connect('fruitsveggies.db')
cursor = conn.cursor()
try:
cursor.execute(
"INSERT INTO users (name, email, phone, password) VALUES (?, ?, ?, ?)",
(name, email, phone, hashed_password)
)
conn.commit()
flash('Account created successfully! Please login.')
return redirect(url_for('login'))
except sqlite3.IntegrityError:
flash('Email or phone number already exists')
finally:
conn.close()
return render_template('signup.html')
@app.route('/logout')
def logout():
session.pop('user_logged_in', None)
session.pop('user_id', None)
session.pop('user_name', None)
flash('You have been logged out')
return redirect(url_for('home'))
@app.route('/profile')
def profile():
# Check if user is logged in
if not session.get('user_logged_in'):
flash('Please login to view your profile')
return redirect(url_for('login'))
user_id = session.get('user_id')
conn = sqlite3.connect('fruitsveggies.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# Get user info
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
user = dict(cursor.fetchone())
# Get user orders
cursor.execute('''
SELECT
o.id,
o.order_date,
o.quantity,
p.name AS product_name,
p.price
FROM orders o
JOIN products p ON o.product_id = p.id
WHERE o.customer_name = ?
ORDER BY o.order_date DESC
''', (user['name'],))
orders = []
for row in cursor.fetchall():
order = dict(row)
# Parse the order_date string into a datetime object
order_date_str = order['order_date']
try:
# Attempt to parse with microseconds
order_date = datetime.strptime(order_date_str, '%Y-%m-%d %H:%M:%S.%f')
except ValueError:
# Fallback to parsing without microseconds
order_date = datetime.strptime(order_date_str, '%Y-%m-%d %H:%M:%S')
order['order_date'] = order_date
orders.append(order)
conn.close()
return render_template('profile.html', user=user, orders=orders)
@app.route('/edit_profile', methods=['GET', 'POST'])
def edit_profile():
# Check if user is logged in
if not session.get('user_logged_in'):
flash('Please login to edit your profile')
return redirect(url_for('login'))
user_id = session.get('user_id')
conn = sqlite3.connect('fruitsveggies.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# Get user info
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
user = dict(cursor.fetchone())
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
phone = request.form['phone']
address = request.form['address']
current_password = request.form['current_password']
new_password = request.form['new_password']
confirm_password = request.form['confirm_password']
# Verify current password
if not check_password_hash(user['password'], current_password):
flash('Current password is incorrect')
return render_template('edit_profile.html', user=user)
try:
# If new password is provided, update it
if new_password:
if new_password != confirm_password:
flash('New passwords do not match')
return render_template('edit_profile.html', user=user)
hashed_password = generate_password_hash(new_password)
cursor.execute(
"UPDATE users SET name = ?, email = ?, phone = ?, address = ?, password = ? WHERE id = ?",
(name, email, phone, address, hashed_password, user_id)
)
else:
# Otherwise just update other fields
cursor.execute(
"UPDATE users SET name = ?, email = ?, phone = ?, address = ? WHERE id = ?",
(name, email, phone, address, user_id)
)
conn.commit()
session['user_name'] = name # Update session user name
flash('Profile updated successfully')
return redirect(url_for('profile'))
except sqlite3.IntegrityError:
flash('Email or phone number already in use')
finally:
conn.close()
conn.close()
return render_template('edit_profile.html', user=user)
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/contact')
def contact():
return render_template('contact.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860) |