I am working on a side project looking to create a polling app with flask where the admin can input images and then the user will vote on the randomly scrambled images. I am following along with the link below to try and cater the app to my own needs- https://pusher.com/tutorials/live-poll-python/#communicating-with-the-backend.
*I took out my pusher secret key for confidentiality
Everything runs fine accept when i get to the polling page, i click to vote and there is no interaction, i have tried to put the /vote route in the /polling route seeing if maybe it never gets called being out of the function however i did not get any success.
I have attached my app.py and my app.js file, however if need be i can publish my repository to be public on github if that would be helpful. In addition my pusher account had a connection to the app but i am unsure if this connection is still valid. my app.py file is as follows-
from flask import Flask,render_template,request,flash,redirect,url_for
import os
import sqlite3, json
import numpy as np
import pandas as pd
import random
from pusher import Pusher
from sqlite3 import Error
import simplejson
app=Flask(__name__)
app.secret_key="123"
pusher = Pusher(
app_id='1580504',
key='7967ce0fbdf40980ed5f',
secret='',
cluster='us2',
ssl=True)
con=sqlite3.connect("myimage.db")
con.execute("create table if not exists image(pid integer primary key,img TEXT,Team TEXT)")
global cur
cur = con.cursor()
con.close()
app.config['UPLOAD_FOLDER']="static\images"
@app.route("/",methods=['GET','POST'])
def upload():
con = sqlite3.connect("myimage.db")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select * from image")
data = cur.fetchall()
con.close()
if request.method=='POST':
upload_image=request.files['upload_image']
Team = request.form.get('Team')
if upload_image.filename!='':
filepath=os.path.join(app.config['UPLOAD_FOLDER'],upload_image.filename)
upload_image.save(filepath)
con=sqlite3.connect("myimage.db")
cur=con.cursor()
cur.execute("insert into image(img, Team)values(?, ?)",(upload_image.filename, Team, ))
con.commit()
flash("File Upload Successfully","success")
con = sqlite3.connect("myimage.db")
con.row_factory=sqlite3.Row
cur=con.cursor()
cur.execute("select * from image")
data=cur.fetchall()
con.close()
return render_template("upload.html",data=data)
return render_template("upload.html",data=data)
@app.route('/admin')
def admin():
return render_template('admin.html')
@app.route("/home")
def home():
return render_template('index.html')
@app.route("/polling")
def polling():
con = sqlite3.connect("myimage.db")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select * from image")
data = cur.fetchall()
#data = [random.choice(data) for _ in range(4)]
data = random.sample(data, 4)
return render_template('next_page.html', data = data)
def main():
global con, cur
def update_item(cur, item):
sql = '''UPDATE items
SET votes = votes + 1
WHERE name = ? '''
cur.execute(sql, item)
def select_all_items(cur, name):
sql = ''' SELECT * FROM items '''
cur.execute(sql)
rows = cur.fetchall()
rows.append({'name' : name})
return json.dumps(rows)
@app.route('/vote', methods=['POST'])
def vote():
data = simplejson.loads(request.data)
update_item(cur, [data['member']])
output = select_all_items(cur, [data['member']])
pusher.trigger(u'poll', u'vote', output)
return request.data
@app.route('/delete_record/<string:id>')
def delete_record(id):
try:
con=sqlite3.connect("myimage.db")
cur=con.cursor()
cur.execute("delete from image where pid=?",[id])
con.commit()
flash("Record Deleted Successfully","success")
except:
flash("Record Deleted Failed", "danger")
finally:
return redirect(url_for("upload"))
con.close()
@app.route("/next_page")
def next_page():
con = sqlite3.connect("myimage.db")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select * from image")
data = cur.fetchall()
#data = [random.choice(data) for _ in range(4)]
data = random.sample(data, 4)
return render_template('next_page.html', data = data)
'''@app.route("/test")
def test():
return render_template('test.html')'''
if __name__ == '__main__':
app.run(debug=True)
My app.js file is as follows-
var pollMembers = document.querySelectorAll('.poll-member')
var members = [ res.Team ]
pollMembers.forEach((pollMember, index) => {
pollMember.addEventListener('click', (event) => {
handlePoll(members[index])
}, true)
})
var handlePoll = function(member) {
axios.post('http://localhost:5000/vote', {member}).then((r) => console.log(r))
}
const pusher = new Pusher('7967ce0fbdf40980ed5f', {
cluster: 'us2',
encrypted: true
});
var channel = pusher.subscribe('poll');
channel.bind('vote', function(data) {
for (i = 0; i < (data.length - 1); i++) {
var total = data[0].votes + data[1].votes + data[2].votes + data[3].votes
document.getElementById(data[i].Team).style.width = calculatePercentage(total, data[i].votes)
document.getElementById(data[i].Team).style.background = "#388e3c"
}
});
let calculatePercentage = function(total, amount) {
return (amount / total) * 100 + "%"
}