How to take HTML user input and query it via Python SQL?

2024/10/13 15:20:32

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 a store name, and for it to return relevant rows

def search():store_search = request.form.get("store")if request.method == "POST":if not store_search:return "please type in a store!"else:c = conn.cursor()c.execute("SELECT * FROM stores WHERE store_name= 'store_search'")rows = c.fetchall()for eachRow in rows:return rowelse:
return render_template("search.html")

HTML:

{% extends "main_page.html" %}
{% block title %}
Search
{% endblock %}{% block main %}<form action="{{ url_for('search') }}" method="post"><fieldset><div class="form-group"><input autocomplete="off" autofocus class="form-control" name="store" placeholder="store" type="text"/></div><div class="form-group"><button class="btn btn-default" type="submit">search</button></div><div class="page-header"><h1>{{ store }}</h1></div></fieldset></form>
{% endblock %}
Answer

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))})
https://en.xdnf.cn/q/118062.html

Related Q&A

Reading and taking specific file contents in a list in python

I have a file containing:name: Sam placing: 2 quote: Ill win.name: Jamie placing: 1 quote: Be the best.and I want to read the file through python and append specific contents into a list. I want my fir…

Scipy / ctypes build-config: How to load lib?

These docs have a nice example on how to compile some external C/C++ code and load this using ctypes. This works great with manual compilation (where im controlling the names of my library which later …

Webfaction Django 1.4.1: easy_thumbnails 3.0b – Couldnt get the thumbnail error

I use easy_thumbnails and it works fine on a development machine but in production I get errors like shown below, when I use {% thumbnail photo.image 300x170 %} templatetag. Though can directly browse …

acronym replacement with its value using python

i have dictionary like that i need to replace acronyms in text with its value in dictionary i use this code but it doesnt give me the appropriate result when i test the function using acronyms("we…

Grako - How to do error handling?

How do I do error handling with Grako?EBNF (MyGrammar.ebnf):pattern = { tag | function }* ; tag = tag:( "%" name:id "%" ); function = function:("$" name:id "…

How get the softlayer storage credendials?

Im trying to get the Username,password and host IQN of a authorized Softlayer Network Storage. I used this python script, but the shell returns []import SoftLayerAPI_USERNAME = xxxAPI_KEY = yyyystorage…

dopy.manager.DoError: Unable to authenticate you

Im trying to configure a Virtual Machine(with Vagrant and Ansible), that needs a file.py to the full correct configuration of this machine (according to the book that Im studying),Im was using the Digi…

subprocess.Popen: OSError: [Errno 2] No such file or directory only on Linux

This is not a duplicate of subprocess.Popen: OSError: [Errno 13] Permission denied only on Linux as that problem occurred due to wrong permissions. That has been fixed and this is an entirely different…

Windows Theano Keras - lazylinker_ext\mod.cpp: No such file or directory

I am installing Theano and Keras follwing the How do I install Keras and Theano in Anaconda Python on Windows?, which worked fine for me with an older release before. Now I have upgraded to the latest…

Python Threading: Making the thread function return from an external signal

Could anyone please point out whats wrong with this code. I am trying to return the thread through a variable flag, which I want to control in my main thread. test27.pyimport threading import timelock …