Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
from flask import Flask, render_template, redirect, url_for, session, flash
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, TextAreaField, HiddenField, SelectField, IntegerRangeField, DateField, \
PasswordField, BooleanField, SubmitField
from flask_wtf.file import FileField, FileAllowed, DataRequired
import random
from flask_sqlalchemy import SQLAlchemy
from flask_uploads import UploadSet, configure_uploads, IMAGES
from wtforms.validators import DataRequired, Length, Email, EqualTo, NumberRange
app = Flask(__name__)
photos = UploadSet('photos', IMAGES) #setting photos as uploadset
app.config['UPLOADED_PHOTOS_DEST'] = 'images' # setting imgae destination as images
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///books.db' #setting database as file books.db
app.config['DEBUG'] = True #enabling debug mode for better coding environments
app.config['SECRET_KEY'] = 'bgggkfuukfgskrferbkjbjjjjsbdev' # setting the secrect key
configure_uploads(app, photos) #configring upload set for app
db = SQLAlchemy(app) #creating database for app
class Book(db.Model): #creating class for table book
id = db.Column(db.Integer, unique=True) #creating coloumn unique id for the book
name = db.Column(db.String(100), unique=True) #creating coloumn name for the book
author = db.Column(db.String(70)) #creating coloumn author name for the book
pubdate = db.Column(db.String(100)) #creating coloumn publishing date for the book
isb13 = db.Column(db.Integer, primary_key=True) #creating coloumn fori Isb13 number primary key
price = db.Column(db.Integer) # creating coloumn for retai price
tprice = db.Column(db.Integer) # creating coloumn for tarde price
stock = db.Column(db.Integer) # creating coloumn for stock
des = db.Column(db.String(500)) #creating coloumn description for the book
image = db.Column(db.String(100)) #creting coloumn for the image
orders = db.relationship('Order_Item', backref='book', lazy=True) #creating coloumn order of books which is sared with classOder item
class Cart(db.Model):
id = db.Column(db.Integer, primary_key=True) #creating coloumn for id which is primsry key
first_name = db.Column(db.String(20),nullable=False) #creating coloumn for first name
last_name = db.Column(db.String(20),nullable=False) #creating coloumn for last name
p_no= db.Column(db.Integer) # creating coloumn for phone number
address = db.Column(db.String(100), nullable=False) #creating coloumn for address
city = db.Column(db.String(100), nullable=False) #creating coloumn address
state = db.Column(db.String(20), nullable=False) #creating coloumn for state
payment_type = db.Column(db.String(10)) #creating coloumn for payment
items = db.relationship('Order_Item', backref='cart', lazy=True) #creating coloumn for items in cart which is shared between class order item
def order_total(self):
return db.session.query(db.func.sum(Order_Item.quantity * Book.price)).join(Book).filter(
Order_Item.order_id == self.id).scalar() + 10
def quantity_total(self):
return db.session.query(db.func.sum(Order_Item.quantity)).filter(Order_Item.order_id == self.id).scalar()
class User(db.Model):
username = db.Column(db.String(20), unique=True, nullable=False, primary_key=True) #creating user name
email = db.Column(db.String(120), unique=True, nullable=False)#creating email
password = db.Column(db.String(60), nullable=False)#creating password
class Order_Item(db.Model):
id = db.Column(db.Integer, primary_key=True)
order_id = db.Column(db.Integer, db.ForeignKey('cart.id'))
product_id = db.Column(db.Integer, db.ForeignKey('book.id'))
quantity = db.Column(db.Integer)
class AddBook(FlaskForm):
name = StringField('Name',validators=[DataRequired()]) #creating Form feild for book name
author = StringField('author Name',validators=[DataRequired()]) #creating Form feild for author
pubdate = DateField('Publish Date',validators=[DataRequired()]) #creating Form feild for pubdate
isb13 = IntegerField('ISB13 Number',validators=[DataRequired()]) #creating Form feild isb13
price = IntegerRangeField('Price',validators=[NumberRange(min=1, max=100)]) #creating Form feild for price
tprice = IntegerRangeField('Price',validators=[NumberRange(min=1, max=100)]) #creating Form feild for trade
stock = IntegerRangeField('Stock',validators=[NumberRange(min=1, max=20)]) #creating Form feild for stock
des = TextAreaField('Description') #creating Form feild for descrption
image = FileField('Image', validators=[FileAllowed(IMAGES, 'Only images are accepted.')]) #creating Form feild for
submit = SubmitField('Add Books') #creating Form feild for storing value of submit button
class CartAdd(FlaskForm):
quantity = IntegerField('Quantity') #creating Form feild for quantity
id = HiddenField('ID') #creating Form feild for id which is an hidden feild
class Checkout(FlaskForm): #creating Form for checkout class of the app
f_name= StringField('First Name',validators=[DataRequired()]) #creating Form feild for first_name of the customer
last_name = StringField('Last Name',validators=[DataRequired()]) #creating Form feild for last_name of the customer
p_no= StringField('Number',validators=[DataRequired()]) #creating Form feild for for the Phone number
address = StringField('Address',validators=[DataRequired()]) #creating Form feild for address of the cutomer
city = StringField('City',validators=[DataRequired()]) #creating Form feild for city of the cutomer
state = StringField('State',validators=[DataRequired()]) #creating Form feild for state of the cutomer
payment_type = SelectField('Payment Type', choices=[('CK', 'Check'), ('WT', 'Wire Transfer')]) #creating Form feild for payment type with choices
class SignUpForm(FlaskForm): #creating Form for sign in page of the web application
username = StringField('Username',
validators=[DataRequired(), Length(min=2, max=20)]) #creating Form feild for username where string must betwwen 2 and 20
email = StringField('Email',
validators=[DataRequired(), Email()]) #creating Form feild for email where email validatotrs are used
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password', #creating from feild for password
validators=[DataRequired(), EqualTo('password')]) #creating Form feild for confirm password
submit = SubmitField('Sign Up') #creating Form feild for submit button
class SignInForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)]) #creating Form feild for username where string must betwwen 2 and 20
password = PasswordField('Password', validators=[DataRequired()]) #creating from feild for password
remember = BooleanField('Remember Me') #creating from feild for Remeber me
submit = SubmitField('Login') #creating from feild for submit button
@app.route('/') #homepage of the flaskapp
def main(): #name of of the home unction
books = Book.query.all() #returning list of books in the Book table
return render_template('main.html', books=books) #rendering the home index template
@app.route('/book/<id>') #approute for diplaying the book
def book(id): #using id varible to identify the book to dipay
book = Book.query.filter_by(id=id).first() #book is assigend the book where id equal sreach id
form = CartAdd() # Flask form cartAdd is assigned as the form
return render_template('book_display.html', book=book, form=form) #template for displaying book is rendered
@app.route('/addnow/<id>')
def add_now(id):
if 'cart' not in session:
session['cart'] = []
session['cart'].append({'id': id, 'quantity': 1})
session.modified = True
return redirect(url_for('main'))
@app.route('/add-to-cart', methods=['POST'])
def cartadd():
if 'cart' not in session:
session['cart'] = []
form = CartAdd()
if form.validate_on_submit():
session['cart'].append({'id': form.id.data, 'quantity': form.quantity.data})
session.modified = True
return redirect(url_for('main'))
def cart_manager():
books = []
grand_sum = 0
main = 0
quantity_tot = 0
for item in session['cart']:
book = Book.query.filter_by(id=item['id']).first()
quantity = int(item['quantity'])
sum = quantity * book.price
grand_sum += sum
quantity_tot += quantity
books.append({'id': book.id, 'name': book.name, 'price': book.price, 'image': book.image, 'quantity': quantity,
'sun': sum, 'main': main})
main += 1
grand_sum_shipping = 3
return books, grand_sum, grand_sum_shipping, quantity_tot
@app.route('/cart')
def cart():
books, grand_sum, grand_sum_shipping, quantity_tot = cart_manager()
return render_template('cart.html', books=books, grand_sum=grand_sum, grand_sum_shipping=grand_sum_shipping,
quantity_tot=quantity_tot)
@app.route('/delete/<main>')
def delete_from_cart(main):
del session['cart'][int(main)]
session.modified = True
return redirect(url_for('cart'))
@app.route('/checkout', methods=['GET', 'POST'])
def check_out():
form = Checkout()
books, grand_sum, grand_sum_shipping, quantity_tot = cart_manager()
if form.validate_on_submit():
for book in books:
order_item = Order_Item(quantity=book['quantity'], product_id=book['id'])
cart.items.append(order_item)
book = Book.query.filter_by(id=book['id']).update({'stock': Book.stock - book['quantity']})
db.session.add(cart)
db.session.commit()
session['cart'] = []
session.modified = True
return redirect(url_for('main'))
return render_template('checkout.html', form=form, grand_sum=grand_sum, grand_sum_shipping=grand_sum_shipping,
quantity_tot=quantity_tot)
@app.route('/admin')
def admin():
book = Book.query.all()
books_in_stock = Book.query.filter(Book.stock > 0).count()
orders = Cart.query.all()
return render_template('admin/index.html', admin=True, books=book, books_in_stock=books_in_stock, orders=orders)
@app.route('/admin/add', methods=['GET', 'POST'])
def addBooks():
form = AddBook()
if form.validate_on_submit():
id = random.randint(10000, 100000)
image_url = photos.url(photos.save(form.image.data))
new_book = Book(id=id, name=form.name.data, price=form.price.data, stock=form.stock.data, des=form.des.data,
image=image_url)
db.session.add(new_book)
db.session.commit()
return redirect(url_for('admin'))
return render_template('admin/add-product.html', admin=True, form=form)
@app.route("/register", methods=['GET', 'POST'])
def SignUp():
form = SignUpForm()
if form.validate_on_submit():
flash(f'Account created for {form.username.data}!', 'success')
return redirect(url_for('main'))
return render_template('signup.html', title='Register', form=form)
@app.route("/login", methods=['GET', 'POST'])
def SignIn():
form = SignInForm()
if form.validate_on_submit():
if form.username.data == 'admin' and form.password.data == 'p455w0rd':
flash('You have been logged as admin in!', 'success')
return redirect(url_for('admin'))
return render_template('signin.html', title='Login', form=form)
if __name__ == '__main__':
app.run()