Fixed all pep8 warnings

This commit is contained in:
Luke Else 2024-01-21 22:22:29 +00:00
parent 44c1ee03ba
commit bca3b0a663
14 changed files with 64 additions and 43 deletions

2
app.py
View File

@ -14,7 +14,7 @@ def main():
# Set app secret key to sign session cookies # Set app secret key to sign session cookies
secret_key = environ.get("APPSECRET") secret_key = environ.get("APPSECRET")
if secret_key == None: if secret_key is None:
# NO Secret Key set! # NO Secret Key set!
print("No app secret set, please set one before deploying in production") print("No app secret set, please set one before deploying in production")
app.secret_key = "DEFAULTKEY" app.secret_key = "DEFAULTKEY"

View File

@ -30,7 +30,7 @@ class CategoryController(DatabaseController):
) )
row = cursor.fetchone() row = cursor.fetchone()
if row == None: if row is None:
return None return None
params = dict(zip(self.FIELDS, row)) params = dict(zip(self.FIELDS, row))
@ -44,7 +44,7 @@ class CategoryController(DatabaseController):
) )
rows = cursor.fetchall() rows = cursor.fetchall()
if rows == None: if rows is None:
return None return None
categories = list() categories = list()

View File

@ -17,8 +17,8 @@ class DatabaseController(ABC):
def __init__(self): def __init__(self):
self._conn = None self._conn = None
try: try:
# Creates a connection and specifies a flag to parse all types back down into # Creates a connection and specifies a flag to parse all types
# Python declared types e.g. date & time # back down into Python declared types e.g. date & time
self._conn = sqlite3.connect( self._conn = sqlite3.connect(
self.__sqlitefile, detect_types=sqlite3.PARSE_DECLTYPES) self.__sqlitefile, detect_types=sqlite3.PARSE_DECLTYPES)
except sqlite3.Error as e: except sqlite3.Error as e:
@ -28,10 +28,10 @@ class DatabaseController(ABC):
print(e) print(e)
def __del__(self): def __del__(self):
if self._conn != None: if self._conn is not None:
self._conn.close() self._conn.close()
""" Takes a dictionary of fields and returns the object """ Takes a dictionary of fields and returns the object
with those fields populated """ with those fields populated """
def new_instance(self, of: type, with_fields: Mapping[str, Any]): def new_instance(self, of: type, with_fields: Mapping[str, Any]):

View File

@ -22,7 +22,11 @@ class ProductController(DatabaseController):
] ]
self._conn.execute( self._conn.execute(
"INSERT INTO Products (name, image, description, cost, categoryID, sellerID, postedDate, quantityAvailable) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", """
INSERT INTO Products
(name, image, description, cost, categoryID,
sellerID, postedDate, quantityAvailable)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
params params
) )
self._conn.commit() self._conn.commit()
@ -38,7 +42,7 @@ class ProductController(DatabaseController):
) )
rows = cursor.fetchmany() rows = cursor.fetchmany()
if rows == None: if rows is None:
return None return None
products = list() products = list()
@ -51,16 +55,17 @@ class ProductController(DatabaseController):
return products return products
def read_all(self, category: str = "", search_term: str = "") -> list[Product] | None: def read_all(self, category: str = "",
search_term: str = "") -> list[Product] | None:
params = [ params = [
"%" + category + "%", "%" + category + "%",
"%" + search_term + "%" "%" + search_term + "%"
] ]
cursor = self._conn.execute( cursor = self._conn.execute(
"""SELECT * FROM Products """SELECT * FROM Products
INNER JOIN Categories ON Products.categoryID = Categories.id INNER JOIN Categories ON Products.categoryID = Categories.id
WHERE Categories.name LIKE ? WHERE Categories.name LIKE ?
AND Products.name LIKE ? AND Products.name LIKE ?
""", """,
params params

View File

@ -23,7 +23,9 @@ class UserController(DatabaseController):
] ]
self._conn.execute( self._conn.execute(
"INSERT INTO Users (username, password, first_name, last_name, email, phone, role) VALUES (?, ?, ?, ?, ?, ?, ?)", """INSERT INTO Users
(username, password, first_name, last_name, email, phone, role)
VALUES (?, ?, ?, ?, ?, ?, ?)""",
params params
) )
self._conn.commit() self._conn.commit()
@ -39,7 +41,7 @@ class UserController(DatabaseController):
) )
row = cursor.fetchone() row = cursor.fetchone()
if row != None: if row is not None:
params = dict(zip(self.FIELDS, row)) params = dict(zip(self.FIELDS, row))
# Is user a seller # Is user a seller
@ -63,7 +65,7 @@ class UserController(DatabaseController):
) )
row = cursor.fetchone() row = cursor.fetchone()
if row != None: if row is not None:
params = dict(zip(self.FIELDS, row)) params = dict(zip(self.FIELDS, row))
# Is user a seller # Is user a seller

View File

@ -12,7 +12,7 @@ blueprint.register_blueprint(user.blueprint)
blueprint.register_blueprint(product.blueprint) blueprint.register_blueprint(product.blueprint)
### CONTEXTS ### # CONTEXTS #
# Function that returns a given user class based on the ID in the session # Function that returns a given user class based on the ID in the session
@blueprint.context_processor @blueprint.context_processor
@ -21,7 +21,7 @@ def get_user() -> dict[User | None]:
user_id = session.get('user_id') user_id = session.get('user_id')
user = None user = None
if user_id != None: if user_id is not None:
db = UserController() db = UserController()
user = db.read_id(user_id) user = db.read_id(user_id)

View File

@ -42,10 +42,13 @@ def index():
products = database.read_all() products = database.read_all()
# No Products visible # No Products visible
if products == None: if products is None:
flash("No Products available") flash("No Products available")
return render_template('index.html', content="content.html", products=products) return render_template('index.html',
content="content.html",
products=products
)
# Loads a given product category page # Loads a given product category page
@ -56,17 +59,21 @@ def category(category: str):
# Check to see if there is a custome search term # Check to see if there is a custome search term
search_term = request.args.get("search", type=str) search_term = request.args.get("search", type=str)
if search_term != None: if search_term is not None:
print(f"Search Term {search_term}") print(f"Search Term {search_term}")
products = database.read_all(category, search_term) products = database.read_all(category, search_term)
else: else:
products = database.read_all(category) products = database.read_all(category)
# No Products visible # No Products visible
if products == None: if products is None:
flash(f"No Products available in {category}") flash(f"No Products available in {category}")
return render_template('index.html', content="content.html", products=products, category=category) return render_template('index.html',
content="content.html",
products=products,
category=category
)
# Loads a given product based on ID # Loads a given product based on ID
@ -82,13 +89,13 @@ def display_add_product():
user_id = session.get('user_id') user_id = session.get('user_id')
# User must be logged in to view this page # User must be logged in to view this page
if user_id == None: if user_id is None:
flash("Please Login to view this page") flash("Please Login to view this page")
return redirect('/login') return redirect('/login')
db = UserController() db = UserController()
user = db.read_id(user_id) user = db.read_id(user_id)
if user == None or user.role != "Seller": if user is None or user.role != "Seller":
flash("You must be logged in as a Seller to view this page") flash("You must be logged in as a Seller to view this page")
return redirect('/') return redirect('/')
@ -101,20 +108,20 @@ def add_product():
user_id = session.get('user_id') user_id = session.get('user_id')
# User must be logged in to view this page # User must be logged in to view this page
if user_id == None: if user_id is None:
flash("Please Login to view this page") flash("Please Login to view this page")
return redirect('/login', code=302) return redirect('/login', code=302)
db = UserController() db = UserController()
user = db.read_id(user_id) user = db.read_id(user_id)
if user == None or user.role != "Seller": if user is None or user.role != "Seller":
flash("You must be logged in as a Seller to perform this action") flash("You must be logged in as a Seller to perform this action")
return redirect('/', code=302) return redirect('/', code=302)
file = request.files.get('image') file = request.files.get('image')
# Ensure that the correct file type is uploaded # Ensure that the correct file type is uploaded
if file == None or not allowed_file(file.filename): if file is None or not allowed_file(file.filename):
flash("Invalid File Uploaded") flash("Invalid File Uploaded")
return redirect("/add") return redirect("/add")

View File

@ -28,7 +28,7 @@ def login():
error = None error = None
# No user found # No user found
if user == None: if user is None:
error = "No user found with the username " + request.form['username'] error = "No user found with the username " + request.form['username']
flash(error) flash(error)
return redirect("/login") return redirect("/login")
@ -57,7 +57,7 @@ def signup():
database = UserController() database = UserController()
# User already exists # User already exists
if database.read(request.form['username']) != None: if database.read(request.form['username']) is not None:
error = "User, " + request.form['username'] + " already exists" error = "User, " + request.form['username'] + " already exists"
flash(error) flash(error)
return redirect("/signup") return redirect("/signup")

View File

@ -23,8 +23,10 @@ class Product:
No additional properties are assigned to the customer No additional properties are assigned to the customer
''' '''
def __init__(self, name: str, image: str, description: str, cost: float, category: int, def __init__(self, name: str, image: str, description: str,
seller_id: int, posted_date: datetime, quantity_available: int): cost: float, category: int, seller_id: int,
posted_date: datetime, quantity_available: int
):
self.id = 0 self.id = 0
self.name = name self.name = name
self.image = image self.image = image

View File

@ -2,11 +2,14 @@ from abc import ABC
class User(ABC): class User(ABC):
""" Functional Class constructor to initialise all properties in the base object """ Functional Class constructor to initialise all properties in
with a value """ the base object with a value
"""
def __init__(self, username: str, password: str, firstname: str, def __init__(self, username: str, password: str,
lastname: str, email: str, phone: str, role: str): firstname: str, lastname: str,
email: str, phone: str, role: str
):
self.id = 0 self.id = 0
self.username = username self.username = username
self.password = password self.password = password

View File

@ -1,7 +1,7 @@
<link rel="stylesheet" href="{{ url_for('static', filename='css/products.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='css/products.css') }}">
<div class="product-container"> <div class="product-container">
{% if products != None %} {% if products is not None %}
{% for product in products %} {% for product in products %}
<a href="/products/{{product.id}}" class="product product-link"> <a href="/products/{{product.id}}" class="product product-link">
<div class="product-title">{{product.name}}</div> <div class="product-title">{{product.name}}</div>

View File

@ -5,7 +5,7 @@
<input type="text" name="search" placeholder="Find your favourite products" class="search-bar"> <input type="text" name="search" placeholder="Find your favourite products" class="search-bar">
<input type="submit" class="search-button"> <input type="submit" class="search-button">
</form> </form>
{% if user != None: %} {% if user is not None: %}
<a href="/logout">Welcome, {{ user.username }}</a> <a href="/logout">Welcome, {{ user.username }}</a>
{% else %} {% else %}
<a href="/login">Login/Signup</a> <a href="/login">Login/Signup</a>
@ -13,7 +13,7 @@
</nav> </nav>
<centre> <centre>
{% if user != None and user.role == "Seller" %} {% if user is not None and user.role == "Seller" %}
<div class="categories"> <div class="categories">
{# List all available seller tools #} {# List all available seller tools #}
<a href="/products/add" class="category">Create Products</a> <a href="/products/add" class="category">Create Products</a>

View File

@ -22,7 +22,8 @@ def test_create_product():
db = ProductController() db = ProductController()
db.create(product) db.create(product)
# Tests the database maintains integrity when we try and add a product with the same details # Tests the database maintains integrity when we try
# and add a product with the same details
@pytest.mark.skip @pytest.mark.skip
@ -40,7 +41,7 @@ def test_search_category():
# Check each category for correct amount of test products # Check each category for correct amount of test products
assert len(db.read_all("Car Parts")) == 9 + 1 # Added in previous test assert len(db.read_all("Car Parts")) == 9 + 1 # Added in previous test
assert len(db.read_all("Books")) == 9 assert len(db.read_all("Books")) == 9
assert db.read_all("Phones") == None assert db.read_all("Phones") is None
# Tests that products can be refined by search term # Tests that products can be refined by search term
@ -51,7 +52,7 @@ def test_search_term():
assert len(db.read_all(search_term="test")) == 33 assert len(db.read_all(search_term="test")) == 33
assert len(db.read_all("Car Parts", "test")) == 9 assert len(db.read_all("Car Parts", "test")) == 9
assert len(db.read_all(search_term="product")) == 1 assert len(db.read_all(search_term="product")) == 1
assert db.read_all(search_term="not_test") == None assert db.read_all(search_term="not_test") is None
# Test we the same product details get returned from the database # Test we the same product details get returned from the database

View File

@ -29,7 +29,8 @@ def test_create_user():
db = UserController() db = UserController()
db.create(customer) db.create(customer)
# Tests the database maintains integrity when we try and add a user with the same details # Tests the database maintains integrity when we try
# and add a user with the same details
def test_duplicate_user(): def test_duplicate_user():