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><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script></head><body><inputtype='text'name='query'id='query'><buttontype='button'id='search'>Search</button><divid='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('/')defhome():
  return"<a href='/search'>Search</a>"@app.route('/search')defsearch():
   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>'ifnot 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?"