2012-03-03 3 views
0

У меня есть простая «голосовая» веб-страница, где пользователю представлена ​​таблица с тремя столбцами. Каждый столбец будет содержать результаты запроса поисковой системы, затем пользователь выберет, какой столбец имеет лучший результат, и нажмите кнопку.как мне добавить партитуры для формы?

Вот пример: http://jsfiddle.net/rfeGa/

мне нужно помощь в следующем: 1. Как отслеживать голоса между страницей HTML и программой питона? 2. Я хочу сохранить список запросов в файле python, как передать эту информацию на веб-страницу?

Вот мой HTML-страница:

<!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> 

Вот мой питон код:

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); 
+0

@GregS отредактирован, но, как вы можете видеть, там не так много. Я программировал только на python около месяца. – iCodeLikeImDrunk

ответ

2

Вы можете использовать JQuery + mod_wsgi, чтобы Python быть бэкенд к переднему концу Javascript. Вы можете вернуть результат к скрипту Python и, например, модифицировать базу данных. Вот несколько упрощенных частей решения. Я оставил пару деталей.

Я не знаком с bottle, но в прошлом я использовал web.py, чтобы помочь в этом.

Я изменил ваш jsfiddle, чтобы использовать основные части из нижеследующего jquery. Ваш javascript вернет кнопку, нажав кнопку.

<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> 

И пусть ваш скрипт python изменяет базу данных в бэкэнд.

и здесь используется web.py, чтобы захватить входы из JQuery импорта веб импорта 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() 

Ваших питона вызовов файла с именем, используя mod_wsgi. Посмотрите, как настроить Apache + mod_WSGI + web.py, как я описал в ответе previous.

Смежные вопросы