Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added flask_website/__pycache__/config.cpython-310.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
33 changes: 7 additions & 26 deletions flask_website/admin/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
More
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Contribute</a>
<a class="dropdown-item" href="/view">View database</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="/todo/">View my to-do list</a>
Expand All @@ -39,7 +39,7 @@
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled,just like your mum</a>
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled for now</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
Expand All @@ -48,32 +48,13 @@
</form>
</div>
</nav>

<p></p>
<p></p>
<p></p>
<p></p>

{% block header%}
{% endblock%}
</header>

<!--
<h2>Why have I decided to make yet another website despite not being able to afford hosting?</h2>
<p>
<img src="{{url_for('static', filename='Images/html.jpg')}}" alt="html" style="float:left;width:400-px;height:100px;">
Welcome, {{content}}, to my glorious display of server management.
I still can't afford proper hosting at this point in time but however, I can use Flask to emulate hosting and create web applicatioons based on Python using Flask, which is very helpful.
</p>
-->
{%block usr%}

{%endblock%}
{%block content%}

{%endblock%}

<button> <a href="/play">Play a song</a></button>


{%block content%}
{%endblock%}

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
Expand Down
5 changes: 1 addition & 4 deletions flask_website/admin/templates/flaskindex.html
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,5 @@ <h1>A table of all of the data held within the database</h1>
<p class="data2">Email: {{item.email}}</p>
{% endfor %}

<image src="{{ url_for('static', filename='Images/code-matrix.jpg')}}" >
{%endblock%}

{% block usr%}
{%endblock%}

11 changes: 8 additions & 3 deletions flask_website/admin/templates/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,14 @@
{% endfor %}
{% endif %}
{% endwith %}

<h2> Sign up form</h2>

<form method="POST">
<p>Name:</p>
<p><input type="text" name="nm" /></p>
<p><input type="text" name="nm" placeholder="Enter your username"/></p>
<p><input type="text" name="password" placeholder="Enter password"/></p>
<p><input type="submit" name="Submit" value="Submit" /></p>
</form>
</form>
<a href="\signup" class="btn btn-primary">Sign up</a>

{% endblock %}
49 changes: 49 additions & 0 deletions flask_website/admin/templates/signup.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{% extends "base.html" %}
{% block title%}Login Page{% endblock %}
{%block style%}
<style>
*
{
background-color: #1BD2BB;
color: black;
}

h1
{
background-color: #E86549;
}

button
{
background-color: #09E268;
color: black;
}

input
{
background-color: white;
color: black;
}
</style>
{%endblock%}
{% block content%}
{% with messages = get_flashed_messages()%}
{% if messages%}
{% for msg in messages%}
<p>{{msg}}</p>
{% endfor %}
{% endif %}
{% endwith %}

<h2>Sign up form</h2>
<p> Please enter your details for your new account, ensuring that your details are brand new and not linked to any other accounts.</p>

<form method="POST">
<p><input type="text" name="nm" placeholder="Enter your username"/></p>
<p><input type="text" name="email" placeholder="Enter your email"/></p>
<p><input type="text" name="password1" placeholder="Enter password"/></p>
<p><input type="text" name="password2" placeholder="Confirm password"/></p>
<p><input type="submit" name="Submit" value="Submit" /></p>
</form>

{%endblock%}
11 changes: 5 additions & 6 deletions flask_website/admin/templates/todoindex.html
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ <h1> Welcome to your collections of tasks. Here, you can modify and view your ta
{% endblock %}
{%block content%}

<p>This website is the collection of my Flask skill taught to me by Tech With Tim. I am a man of honour, so I like to give credit where it is due</p>
<div> Add a new task here:
<form action="/todo/add" method="POST">
<input style="width: 30%;" type="text" name="task">
Expand All @@ -65,7 +64,7 @@ <h2>Incomplete tasks</h2>
<h2>Completed task</h2>
<ul>
{% for i in completed_todos%}
<li> {{i.body}} <a style="font-size: 15px" href="{{url_for('todo.incomplete', id=i.id)}}">Mark as incomplete</a> <a style="font-size: 15px" href="">Delete this task</a></li>
<li> {{i.body}} <a style="font-size: 15px" href="{{url_for('todo.incomplete', id=i.id)}}">Mark as incomplete</a> <a style="font-size: 15px" href="{{url_for('todo.delete', id=i.id)}}">Delete this task</a></li>
{% endfor%}
</ul>

