Commit 96293c3f authored by danmcquillan's avatar danmcquillan

adding lab 20 steps 1,2,3

parent 50d7281b
import pymysql
import datetime
import hashlib
class DBHelper:
def __init__(self):
self.db = pymysql.connect(host='localhost',
user='mytwits_user',
passwd='mytwits_password',
db='mytwits')
def get_user(self, user_id):
query = "select * from users where user_id=%s"
with self.db.cursor() as cursor:
cursor.execute(query,user_id)
return cursor.fetchone()
def get_all_twits(self):
query = "select u.username, t.twit_id, t.twit, t.created_at from twits t, users u where t.user_id=u.user_id order by t.created_at desc;"
with self.db.cursor(pymysql.cursors.DictCursor) as cursor:
cursor.execute(query)
return cursor.fetchall()
def get_twit(self,twit_id):
query = "select twit_id, twit, created_at from twits where twit_id=%s"
# using
with self.db.cursor(pymysql.cursors.DictCursor) as cursor:
# note that we are using a cursor which returns the results as a
# dictionary
# https://pymysql.readthedocs.io/en/latest/modules/cursors.html
# this is so we can use resource_fields and @marshal_with for our
# flask-restful api
cursor.execute(query, twit_id)
return cursor.fetchone()
def get_user_twits(self,username):
query = "select u.username, t.twit, t.created_at from twits t,\
users u where t.user_id=u.user_id and u.username=%s order by t.created_at desc;"
with self.db.cursor() as cursor:
cursor.execute(query,(username))
return cursor.fetchall() # The method fetches all (or all remaining) rows of a query result set and returns a list of tuples
#
def add_twit(self,twit,user_id):
query = "insert into twits (twit,user_id) values \
(%s,%s);"
with self.db.cursor() as cursor:
cursor.execute(query, (twit,user_id))
return self.db.commit()
def update_twit(self,twit,twit_id):
query = "update twits set twit=%s where twit_id=%s"
with self.db.cursor() as cursor:
cursor.execute(query,(twit,twit_id))
return self.db.commit()
def delete_twit(self,twit_id):
query = "delete from twits where twit_id=%s"
with self.db.cursor() as cursor:
cursor.execute(query, twit_id)
return self.db.commit()
def check_password(self,username,password):
query = "select user_id, salt, hashed from users where username = %s;"
with self.db.cursor() as cursor:
cursor.execute(query,(username))
user = cursor.fetchone()
if user:
user_id, salt, hashed = user
if hashlib.sha512((salt + password).encode('utf-8')).hexdigest() == hashed:
return user_id
return None
db = DBHelper()
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms import HiddenField
from wtforms import PasswordField
from wtforms import SubmitField
from wtforms import validators
class addTwitForm(FlaskForm):
twit = StringField('twit', validators = [validators.DataRequired()])
submit = SubmitField('submit', [validators.DataRequired()])
class editTwitForm(FlaskForm):
twit = StringField('twit', validators = [validators.DataRequired()])
twit_id = HiddenField('twit_id')
submit = SubmitField('submit', [validators.DataRequired()])
class loginForm(FlaskForm):
username = StringField('username', validators = [validators.DataRequired()])
password = PasswordField('password', validators =[validators.DataRequired()])
password2 = PasswordField('password2', validators=[validators.DataRequired(),
validators.EqualTo('password', message='Passwords must match')])
submit = SubmitField('submit', [validators.DataRequired()])
from flask import Flask, request
from flask import render_template
from flask import redirect, url_for
from flask import flash
from vs_url_for import vs_url_for
from forms import loginForm
from dbhelper import DBHelper
from flask_login import LoginManager, login_required
from flask_login import login_user, logout_user
from flask_login import current_user
from user import User
login_manager = LoginManager()
from dbhelper import db
from twits_blueprint import twits_blueprint
app = Flask(__name__)
login_manager.init_app(app)
app.register_blueprint(twits_blueprint)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
#---- the callback function for flask-login
@login_manager.user_loader
def load_user(user_id):
result = db.get_user(user_id)
if result:
username = result[1]
return User(user_id,username)
@app.route('/login', methods = ['GET', 'POST'])
def login():
form = loginForm()
if form.validate_on_submit():
password = form.password.data
username = form.username.data
user_id = db.check_password(username,password)
if user_id:
user = User(user_id, username)
login_user(user)
return redirect(vs_url_for('twits_blueprint.index'))
else:
flash('login unsuccessful!')
return render_template('login.html',form=form)
@app.route('/logout')
def logout():
# remove the username from the session if it's there
logout_user()
return redirect(vs_url_for('twits_blueprint.index'))
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0',port=8000)
{% extends "base.html" %}
{% block body %}
<div class="jumbotron">
<div >
<form class="form-horizontal" method="post" action="/add_twit">
{{ form.csrf_token }}
<div class='form-group'>
<div class='col-md-6'>
{% if form.twit.errors %}
<ul class='errors'>
{% for error in form.twit.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
{{ form.twit(class='form-control',placeholder='twit') }}
</div>
</div>
<div class='form-group'>
<div class='col-md-6'>
{{ form.submit(class='btn btn-primary btn-block') }}
</div>
</div>
</form>
</div>
</div>
{% endblock %}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css"
integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<!--- flash messages -->
{% for category, message in get_flashed_messages(with_categories=true) %}
<div class="alert alert-dismissable alert-warning alert-{{ category }}">
<button type="button" class="close" data-dismiss="alert">&times;</button>
{{ message }}
</div>
{% endfor %}
{% if current_user.is_authenticated %}
<div class="lead mark">
logged in as {{ current_user.username }}
</div>
{% endif %}
<!--- the body will come from a template that inherits from this one -->
{% block body %}{% endblock %}
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js" integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4" crossorigin="anonymous"></script>
</body>
</html>
{% extends "base.html" %}
{% block body %}
<div class="jumbotron">
<div >
<form class="form-horizontal" method="post" action="/edit_twit">
{{ form.csrf_token }}
<div class='form-group'>
<div class='col-md-6'>
{% if form.twit.errors %}
<ul class='errors'>
{% for error in form.twit.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
{{ form.twit(class='form-control') }}
</div>
</div>
<div>
{{ form.twit_id }}
</div>
<div class='form-group'>
<div class='col-md-6'>
{{ form.submit(class='btn btn-primary btn-block') }}
</div>
</div>
</form>
</div>
</div>
{% endblock %}
{% extends "base.html" %}
{% block body %}
<div class="jumbotron">
<form class='form-horizontal' method="post">
{{ form.csrf_token }}
<div class='form-group'>
<div class='col-md-6'>
{% if form.username.errors %}
<ul class='errors'>
{% for error in form.username.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
{{ form.username(class='form-control',placeholder='username') }}
</div>
</div>
<div class='form-group'>
<div class='col-md-6'>
{% if form.password.errors %}
<ul class='errors'>
{% for error in form.password.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
{{
form.password(class='form-control',placeholder='password') }}
</div>
</div>
<div class='form-group'>
<div class='col-md-6'>
{% if form.password2.errors %}
<ul class='errors'>
{% for error in form.password2.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
{{ form.password2(class='form-control',placeholder='confirm password') }}
</div>
</div>
<div class='form-group'>
<div class='col-md-6'>
{{ form.submit(class='btn btn-primary btn-block') }}
</div>
</div>
</form>
</div >
{% endblock %}
{% extends "base.html" %}
{% block body %}
<div class="jumbotron">
{% for twit in twits %}
<div class="row">
<div class="col-md-4">{{ twit['username'] }}</div>
<div class="col-md-4">{{ twit['twit'] }}</div>
<div class="col-md-4"><a href='/edit_twit?id={{ twit['twit_id'] }}'> edit </a><a
href='/delete_twit?id={{ twit['twit_id'] }}'> delete </a></div>
</div>
{% endfor %}
</div>
{% endblock %}
from flask import Blueprint
from flask import render_template
from flask import redirect, url_for
from flask import request
from vs_url_for import vs_url_for
from flask_login import current_user
from flask_login import LoginManager, login_required
from forms import addTwitForm, editTwitForm
from dbhelper import db
twits_blueprint = Blueprint('twits_blueprint', __name__,
template_folder = 'templates')
@twits_blueprint.route('/')
def index():
twits = db.get_all_twits()
return render_template("mytwits_mysql.html", twits=twits)
@twits_blueprint.route('/add_twit', methods = ['GET', 'POST'])
@login_required
def add_twit():
form = addTwitForm()
if form.validate_on_submit():
twit = form.twit.data
user_id = current_user.user_id
db.add_twit(twit,user_id)
return redirect(vs_url_for('.index'))
return render_template('add_twit_mysql.html',form=form)
@twits_blueprint.route('/edit_twit', methods = ['GET', 'POST'])
@login_required
def edit_twit():
form = editTwitForm()
if request.args.get('id'):
twit_id = request.args.get('id')
twit = db.get_twit(twit_id)
form.twit.data = twit['twit']
form.twit_id.data = twit_id
return render_template('edit_twit_mysql.html',form=form,twit=twit)
if form.validate_on_submit():
twit = form.twit.data
twit_id = form.twit_id.data
db.update_twit(twit,twit_id)
return redirect(vs_url_for('.index'))
return render_template('edit_twit_mysql.html',form=form)
@twits_blueprint.route('/delete_twit', methods = ['GET', 'POST'])
@login_required
def delete_twit():
if request.args.get('id'):
twit_id = request.args.get('id')
twit = db.delete_twit(twit_id)
return redirect(vs_url_for('.index'))
class User:
def __init__(self, user_id,username):
self.user_id = user_id
self.username = username
def username(self):
return self.username
@property
def is_authenticated(self):
return True
@property
def is_active(self):
return True
@property
def is_anonymous(self):
return False
def get_id(self):
return self.user_id
def __repr__(self):
return 'user_id {}'.format(self.user_id)
from flask import url_for
URL_PREFIX = '/usr/253'
#URL_PREFIX = ''
def vs_url_for(view):
url = url_for(view)
url = URL_PREFIX + url
return url
import pymysql
import datetime
import hashlib
class DBHelper:
def __init__(self):
self.db = pymysql.connect(host='localhost',
user='mytwits_user',
passwd='mytwits_password',
db='mytwits')
def get_user(self, user_id):
query = "select * from users where user_id=%s"
with self.db.cursor() as cursor:
cursor.execute(query,user_id)
return cursor.fetchone()
def get_all_twits(self):
query = "select u.username, t.twit_id, t.twit, t.created_at from twits t, users u where t.user_id=u.user_id order by t.created_at desc;"
with self.db.cursor(pymysql.cursors.DictCursor) as cursor:
cursor.execute(query)
return cursor.fetchall()
def get_twit(self,twit_id):
query = "select twit_id, twit, created_at from twits where twit_id=%s"
# using
with self.db.cursor(pymysql.cursors.DictCursor) as cursor:
# note that we are using a cursor which returns the results as a
# dictionary
# https://pymysql.readthedocs.io/en/latest/modules/cursors.html
# this is so we can use resource_fields and @marshal_with for our
# flask-restful api
cursor.execute(query, twit_id)
return cursor.fetchone()
def get_user_twits(self,username):
query = "select u.username, t.twit, t.created_at from twits t,\
users u where t.user_id=u.user_id and u.username=%s order by t.created_at desc;"
with self.db.cursor() as cursor:
cursor.execute(query,(username))
return cursor.fetchall() # The method fetches all (or all remaining) rows of a query result set and returns a list of tuples
#
def add_twit(self,twit,user_id):
query = "insert into twits (twit,user_id) values \
(%s,%s);"
with self.db.cursor() as cursor:
cursor.execute(query, (twit,user_id))
return self.db.commit()
def update_twit(self,twit,twit_id):
query = "update twits set twit=%s where twit_id=%s"
with self.db.cursor() as cursor:
cursor.execute(query,(twit,twit_id))
return self.db.commit()
def delete_twit(self,twit_id):
query = "delete from twits where twit_id=%s"
with self.db.cursor() as cursor:
cursor.execute(query, twit_id)
return self.db.commit()
def check_password(self,username,password):
query = "select user_id, salt, hashed from users where username = %s;"
with self.db.cursor() as cursor:
cursor.execute(query,(username))
user = cursor.fetchone()
if user:
user_id, salt, hashed = user
if hashlib.sha512((salt + password).encode('utf-8')).hexdigest() == hashed:
return user_id
return None
db = DBHelper()
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms import HiddenField
from wtforms import PasswordField
from wtforms import SubmitField
from wtforms import validators
class addTwitForm(FlaskForm):
twit = StringField('twit', validators = [validators.DataRequired()])
submit = SubmitField('submit', [validators.DataRequired()])
class editTwitForm(FlaskForm):
twit = StringField('twit', validators = [validators.DataRequired()])
twit_id = HiddenField('twit_id')
submit = SubmitField('submit', [validators.DataRequired()])
class loginForm(FlaskForm):
username = StringField('username', validators = [validators.DataRequired()])
password = PasswordField('password', validators =[validators.DataRequired()])
password2 = PasswordField('password2', validators=[validators.DataRequired(),
validators.EqualTo('password', message='Passwords must match')])
submit = SubmitField('submit', [validators.DataRequired()])
from flask import Blueprint
from forms import loginForm
from flask import render_template
from flask import redirect, url_for
from flask import flash
from flask_login import LoginManager, login_required
from flask_login import login_user, logout_user
from flask_login import current_user
from user import User
from vs_url_for import vs_url_for
from dbhelper import db
login_manager = LoginManager()
login_blueprint = Blueprint('login_blueprint', __name__,
template_folder = 'templates')
@login_blueprint.record_once
def on_load(state):
login_manager.init_app(state.app)
#---- the callback function for flask-login
@login_manager.user_loader
def load_user(user_id):
result = db.get_user(user_id)
if result:
username = result[1]
return User(user_id,username)
@login_blueprint.route('/login', methods = ['GET', 'POST'])
def login():
form = loginForm()
if form.validate_on_submit():
password = form.password.data
username = form.username.data
user_id = db.check_password(username,password)
if user_id:
user = User(user_id, username)
login_user(user)
return redirect(vs_url_for('twits_blueprint.index'))
else:
flash('login unsuccessful!')
return render_template('login.html',form=form)
@login_blueprint.route('/logout')
def logout():
# remove the username from the session if it's there
logout_user()
return redirect(vs_url_for('twits_blueprint.index'))
from flask import Flask
from twits_blueprint import twits_blueprint
from login_blueprint import login_blueprint
from flask_login import current_user
app = Flask(__name__)
#login_manager.init_app(app)
app.register_blueprint(twits_blueprint)
app.register_blueprint(login_blueprint)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
if __name__ == '__main__':