-
Notifications
You must be signed in to change notification settings - Fork 0
/
E-commerce.py
79 lines (67 loc) · 2.73 KB
/
E-commerce.py
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
# e-commerce.py
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, logout_user, current_user, login_required
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SECRET_KEY'] = 'your_secret_key'
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
description = db.Column(db.Text, nullable=False)
price = db.Column(db.Float, nullable=False)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route('/')
def home():
products = Product.query.all()
return render_template('home.html', products=products)
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('home'))
if request.method == 'POST':
user = User.query.filter_by(email=request.form['email']).first()
if user and user.password == request.form['password']:
login_user(user)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('home'))
else:
flash('Login unsuccessful. Please check email and password.', 'danger')
return render_template('login.html')
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('home'))
@app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('home'))
if request.method == 'POST':
user = User(username=request.form['username'], email=request.form['email'], password=request.form['password'])
db.session.add(user)
db.session.commit()
flash('Your account has been created! You are now able to log in.', 'success')
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/product/<int:product_id>')
@login_required
def product(product_id):
product = Product.query.get_or_404(product_id)
return render_template('product.html', product=product)
@app.route('/order', methods=['POST'])
@login_required
def order():
# Handle order processing logic here
return redirect(url_for('home'))
if __name__ == '__main__':
app.run(debug=True)