Expand All @@ -74,8 +73,8 @@ <h2>Completed task</h2>
</div>


<image src="{{ url_for('static', filename='Images/code-matrix.jpg')}}" >
<image src="{{ url_for('admin.static', filename='Images/code-matrix.jpg')}}" >

<p>This website is the collection of my Flask skill taught to me by Tech With Tim. I am a man of honour, so I like to give credit where it is due</p>
{%endblock%}

{% block usr%}
{%endblock%}

47 changes: 39 additions & 8 deletions flask_website/databases.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
from flask_sqlalchemy import SQLAlchemy
from datetime import timedelta, datetime
from flask_login import UserMixin
from sqlalchemy.sql import func
from hashlib import md5
from flask import Flask

db = SQLAlchemy()

class users(db.Model):
class users(db.Model, UserMixin):
#__tablename__ = "users"
id = db.Column("id", db.Integer, primary_key=True)
name = db.Column("name", db.String(100), unique=True)
about_me = db.Column("about_me", db.String(200))
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
tasks = db.relationship('Todo', backref='post_author', lazy='dynamic')
learn = db.relationship('Learning', backref='author', lazy='dynamic')
def avatar(self, size):
digest = md5(self.email.lower().encode('utf-8')).hexdigest()
return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(
digest, size)
'''
For those unaware of SQL, I have set a column(field using the SQL jargon) called
'id' which will be my primary_key. The primary key is used to identify the
Expand All @@ -14,26 +27,44 @@ class users(db.Model):
in order to find the right data. Each column can only hold data of a certain type,
so I have used integers because it is simplest
'''
name = db.Column("name", db.String(100))
email = db.Column(db.String(100))
'''
the number in the brackets next to db.String define the maximum length of the strings allowed within that colummn
'''
tasks = db.relationship('Todo', backref='author', lazy='dynamic')

def __init__(self, name, email):
def __init__(self, name, email, password):
self.name = name
self.email = email
self.password = password

def __repr__(self):
return '<Username: {0}, Email: {1}>'.format(self.name, self.email)
pass

#This database handles all tasks set per user
class Todo(db.Model):
#__tablename__ = "todo"
id = db.Column(db.Integer, primary_key=True)
body= db.Column(db.String(300))
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
body= db.Column(db.String(300), nullable=False)
author= db.Column(db.String(100), nullable=False) #I need to update my table somehow
timestamp = db.Column(db.DateTime(timezone=True), index=True, default=func.now())
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
complete = db.Column(db.Boolean)

#users_rel = db.relationship(users)
def __repr__(self):
return '<Task: {}>'.format(self.body)

pass

class Learning(db.Model):
#__searchable__ = ['title', 'body']
id = db.Column(db.Integer, primary_key=True)
title= db.Column(db.String(300), nullable=False)
body = db.Column(db.String(500), nullable=False)
timestamp = db.Column(db.DateTime, index=True, default=func.now())
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))

def __repr__(self):
return '<Post title: {}>'.format(self.title)

pass
84 changes: 45 additions & 39 deletions flask_website/hello.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from html.entities import name2codepoint
from flask import Flask, redirect, url_for, render_template,request, session, flash, g
from admin.blueprint import blueprint #this is possible because my empty __init__.py file allows me to access files from different folders
#import songify as song #This can be used to play songs currently downloaded on device
Expand All @@ -6,7 +7,7 @@
import logging
from flask_migrate import Migrate
from databases import db, users #This allows me to access databases in other files

from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)

Expand All @@ -15,9 +16,7 @@ def load_user():
g.user = None

if 'user' in session:
user = User.query.filter_by(username=session['user']).first()
app.logger.info("we have identified the location of the user in session")
app.logger.info(str(session.get('user')) + " - We have added the user to g so that it is globally accessible across functions.")
user = users.query.filter_by(name=session['user']).first()
g.user = session['user']


Expand Down Expand Up @@ -47,18 +46,6 @@ def load_user():
migrate = Migrate(app, db)
db.init_app(app)

