Commit 2a9aa3b8 authored by danmcquillan's avatar danmcquillan

added skeleton for flask-login

parent c1e8cd5f
import pymysql
import datetime
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() as cursor:
cursor.execute(query)
return cursor.fetchall() # The method fetches all (or all remaining) rows of a query result set and returns a list of tuples
def get_twit(self,twit_id):
query = "select twit from twits where twit_id=%s"
with self.db.cursor() as cursor:
cursor.execute(query, twit_id)
return cursor.fetchone()
# more detals about cursor.fetchone at
# https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchone.html
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 from users where username = %s and password=%s;"
with self.db.cursor() as cursor:
user_id = None
cursor.execute(query,(username,password))
return cursor.fetchone()
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 session, flash, abort
from vs_url_for import vs_url_for
from forms_flasklogin import addTwitForm, editTwitForm, loginForm
from dbhelper_flasklogin import DBHelper
#>>> import flask_login modules here
#>>> import the user class here
#>>> create an instance of LoginManager here
app = Flask(__name__)
db = DBHelper()
#>>> initiate your login_manager here
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
#>>> add your user_loader callback function here
@app.route('/')
def index():
twits = db.get_all_twits()
return render_template("mytwits_mysql_flasklogin.html", twits=twits)
@app.route('/add_twit', methods = ['GET', 'POST'])
@login_required
def add_twit():
form = addTwitForm()
if form.validate_on_submit():
twit = form.twit.data
db.add_twit(twit,session['user_id'])
return redirect(vs_url_for('index'))
return render_template('add_twit_mysql_flasklogin.html',form=form)
@app.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[0]
form.twit_id.data = twit_id
return render_template('edit_twit_mysql_flasklogin.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_flasklogin.html',form=form)
@app.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'))
@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:
#>>> instantiate the user here
#>>> login the user here
flash('login successful!')
return redirect(vs_url_for('index'))
else:
flash('login unsuccessful!')
return render_template('login.html',form=form)
@app.route('/logout')
def logout():
#>>> logout the user here
return redirect(vs_url_for('index'))
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0',port=8000)
{% extends "base_flasklogin.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 %}
{% current_user.is_authenticated %}
logged in as {{ session['username'] }}
{% 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_flasklogin.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_flasklogin.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_flasklogin.html" %}
{% block body %}
<div class="jumbotron">
{% for twit in twits %}
<div class="row">
<div class="col-md-4">{{ twit[0] }}</div>
<div class="col-md-4">{{ twit[2] }}</div>
<div class="col-md-4"><a href='/edit_twit?id={{ twit[1] }}'> edit </a><a
href='/delete_twit?id={{ twit[1] }}'> delete </a></div>
</div>
{% endfor %}
</div>
{% endblock %}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment