Files

268 lines
8.3 KiB
Python

from functools import wraps
from flask import Flask, render_template, redirect, request, url_for, session, flash
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy.exc import IntegrityError
app = Flask(__name__)
# email_option = str(0)
# email = str(0)
# password = str(0)
# with app.app_context():
# print("--- Server Initialization ---")
# response = input("Set the email and password type 'skip' to skip this: ")
# if response.lower() != "skip":
# email = input("Enter your email")
# password = input("Enter your emails password")
# print(f"Server started. Current role is: {email}\n")
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///accounts.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'this key is so secret noone will ever get it 👌'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(128), nullable=False)
with app.app_context():
db.create_all()
def login_required(view_func):
@wraps(view_func)
def wrapped(*args, **kwargs):
if 'user_id' not in session:
flash('sign in to view that page.')
return redirect(url_for('signin'))
return view_func(*args, **kwargs)
return wrapped
from sqlalchemy.exc import IntegrityError
@app.route('/submit-form', methods=['POST'])
def handle_submission():
form_username = (request.form.get('username') or '').strip()
form_email = (request.form.get('email') or '').strip().lower()
form_password = request.form.get('password') or ''
if not form_username or not form_email or not form_password:
return render_template('signup.html', error="All fields must be entered to complete registration"), 400
if len(form_password) < 8:
return render_template('signup.html', error="Password must be at least 8 characters"), 400
if User.query.filter_by(username=form_username).first():
return render_template('signup.html', user_taken="Username has already been taken"), 400
if User.query.filter_by(email=form_email).first():
return render_template('signup.html', email_taken="Email has already been used before"), 400
hashed_password = generate_password_hash(form_password)
new_user = User(username=form_username, email=form_email, password_hash=hashed_password)
try:
db.session.add(new_user)
db.session.commit()
except IntegrityError:
db.session.rollback()
return render_template('signup.html', error="Username or email has already taken"), 400
return render_template('signup.html', success_message="Account successfully created")
@app.route('/users')
def view_users():
all_users = User.query.all()
html_output = "<h2>Registered Accounts</h2><table border='1' cellpadding='10'>"
html_output += "<tr><th>ID</th><th>Username</th><th>Email</th></tr>"
for user in all_users:
html_output += f"<tr><td>{user.id}</td><td>{user.username}</td><td>{user.email}</td></tr>"
html_output += "</table>"
if not all_users:
return "<h3>emptyyyyy daaatabase</h3>"
return html_output
# Mail system uncomment all of the stuff below this line to use but requires a google account to use will have to put email in username area and password in password area when starting the py file
# app.config['MAIL_SERVER'] = 'smtp.google.com'
# app.config['MAIL_PORT'] = 587
# app.config['MAIL_USE_TLS'] = True
# app.config['MAIL_USERNAME'] = email
# app.config['MAIL_PASSWORD'] = password
quiz_data = {
"quizzes": {
"linearprogramming": [
{
"question": "1",
"options": ["1", "2", "3", "4"],
"answer": "1"
},
{
"question": "2",
"options": ["1", "2", "3", "4"],
"answer": "2"
},
{
"question": "3",
"options": ["1", "2", "3", "4"],
"answer": "3"
},
]
}
}
@app.route('/')
def home():
return render_template('index.html')
@app.route('/bivariate')
@login_required
def bivariate():
return render_template('bivariate.html')
@app.route('/linearprogramming')
@login_required
def linearprogramming():
return render_template('linearprogramming.html', quizzes=quiz_data["quizzes"])
@app.route('/start_quiz/<quiz_name>')
def start_quiz(quiz_name):
session['quiz_name'] = quiz_name
session['current_question'] = 0
session['score'] = 0
return redirect(url_for('linearprogrammingquiz'))
@app.route('/simultaneousequations')
@login_required
def simultaneousequations():
return render_template('simultaneousequations.html')
@app.route('/calculus')
@login_required
def calculus():
return render_template('calculus.html')
@app.route('/triganometry')
@login_required
def triganometry():
return render_template('triganometry.html')
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/signin', methods=['GET', 'POST'])
def signin():
if request.method == 'POST':
form_username = request.form.get('username')
form_password = request.form.get('password')
user = User.query.filter_by(username=form_username).first()
if user is None or not check_password_hash(user.password_hash, form_password):
flash('Incorrect username or password.')
return render_template('signin.html'), 401
session['user_id'] = user.id
session['username'] = user.username
return redirect(url_for('home'))
return render_template('signin.html')
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('home'))
@app.route('/signup')
def signup():
return render_template('signup.html')
@app.route('/pagemaker')
def pagemaker():
return render_template('pagemaker.html')
@app.route('/all_users')
@login_required
def all_users():
return render_template('all_users.html')
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.route('/resetpassword')
def resetpassword():
return render_template('resetpassword.html')
@app.route('/resetpasscode')
def resetpasscode():
return render_template('resetpasswordcode.html')
@app.route('/newpassword')
def newpassword():
return render_template('newpassword.html')
@app.route('/linearprogrammingquiz', methods=['GET', 'POST'])
def linearprogrammingquiz():
quiz_name = session.get('quiz_name')
current_question = session.get('current_question', 0) # Default to 0 if not set
quiz_questions = quiz_data["quizzes"].get(quiz_name, [])
if request.method == 'POST':
selected_option = request.form.get('option')
correct_answer = quiz_questions[current_question]['answer']
# Check if the selected answer is correct
if selected_option == correct_answer:
session['score'] = session.get('score', 0) + 1 # Increment score if the answer is correct
feedback = "Correct! Well done."
else:
feedback = f"Wrong! The correct answer is {correct_answer}."
# Move to the next question
session['current_question'] = current_question + 1
session['feedback'] = feedback
if session['current_question'] >= len(quiz_questions):
return redirect(url_for('quiz_result'))
return redirect(url_for('linearprogrammingquiz'))
# Handle GET request: get current question data
if current_question < len(quiz_questions):
current_question_data = quiz_questions[current_question]
feedback = session.pop('feedback', '') # Remove feedback from session
return render_template('quiz_question.html', question_data=current_question_data, current_question=current_question + 1, total_questions=len(quiz_questions), feedback=feedback)
else:
return redirect(url_for('quiz_result'))
@app.route('/quiz_result')
def quiz_result():
score = session.get('score', 0) # Default to 0 if score is not found
quiz_name = session.get('quiz_name')
total_questions = len(quiz_data["quizzes"].get(quiz_name, [])) # Handle case where quiz_name might not be found
if __name__ == '__main__':
app.run(debug=True)