article

Wednesday, June 30, 2021

Live Poll using Jquery ajax and Python Flask PosgreSQL

Live Poll using Jquery ajax and Python Flask PosgreSQL

CREATE TABLE tblprogramming (
id serial PRIMARY KEY,
title VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    tblprogramming(title)
VALUES
('Flask'),
('Laravel'),
('React.js'),
('Express'),
('Django');

CREATE TABLE tbl_poll (
id serial PRIMARY KEY,
web_framework VARCHAR ( 150 ) NOT NULL
);

INSERT INTO
    tbl_poll(web_framework)
VALUES
('Flask'),
('Flask'),
('Flask'),
('Express'),
('React.js'),
('Laravel'),
('Flask'),
('Flask'),
('Laravel'),
('Django'),
('Django'),
('Flask');


install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify, flash, redirect
import psycopg2 #pip install psycopg2 
import psycopg2.extras
   
app = Flask(__name__)
   
app.secret_key = "caircocoders-ednalan"
   
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
       
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST) 

@app.route('/')
def index():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM tblprogramming ORDER BY id ASC")
    webframework = cur.fetchall()  
    return render_template('index.html', webframework = webframework)
 
@app.route("/polldata",methods=["POST","GET"])
def polldata():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) 
    query = "SELECT * from tbl_poll"
    cur.execute(query)
    total_poll_row = int(cur.rowcount) 
    cur.execute("SELECT * FROM tblprogramming ORDER BY id ASC")
    framework = cur.fetchall()  
    frameworkArray = []
    for row in framework:
        get_title = row['title']
        cur.execute("SELECT * FROM tbl_poll WHERE web_framework = %s", [get_title])
        row_poll = cur.fetchone()  
        total_row = cur.rowcount
        #print(total_row)
        percentage_vote = round((total_row/total_poll_row)*100)
        print(percentage_vote)
        if percentage_vote >= 40:
            progress_bar_class = 'progress-bar-success'
        elif percentage_vote >= 25 and percentage_vote < 40:   
            progress_bar_class = 'progress-bar-info'  
        elif percentage_vote >= 10 and percentage_vote < 25:
            progress_bar_class = 'progress-bar-warning'
        else:
            progress_bar_class = 'progress-bar-danger'
  
        frameworkObj = {
                'id': row['id'],
                'name': row['title'],
                'percentage_vote': percentage_vote,
                'progress_bar_class': progress_bar_class}
        frameworkArray.append(frameworkObj)
    return jsonify({'htmlresponse': render_template('response.html', frameworklist=frameworkArray)})
 
@app.route("/insert",methods=["POST","GET"])
def insert():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        poll_option = request.form['poll_option']
        print(poll_option)      
        cur.execute("INSERT INTO tbl_poll (web_framework) VALUES (%s)",[poll_option])
        conn.commit()       
        cur.close()
        msg = 'success' 
    return jsonify(msg)
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>  
<head>  
<title>Live Poll using Jquery ajax and Python Flask PosgreSQL</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
</head>  
    <body>  
        <div class="container">  
            <br />  <br />
            <h2 align="center">Live Poll using Jquery ajax and Python Flask PosgreSQL </h2><br />
            <div class="row">
                <div class="col-md-6">
                    <form method="post" id="poll_form">
                        <h3>Which is Best Web Development Frameworks</h3>
                        <br />
                        {% for row in webframework %}
                        <div class="radio">
                            <label><h4><input type="radio" name="poll_option" class="poll_option" value="{{row.title}}" /> {{row.title}}</h4></label>
                        </div>
                        {% endfor %}
                        <br />
                        <input type="submit" name="poll_button" id="poll_button" class="btn btn-primary" />
                    </form>
                    <br />
                </div>
                <div class="col-md-6">
                    <br />
                    <br />
                    <h4>Live Poll Result</h4><br />
                    <div id="poll_result"></div>
                </div>
            </div>
        </div>
<script>  
$(document).ready(function(){
    fetch_poll_data();
    function fetch_poll_data()
    { 
        var fetchall = 'all';
        var dataString = 'fetchall='+ fetchall;
        $.ajax({
            url:"/polldata",
            method:"POST",
            data: dataString,
            success:function(data)
            {
                $('#poll_result').html(data); 
                $("#poll_result").append(data.htmlresponse);
            }
        });
    }
    $('#poll_form').on('submit', function(event){
        event.preventDefault();
        var poll_option = '';
        $('.poll_option').each(function(){
            if($(this).prop("checked"))
            {
                poll_option = $(this).val();
            }
        });
        if(poll_option != '')
        {
            $('#poll_button').attr('disabled', 'disabled');
            var form_data = $(this).serialize();
            $.ajax({
                url:"/insert",
                method:"POST",
                data:form_data,
                success:function()
                {
                    $('#poll_form')[0].reset();
                    $('#poll_button').attr('disabled', false);
                    fetch_poll_data();
                    alert("Poll Submitted Successfully");
                }
            });
        }
        else
        {
            alert("Please Select Option");
        }
    });
});  
</script>
</body>  
</html>
templates/response.html
//templates/response.html
{% for row in frameworklist %}  
<div class="row">
    <div class="col-md-2" align="right">
        <label>{{row.name}}</label>
    </div>
    <div class="col-md-10">
        <div class="progress">
            <div class="progress-bar {{row.progress_bar_class}}" role="progressbar" aria-valuenow="{{row.percentage_vote}}" aria-valuemin="0" aria-valuemax="100" style="width:{{row.percentage_vote}}%">
                {{row.percentage_vote}} % programmer like <b>{{row.name}}</b> Web Framework
            </div>
        </div>
    </div>
</div>
{% endfor %} 

Related Post