@app.route('/')
def index():
#print(app.config)
app.logger.info(app.config) #I use this so I can see print messages while
#running my Flask file at the same time - not possible on Mac apparantly
return render_template("flaskindex.html")
#render_template just gets rid of complaints from flask
app.logger.info(metadata.tables.keys())
@app.route("/<name>")
def homepage(name):
return render_template("flaskindex.html", content=name)

@app.route("/view")
def view():
return render_template("flaskindex.html",values=users.query.all())
Expand All @@ -68,20 +55,23 @@ def login():
if request.method == "POST":
session.pop('user', None)

username = request.form['nm'] #searches for name submitted at login page
username = request.form.get('nm')#searches for name submitted at login page
password = request.form.get('password')
found_user = users.query.filter_by(name=username).first() #checks to see if user exists in database

#If error shows, that means for now that user doesn't exist
app.logger.info(found_user.name) #prints to console during runtime (can't use print now)
try:
#If error shows, that means for now that user doesn't exist
app.logger.info(found_user.name) #prints to console during runtime (can't use print now)
except:
app.logger.warning(username + " doesn't exist on our database.")
app.logger.warning(users.query.all())
if found_user: #If existing user
session['user'] = found_user.name #creates new session for user
detail = session.get('user')
app.logger.info(str(detail) + " - Hooray, we are logged in.")
return redirect(url_for('user', detail=detail)) #redirects to user-only content

flash("Unfortunately, we have an internal error at our servers. Either your account doesn't exist or we have a bug.")
if check_password_hash(found_user.password, password):
session['user'] = found_user.name #creates new session for user
app.logger.info(str(session.get('user')) + " - Hooray, we are logged in.")
return redirect(url_for('user', detail=session.get('user'))) #redirects to user-only content
flash('Incorrect password entered. Please try again', category='error')
return redirect(url_for('login'))

else:
if 'user' in session:
app.logger.info("You are already logged in")
Expand All @@ -96,13 +86,6 @@ def logout():

@app.route("/user/<detail>", methods=['POST','GET'])
def user(detail):
if detail:
#return render_template("flaskindex.html", user=g.user.name)
app.logger.info("Bruh, what is going on, " + str(detail))
else:
app.logger.info(str(session.get('user')) + " - str(g.user) doesn't work in the other one but somehow works here")
return render_template("flaskindex.html", user="Anonymous User created from a mistake")

if request.method == "POST":
email = request.form["email"]
session["email"] = email
Expand All @@ -126,12 +109,35 @@ def user(detail):
flash("You are not logged in yet, you should login in for full access to all features")
return redirect(url_for("login"))

'''
@app.route('/play')
def playsong():
song.funkymusic("Kanskaart - Congratulations (100K Special).mp3")
'''
@app.route("/signup", methods=['GET','POST'])
def signup():
if request.method == 'POST':
name = request.form.get('nm')
email = request.form.get('email')
p1 = request.form.get('password1')
p2 = request.form.get('password2')
if len(email) < 12 and "@" not in email and ".com" not in email:
flash("Please input an email in the correct format, containing an @ and a '.com' ", category='warning')
elif p1 != p2 or len(p1) == 0 or len(p2) == 0:
flash("Please enter the same password in both password input boxes", category='warning')
elif len(users.query.filter_by(name=name).all()) > 1 or len(users.query.filter_by(email=email).all()) > 1:
flash("Perhaps you already have an account. Try logging in with that account, if you remember the details fully", category='warning')
return redirect(url_for('login'))
else:
new_user = users(name=name, email=email, password=generate_password_hash(p1, "pbkdf2:sha512"))
db.session.add(new_user)
db.session.commit()
try:
#session['user'] = users.query.filter_by(name=name).first().name
#Seem to be unable to search the database
return redirect(url_for('user', detail=name))
except:
app.logger.info("We have a problem, officer. {} is not bein put into the database".format(name))
app.logger.info(session.get('user'))
app.logger.info(users.query.all())

return render_template('signup.html')

if __name__ == "__main__":
#db.create_all() #creates the database in case it doesn't already exist
db.create_all(app=app) #creates the database in case it doesn't already exist
app.run(debug=True)
Binary file modified flask_website/users.sqlite3
Binary file not shown.