Skip to content
Snippets Groups Projects
Commit b73f2f03 authored by Tayeeb Islam's avatar Tayeeb Islam
Browse files

Commit 2

parent ebe80d23
No related branches found
No related tags found
No related merge requests found
Showing
with 371 additions and 0 deletions
CM1102 - Online Shop Coursework.
This is submission of student c2003538
1. URL of my website:
2. Admin login details:
- Admin username:
- Admin password:
3. Individual Responsibilities:
1. Student number: c2003538
2. Email address: islamt4@cardiff.ac.uk
4. Full (40 characters) CHECKSUM of my last commit on GitLab :
\ No newline at end of file
alembic==1.0.7
Click==7.0
Flask==1.0.2
Flask-Migrate==2.3.1
Flask-MySQL==1.4.0
Flask-SQLAlchemy==2.3.2
Flask-WTF==0.14.2
itsdangerous==1.1.0
Jinja2==2.10
Mako==1.0.7
MarkupSafe==1.1.0
PyMySQL==0.9.3
python-dateutil==2.8.0
python-editor==1.0.4
six==1.12.0
SQLAlchemy==1.2.17
Werkzeug==0.14.1
WTForms==2.2.1
gunicorn==20.0.4
Flask-Login==0.4.1
Flask-Admin==1.5.4
run.py 0 → 100644
from shop import app
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = 'edd9229339e5754427a7792fc79b51318395e93569165fa4'
# Note: type 'app.config[..]' as one line, it is split into
# multiple lines in this document to fit on the page
# {USERNAME} and {YOUR_DATABASE} are your Cardiff username
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://c2003538:Newport123@csmysql.cs.cf.ac.uk:3306/c2003538_Online_Shop'
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
from shop import routes
from flask_admin import Admin
from shop.views import AdminView
from shop.models import User, Item
admin = Admin(app,name='Admin panel',template_mode='bootstrap3')
admin.add_view(AdminView(User, db.session))
admin.add_view(AdminView(Item, db.session))
File added
File added
File added
File added
File added
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, SelectField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError, Regexp
from shop.models import User
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired('Please enter your username'), Length(min=3, max=15)])
email = StringField('Email',
validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired(),Regexp('^.{6,8}$',
message='Your password should be between 6 and 8 characters long.')])
confirm_password = PasswordField('Confirm Password',
validators=[DataRequired(), EqualTo('password', message='Passwords must match')])
submit = SubmitField('Register')
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError('Oh no! This username has already been taken. Please choose a different one.')
def validate_email(self, email):
user = User.query.filter_by(email=email.data).first()
if user:
raise ValidationError('Oh no! This email is already registered. Please choose a different one.')
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Login')
class SearchForm(FlaskForm):
choices = [('Rose', 'Rose'), ('Lily', 'Lily'), ('Daisy', 'Daisy'), ('Sunflower', 'Sunflower'), ('Carnation', 'Carnation'), ('Freesia', 'Freesia'), ('Jasmine', 'Jasmine'), ('Peony', 'Peony'), ('Amaryllis', 'Amaryllis')]
select = SelectField('Search flower:', choices=choices)
search = StringField('')
class CheckoutForm(FlaskForm):
forename = StringField('Forename', validators=[DataRequired('Please enter your forename'), Length(min=3, max=15)])
surname = StringField('Surname', validators=[DataRequired('Please enter your surname'), Length(min=3, max=15)])
address = StringField('Address',
validators=[DataRequired('Please enter your billing address')])
card_no = PasswordField('card_no', validators=[DataRequired('Please enter your 16-digit card number'), Length(min=16, max=16)])
cvc = PasswordField('cvc', validators=[DataRequired('Please enter your 3-digit CVC'), Length(min=3, max=3)])
submit = SubmitField('Checkout')
from datetime import datetime
from shop import db, login_manager
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
class Item(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50),nullable=False)
description = db.Column(db.String(300), nullable=False)
#publication_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
price = db.Column(db.Numeric(10,2), nullable=False)
image_file = db.Column(db.String(50), nullable=False, default='default.jpg')
def __repr__(self):
return f"Item('{self.title}', '{self.description}', '{self.price}')"
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(15), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(128))
password = db.Column(db.String(60), nullable=False)
is_admin=db.Column(db.Boolean,nullable=False,default=False)
def __repr__(self):
return f"User('{self.username}', '{self.email}')"
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class Cart(db.Model):
id = db.Column(db.Integer, primary_key=True)
quantity = db.Column(db.Integer)
item_id = db.Column(db.Integer, db.ForeignKey('item.id'), nullable=False)
import os
from flask import render_template, url_for, request, redirect, flash, session
from shop import app, db
from shop.models import Item, User
from shop.forms import RegistrationForm, LoginForm, SearchForm, CheckoutForm
from flask_login import login_user, current_user, logout_user, login_required
@app.route("/", methods= ['GET', 'POST'])
@app.route("/home", methods= ['GET', 'POST'])
def home():
form = SearchForm()
search = SearchForm(request.form)
search_string = ""
if request.method == 'POST':
search_string = search.items['search']
items = Item.query.filter_by(Item.title == search_string).first()
return render_template('home.html', items=item, form=form)
return render_template('home.html', items = Item.query.all(), title='Home')
@app.route("/about")
def about():
return render_template('about.html', title='About')
@app.route("/orderasc")
def orderasc():
return render_template('home.html', items = Item.query.order_by("price"), title='Home')
@app.route("/orderdesc")
def orderdesc():
return render_template('home.html', items = Item.query.order_by("price")[::-1], title='Home')
@app.route("/item/<int:item_id>")
def item(item_id):
item = Item.query.get_or_404(item_id)
return render_template('item.html', item=item) #title=book.title
@app.route("/register", methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
user = User(username=form.username.data, email=form.email.data, password=form.password.data)
db.session.add(user)
db.session.commit()
flash('Your account has been created. You can now log in.')
return redirect(url_for('home'))
return render_template('register.html', title='Register', form=form)
@app.route("/checkout", methods=['GET', 'POST'])
def checkout():
form = CheckoutForm()
if form.validate_on_submit():
#user = User(forename=form.forename.data,surname=form.surname.data)
session["cart"] = []
return redirect(url_for('thankyou'))
return render_template('checkout.html', title='Checkout', form=form)
@app.route("/login", methods=['GET','POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is not None and user.verify_password(form.password.data):
login_user(user)
flash('You are now logged in.')
return redirect(url_for('home'))
flash('Invalid username or password.')
return render_template('login.html', form=form)
return render_template('login.html', title='Login', form=form)
@app.route("/logout")
def logout():
db.session.commit()
session.clear()
logout_user()
return redirect(url_for('home'))
@app.route("/add_to_cart/<int:item_id>")
def add_to_cart(item_id):
if "cart" not in session:
session["cart"] = []
session["cart"].append(item_id)
flash("The item is added to your shopping cart!")
return redirect("/cart")
@app.route("/cart", methods=['GET', 'POST'])
def cart_display():
if "cart" not in session:
flash('There is nothing in your cart.')
return render_template("cart.html", display_cart = {}, total = 0)
else:
items = session["cart"]
cart = {}
total_price = 0
total_quantity = 0
for item in items:
item = Item.query.get_or_404(item)
total_price += item.price
if item.id in cart:
cart[item.id]["quantity"] += 1
else:
cart[item.id] = {"quantity":1, "title": item.title, "price":item.price}
total_quantity = sum(item['quantity'] for item in cart.values())
return render_template("cart.html", title='Your Shopping Cart', display_cart = cart, total = total_price, total_quantity = total_quantity)
return render_template('cart.html')
@app.route("/delete_item/<int:item_id>", methods=['GET', 'POST'])
def delete_item(item_id):
if "cart" not in session:
session["cart"] = []
session["cart"].remove(item_id)
flash("The item has been removed from your shopping cart!")
session.modified = True
return redirect("/cart")
@app.route("/add_to_wishlist/<int:item_id>")
def add_to_wishlist(item_id):
if "wishlist" not in session:
session["wishlist"] = []
session["wishlist"].append(item_id)
flash("The item has been added to your wishlist")
return redirect("/wishlist")
@app.route("/wishlist", methods=['GET', 'POST'])
def wishlist_display():
if "wishlist" not in session:
flash('Your wishlist is empty.')
return render_template("wishlist.html", display_wishlist = {}, total = 0)
else:
items = session["wishlist"]
wishlist = {}
total_price = 0
total_quantity = 0
for item in items:
item = Item.query.get_or_404(item)
total_price += item.price
if item.id in wishlist:
wishlist[item.id]["quantity"] += 1
else:
wishlist[item.id] = {"quantity":1, "title": item.title, "price":item.price}
total_quantity_wishlist = sum(item_id['quantity'] for item_id in wishlist.values())
return render_template("wishlist.html", title= "Your Shopping Cart", display_wishlist = wishlist, total = total_price, total_quantity_wishlist = total_quantity_wishlist)
@app.route("/delete_item_wishlist/<int:item_id>", methods=['GET', 'POST'])
def delete_item_wishlist(item_id):
if "wishlist" not in session:
session["wishlist"] = []
session["wishlist"].remove(item_id)
flash("The item has been removed from your wishlist")
session.modified = True
return redirect("/wishlist")
@app.route("/thankyou")
def thankyou():
return render_template("thankyou.html", title='Thank You')
shop/static/img/calculator.jpg

165 KiB

shop/static/img/pen.jpg

51.3 KiB

shop/static/img/pencil.jpg

76.1 KiB

shop/static/img/rubber.jpg

47.4 KiB

shop/static/img/ruler.jpg

18 KiB

shop/static/img/usb.jpg

332 KiB

body {
font-family:helvetica, sans-serif;
background-color: white;
}
h1 {
padding-left: 20px;
font-family:sans-serif;
color:black;
}
a {
text-decoration:none;
color:#000099;
/*color:#104e77;*/
}
a:hover {
/*color:#77b6e2;*/
color:red;
}
#header {
padding:10px 100px;
font-size:18px;
overflow:auto;
background-color: #ffffe6;
}
{% extends "layout.html" %}
{% block content %}
<h1>This is the About Us Page</h1>
<p>Needs some new staionary? this place sells all of it </p>
{% endblock content %}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment