'''
The purpose of this program is to demonstrate proper code security practices
and logging methods to secure a python website.
'''
from flask import Flask, render_template, request, jsonify, flash, redirect, url_for
import logging
logging.basicConfig(filename='Troubleshooting_app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', )
logger = logging.getLogger(__name__)
app = Flask(__name__)
app.secret_key = 'supersecretkeyforflasksessions'
# Equipment Pricing Data
EQUIPMENT_PRICES = {
"Bulldozer": 500,
"Excavator": 450,
"Crane": 800
}
# Helper Functions
def validate_username(username):
assert username is not None, "Username is empty"
assert isinstance(username, str), "Username must be string"
logger.info("Username is valid")
allowed_users = {"admin", "alice", "bob", "charlie"}
if username in allowed_users:
return True
return False
# Routes
@app.route('/')
def home():
logger.info("Home page accessed")
return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get("username")
password = request.form.get("password")
# Simulated IP address
ip_address = request.remote_addr
logger.info(f"Login attempt from {username} {ip_address}")
assert ip_address is not None, "IP address is empty"
if (ip_address.startswith("192.168.") or ip_address.startswith("10.")):
pass
else:
logger.warning("IP is suspicious")
# Authentication Logic
if validate_username(username) and password == "secret123":
logger.info(f"User {username} logged in.")
flash(f"Welcome back, {username}!", "success")
return redirect(url_for('home'))
else:
logger.warning(f"Login failed for {username}.")
flash("Invalid credentials.", "danger")
return redirect(url_for('login'))
return render_template('login.html')
@app.route('/rent', methods=['GET', 'POST'])
def rent_equipment():
rental_result = None
if request.method == 'POST':
equipment_type = request.form.get("equipment_type")
days_str = request.form.get("days")
logger.info(f"Rental request of {equipment_type} for {days_str}")
# Potential Crash: equipment_type not in dictionary
try:
if equipment_type not in EQUIPMENT_PRICES:
raise KeyError(f"{equipment_type} is not in dictionary")
daily_rate = EQUIPMENT_PRICES[equipment_type]
# Potential Crash: invalid days_str
days = int(days_str)
# Logic Defect: days <= 0
assert days > 0, "Days must be greater than 0"
logger.info("Days is valid")
total_cost = daily_rate * days
logger.info(f"Calculated cost: {total_cost}")
rental_result = {
"equipment": equipment_type,
"days": days,
"total_cost": total_cost
}
flash("Rental calculated successfully!", "success")
except KeyError:
logger.error(f"{equipment_type} is not in dictionary")
flash("Invalid equipment input")
except ValueError:
logger.warning("Days value is invalid")
flash("Invalid days value")
except AssertionError:
logger.error("Days input is invalid")
flash("Invalid days input")
return render_template('rent.html', rental_result=rental_result)
if __name__ == '__main__':
logger.info("Starting application...") # Replace with logger
app.run(debug=False, port=5000)
import requests
import json
def get_movies_from_tastedive(movie_name):
tastedive = "https://tastedive.com/api/similar"
params_diction = {}
params_diction['q'] = movie_name
params_diction['type'] = 'movies'
params_diction['limit'] = 5
movie = requests.get(tastedive, params = params_diction)
print(movie.url)
return movie.json()
def extract_movie_titles(movie):
title_lst = [name["Name"]for name in movie["Similar"]["Results"]]
return title_lst
def get_related_titles(movie_lst):
title_lst = []
for movie in movie_lst:
get_movie = get_movies_from_tastedive(movie)
extracted_movies = extract_movie_titles(get_movie)
for movie_title in extracted_movies:
if movie_title not in title_lst:
title_lst.append(movie_title)
return title_lst
def get_movie_data(movie_name):
OMDB = "http://www.omdbapi.com/"
params_diction = {}
params_diction['t'] = movie_name
params_diction['r'] = 'json'
movie_data = requests_with_caching.get(OMDB, params = params_diction)
print(movie_data.url)
return movie_data.json()
def get_movie_rating(movie_data):
for rate in movie_data['Ratings']:
if rate['Source'] == 'Rotten Tomatoes':
return int(rate['Value'][:2])
return int(0)
def get_sorted_recommendations(input_movie):
recommended = []
related = get_related_titles(input_movie)
for movie in related:
recommended.append(movie)
sorted_recommendations = sorted(recommended, key = lambda x: (get_movie_rating(get_movie_data(x)), x), reverse = True)
return sorted_recommendations