Question

I have a simple "voting" webpage, where user is presented with a table with three columns. Each column will contain results of a search engine query, then user will choose which column has the better result and click a button.

Here is a sample: http://jsfiddle.net/rfeGa/

I need help with the following: 1. How do I keep track of the votes between the html page and python program? 2. I want to keep the list of queries in the python file, how do I pass that info over to the webpage?

Here is my html page:

<!DOCTYPE html>
<html>
    <head>
        <title>Search Engine Comparator!</title>
    </head>
    <body>      
        % queries = ("ccny", "bmcc", "qcc");
        % bingScore = googScore = yhooScore = 0;        
        % for q in queries:
        The query is: {{ q }}
        <br />
        And the scores are: Bing = {{ bingScore }}, Google = {{ googScore }}, Yahoo = {{ yhooScore }}.
        <hr>    
        <form action="/" method="post">
            <table border="1" width="100%">         
                <tr>
                    <th>
                        <input type="submit" name="engine1" value="Engine 1 is better!" />
                    </th>
                    <th>
                        <input type="submit" name="engine2" value="Engine 2 is better!" />
                    </th>
                    <th>
                        <input type="submit" name="engine3" value="Engine 3 is better!" />
                    </th>       
                </tr>
            </table>
        </form>
        % end
    </body>
</html>     

<script type="text/javascript">

</script>

Here is my python code:

from bottle import request, route, run, view
from mini_proj import *

@route('/', method=['GET', 'POST'])
@view('index.html')
def index():
    return dict(parts = request.forms.sentence.split(),
                show_form = request.method == 'GET');

run(host = 'localhost', port = 9988);
Was it helpful?

Solution

You can use jquery + mod_WSGI to let Python be the backend to a Javascript front end. You can push a result back to the Python script and let it modify a database for example. Here are some simplified portions of the solution. I left out a couple of details.

I'm not familiar with bottle, but I have used web.py in the past to help accomplish this.

I modified your jsfiddle to use the basic parts from the below jquery. Your javascript will pass back which button was clicked.

<script type="text/javascript">

jQuery(document).ready(function() {

    jQuery("input ").click(function() {

        // this captures passes back the value of the button that was clicked.
        var input_string = jQuery(this).val();
        alert ( "input: " + input_string );

        jQuery.ajax({
            type: "POST",
            url: "/myapp/",
            data: {button_choice: input_string},
        });
    });
});

</script>

And let your python script modify a database in the backend .

and here is using web.py , to grab inputs from jQuery import web import pyodbc

urls = ( '/', 'broker',)
render = web.template.render('/opt/local/apache2/wsgi-scripts/templates/')

application = web.application(urls, globals()).wsgifunc()

class broker:
    def GET(self):
        # here is where you will setup search engine queries, fetch the results 
        # and display them

        queries_to_execute = ...
        return str(queries_to_execute)
    def POST(self):
        # the POST will handle values passed back by jQuery AJAX

        input_data = web.input()

        try:
            print "input_data['button_choice'] : ", input_data['button_choice']
            button_chosen = input_data['button_choice']
        except KeyError:
            print 'bad Key'


        # update the database with the user input in the variable button_chosen

        driver = "{MySQL ODBC 5.1 Driver}"
        server = "localhost"
        database = "your_database" 
        table = "your_table"

        conn_str = 'DRIVER=%s;SERVER=%s;DATABASE=%s;UID=%s;PWD=%s' % ( driver, server, database, uid, pwd ) 

        cnxn = pyodbc.connect(conn_str)

        cursor = cnxn.cursor()

        # you need to put some thought into properly update your table to avoid race conditions
        update_string = "UPDATE your_table SET count='%s' WHERE search_engine='%s' "

        cursor.execute(update_string % (new_value ,which_search_engine)
        cnxn.commit()

Your python file calls called using mod_WSGI. Take a look at how to set up Apache + mod_WSGI + web.py backend like i have described in a previous answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top