Skip to content Skip to sidebar Skip to footer

How To Take HTML User Input And Query It Via Python & SQL?

Is there a way to take user input from HTML, and use python to run the input through to a SQL database? Does the input need to be parsed? I want the the user to be able to type in

Solution 1:

You can create a simple app in flask that receives user input and scans the items returned from a SELECT query in sqlite3:

First, create the user form. You can use ajax with jquery for a dynamic response:

In search.html:

<html>
 <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 </head>
 <body> 
    <input type='text' name='query' id='query'>
    <button type='button' id='search'>Search</button>
    <div id='results'></div>
 </body>
  <script> 
    $(document).ready(function() {
     $('#search').click(function() {
       var text = $('#query').val();
        $.ajax({
        url: "/search",
        type: "get",
        data: {query: text},
        success: function(response) {
        $("#results").html(response.html);
       },
       error: function(xhr) {
        //Do Something to handle error
       }
     });
   });
  });
  </script>
</html>

In app.py

import flask
import sqlite3
app = flask.Flask(__name__)

@app.route('/')
def home():
  return "<a href='/search'>Search</a>"

@app.route('/search')
def search():
   term = flask.request.args.get('query')
   possibilities = [i for [i] in sqlite3.connect('filename.db').cursor().execute("SELECT * FROM stores") if term.lower() in i.lower()]
   return flask.jsonify({'html':'<p>No results found</p>' if not possibilities else '<ul>\n{}</ul>'.format('\n'.join('<li>{}</li>'.format(i) for i in possibilities))})

Post a Comment for "How To Take HTML User Input And Query It Via Python & SQL?"