Skip to content

Instantly share code, notes, and snippets.

@giorgi-ghviniashvili
Created April 20, 2018 15:09
Show Gist options
  • Save giorgi-ghviniashvili/c66d1167f2d77fc8f835ba283ee252a8 to your computer and use it in GitHub Desktop.
Save giorgi-ghviniashvili/c66d1167f2d77fc8f835ba283ee252a8 to your computer and use it in GitHub Desktop.
# Check if user logged in
def is_logged_in(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('Unauthorized, Please login', 'danger')
return redirect(url_for('login'))
return wrap
# Dashboard
@app.route('/dashboard')
@is_logged_in
def dashboard():
db = get_db()
# Create cursor
cur = db.cursor()
# Get experiments
cur.execute("SELECT * FROM experiments")
experiments = cur.fetchall()
if len(experiments) > 0:
return render_template('dashboard.html', experiments=experiments)
else:
msg = 'No Experiments Found'
return render_template('dashboard.html', msg=msg)
# Add experiment
@app.route('/add_experiment', methods=['GET', 'POST'])
@is_logged_in
def add_experiment():
form = ExperimentForm(request.form)
if request.method == 'POST' and form.validate():
title = form.title.data
body = form.body.data
db = get_db()
# Create Cursor
cur = db.cursor()
# Execute
cur.execute("INSERT INTO experiments(title, body, author) VALUES('{0}', '{1}', '{2}')".format(title, body, session['username']))
# Commit to DB
db.commit()
flash('Experiment Created', 'success')
return redirect(url_for('dashboard'))
return render_template('add_experiment.html', form=form)
# Edit Experiment
@app.route('/edit_experiment/<string:id>', methods=['GET', 'POST'])
@is_logged_in
def edit_experiment(id):
db = get_db()
# Create cursor
cur = db.cursor()
# Get experiment by id
cur.execute("SELECT * FROM experiments WHERE id = {0}".format(id))
experiment = cur.fetchone()
# Get form
form = ExperimentForm(request.form)
# Populate experiment form fields
form.title.data = experiment['title']
form.body.data = experiment['body']
if request.method == 'POST' and form.validate():
title = request.form['title']
body = request.form['body']
db = get_db()
# Create cursor
cur = db.cursor()
app.logger.info(title)
# Execute
cur.execute ("UPDATE experiments SET title='{0}', body='{1}' WHERE id={2}".format(title, body, id))
# Commit to DB
db.commit()
flash('experiment Updated', 'success')
return redirect(url_for('dashboard'))
return render_template('edit_experiment.html', form=form)
# Delete experiment
@app.route('/delete_experiment/<string:id>', methods=['POST'])
@is_logged_in
def delete_experiment(id):
db = get_db()
# Create cursor
cur = db.cursor()
# Execute
cur.execute("DELETE FROM experiments WHERE id = {0}".format(id))
# Commit to DB
db.commit()
flash('experiment Deleted', 'success')
return redirect(url_for('dashboard'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment