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 #creating a instnace of the Flask framework
from flask import redirect #utility for redirecting to specific URLs
from flask import url_for #utility for extracting the url for given html file name
from flask import render_template #utility for displaying html templates
from flask_sqlalchemy import SQLAlchemy #utility for SQL/Database functions in flask
from flask_login import UserMixin #utility for authentication of the login details
from flask import session #utility for storing temporary data across the site
from flask import request #utility to accesss methods
from flask import flash #for displaying messages on the next page
from werkzeug.utils import secure_filename
import os
import datetime
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
#UPLOAD_FOLDER = "static"
app.secret_key = "halamathihabibo" #Secret key to encrypt each sessions
#app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = set(["png","jpg", "jpeg"])
def allowed_file(filename):
return "." in filename and filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///User.db' #Connecting the app file to the database
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False #Turning of tracking database activities to avoid warning messages
db = SQLAlchemy(app) #Database instance
#The database table with user details
class User(db.Model):
username = db.Column(db.String(20), primary_key = True)
email = db.Column(db.String(50))
phonenum = db.Column(db.Integer)
password = db.Column(db.String(100))
sale_item = db.relationship('Item')
def __init__(self,username,email,phonenum,password):
self.username = username
self.email = email
self.phonenum = phonenum
self.password = password
#Database table with item(sale items) details
class Item(db.Model):
id = db.Column(db.Integer, primary_key=True)
itemName = db.Column(db.String(30))
itemDescrip = db.Column(db.String(1000))
item_sold = db.Column(db.Boolean)
item_date = db.Column(db.Date)
item_time = db.Column(db.DateTime)
item_username = db.Column(db.String(20), db.ForeignKey('user.username'))
def __init__(self,itemName,itemDescrip,item_sold,item_date,item_time,item_username):
self.itemName = itemName
self.itemDescrip = itemDescrip
self.item_sold = item_sold
self.item_date = item_date
self.item_time = item_time
self.item_username = item_username
#Default home page functions and features
@app.route("/")
@app.route("/home")
def home():
#[1] if an error is caused due to zero sales in database, then just render a empty home page
try:
sales = Item.query.all()
return render_template("home.html", sales=sales)
except:
return render_template("home.html")
#Registration functions and features
@app.route("/register", methods=["POST","GET"]) #Using methods to send and receive info from user
def register():
if request.method == "POST":
usernameReg= request.form["usernameIn"]
emailReg= request.form["emailIn"]
phonenumReg= request.form["phonenumIn"]
passwordReg= request.form["passwordIn"]
user_exist = User.query.filter_by(username=usernameReg).first()
if user_exist:
flash("Username already exists!")
return redirect(url_for("register"))
else:
user_info = User(usernameReg,emailReg,phonenumReg,passwordReg)
db.session.add(user_info)
db.session.commit()
flash("You have successfully registered! You can login now")
return redirect(url_for("login"))
else:
return render_template("register.html")
#Login functions and features
@app.route("/login", methods=["POST","GET"]) #Using methods to send and receive info from user
def login():
if request.method == "POST":
usernameLog = request.form["usernameLIn"]
passwordLog = request.form["passwordLIn"]
user_check = User.query.filter_by(username=usernameLog).first() #Select the first row matching the username input
if user_check:
if user_check.password == passwordLog:
session["current_user"] = usernameLog #if login successful then store the current username using session
flash("You have logged in!")
return redirect(url_for("home"))
else:
flash("Incorrect Password")
return render_template("login.html")
else:
flash("Username not recognised! Please register.")
return render_template("login.html")
else:
return render_template("login.html")
@app.route("/log_out")
def log_out():
session.pop("current_user", None)
flash("You have successfully logged out")
return redirect(url_for("home"))
@app.route("/sell_item", methods=["POST","GET"])
def sell_item():
if request.method == "POST":
itemName = request.form.get("nameItem")
itemDescription = request.form.get("description")
today_date = datetime.date.today()
#get date and time and convert to time
time_now = datetime.datetime.today()
item_added = Item(itemName,itemDescription,False,today_date,time_now,session["current_user"])
db.session.add(item_added)
db.session.commit()
session["upload"] = item_added.id
return render_template("upload.html")
else:
return render_template("sell_item.html")
@app.route("/product_page/<int:product>", methods=["GET", "POST"])
def product_page(product):
selected_product= Item.query.filter_by(id=product)
return render_template("product_page.html", selected_product = selected_product)
@app.route("/my_items")
def my_items():
user_items = Item.query.all()
return render_template("my_items.html", user_items=user_items)
@app.route("/sold_item/<int:item>", methods=["GET", "POST"])
def sold_item(item):
selected_item = Item.query.filter_by(id=item).first()
selected_item.item_sold = True
db.session.commit()
return redirect(url_for("my_items"))
@app.route("/upload", methods=['GET','POST'])
def upload():
target = os.path.join(APP_ROOT, 'static/')
if not os.path.isdir(target):
os.mkdir(target)
upload = request.files.get("file")
filename = str(session["upload"])
destination = "/".join([target,filename])
upload.save(destination)
flash("Item Added!")
return redirect(url_for("home"))
if __name__ == "__main__":
with app.app_context():
db.create_all() #create the database everytime the website is run
app.run(debug=True)