I'm a novice Python and Javascript programmer and am currently working on creating an events manager app using Flask and MySQL.
The one page website should allow users to:
Add and view events.
Sort events by date or by category
I can't seem to insert data into my local MySQL database. Each time I open the MySQL workbench to check, the table remains empty.
My questions are:
How do I insert the data from the input tags into MySQL using Flask?
What is the best method to check MySQL if the insertion was successful?
How do I get data from MySQL into the HTML table using Flask on app startup?
The HTML:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<link rel = 'stylesheet' href = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
<title>Events and Opportunities</title>
</head>
<body>
<div class = 'container'>
<h1>Events and Opportunities</h1>
<table class="table">
<thead>
<tr id = 'tableHeader'>
<th>Date</th>
<th>Category</th>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<form action = '/' method = 'post'>
<tr id = 'tableInput'>
<td><input type = 'date' name = 'inputDate' id = 'inputDate'></td>
<td><input type = 'text' name = 'inputCategory' id = 'inputCategory' maxlength = '20'></td>
<td><input type = 'text' name = 'inputTitle' id = 'inputTitle' maxlength = '100'></td>
<td><input type = 'text' name = 'inputDescription' id = 'inputDescription' maxlength = '500'></td>
</tr>
</form>
</tbody>
</table>
<button type = 'button' id = 'addButton' class="btn btn-default">Add</button>
</div>
<script src = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src = 'static/app.js'></script>
</body>
</html>
The Javascript:
$('#addButton').on('click', () => {
if ($('#inputDate').val() === '' || $('#inputCategory') === '' || $('#inputTitle') === '' || $('#inputDescription') === ''){
alert('Please fill in the form.');
}
else{
const valDate = $('<th></th>').text($('#inputDate').val());
const valCategory = $('<th></th>').text($('#inputCategory').val());
const valTitle = $('<th></th>').text($('#inputTitle').val());
const valDescription = $('<th></th>').text($('#inputDescription').val());
const newRow = $('<tr></tr>').append(valDate, valCategory, valTitle, valDescription);
$('#tableInput').before(newRow);
$('#inputDate').val('');
$('#inputCategory').val('');
$('#inputTitle').val('');
$('#inputDescription').val('');
}
})
The Flask code:
from flask import Flask, render_template, request
import mysql.connector
app = Flask(__name__)
cnx = mysql.connector.connect(user='root', password='yunani', host='127.0.0.1', database='test')
cursor = cnx.cursor()
#app.route('/', methods = ['GET', 'POST'])
def index():
return render_template('index.html')
if request.method == 'POST':
date = request.form['inputDate']
category = request.form['inputCategory']
title = request.form['inputTitle']
description = request.form['inputDescription']
cursor.execute('INSERT INTO data (Date, Category, Title, Description) VALUES ({}, {}, {}, {})'.format(date, category, title, description))
cnx.commit()
if __name__ == '__main__':
app.run(debug = True)
The MySQL schema:link to image
Try changing your handler to
def index():
if request.method == 'POST':
date = request.form['inputDate']
category = request.form['inputCategory']
title = request.form['inputTitle']
description = request.form['inputDescription']
cursor.execute('INSERT INTO data (Date, Category, Title, Description) VALUES ({}, {}, {}, {})'.format(date, category, title, description))
cnx.commit()
return render_template('index.html') # don't do this at the top
You are currently returning before checking the call type or talking to the database.
Related
I am trying to build small web application fetchehing data from MySQL database with help of ajax date filter and applying dates and rendering table and chart in frontend I can able to get Table with my script not able to get chart how to do changes for getting chart and table as well
this is main.py file
from flask import Flask, render_template, request, jsonify, flash, redirect
from flask_mysqldb import MySQL, MySQLdb # pip install flask-mysqldb https://github.com/alexferl/flask-mysqldb
app = Flask(__name__)
app.secret_key = "caircocoders-ednalan"
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'xxxx'
app.config['MYSQL_DB'] = "battery_voltage"
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
#app.route('/')
def index():
cursor= mysql.connection.cursor()
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT * FROM voltage ORDER BY date desc")
orders = cur.fetchall()
return render_template('index.html', orders=orders)
#app.route("/range", methods=["POST", "GET"])
def range():
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
if request.method == 'POST':
From = request.form['From']
to = request.form['to']
print(From)
print(to)
query = "SELECT * FROM voltage WHERE date BETWEEN '{}' AND '{}'".format(From, to)
cur.execute(query)
ordersrange = cur.fetchall()
return jsonify({'htmlresponse': render_template('response.html', ordersrange=ordersrange)})
if __name__ == "__main__":
app.run(debug=True,port="2021")
index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Python Flask Date Range Search with jQuery Ajax DatePicker MySQL Database</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css"/>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<br/>
<div class="container">
<h2 align="left">OPSPOD Battery Voltage</h2>
<br/>
<br/>
<div class="col-md-2">
<input type="text" name="From" id="From" class="form-control" placeholder="From Date"/>
</div>
<div class="col-md-2">
<input type="text" name="to" id="to" class="form-control" placeholder="To Date"/>
</div>
<div class="col-md-8">
<input type="button" name="range" id="range" value="Range" class="btn btn-success"/>
</div>
<div class="clearfix"></div>
<br/>
<div id="purchase_order">
<table class="table table-bordered" style="width:40%" align="left" >
<tr>
<th width="5%">Date</th>
<th width="4%">Time</th>
<th width="4%">voltage</th>
<th width="4%">ignition</th>
</tr>
{% for row in orders %}
<tr>
<td>{{row.date}}</td>
<td>{{row.time}}</td>
<td>{{row.voltage}}</td>
<td>{{row.ignition}}</td>
</tr>
{% endfor %}
</table>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<!-- Script -->
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'dd-mm-yy'
});
$(function(){
$("#From").datepicker();
$("#to").datepicker();
});
$('#range').click(function(){
var From = $('#From').val();
var to = $('#to').val();
if(From != '' && to != '')
{
$.ajax({
url:"/range",
method:"POST",
data:{From:From, to:to},
success:function(data)
{
$('#purchase_order').html(data);
$('#purchase_order').append(data.htmlresponse);
}
});
}
else
{
alert("Please Select the Date");
}
});
});
</script>
</body>
</html>
response.html
<table class="table table-bordered" style="width:40%" align="left" >
<tr>
<th width="5%">Date</th>
<th width="4%">Time</th>
<th width="4%">voltage</th>
<th width="4%">ignition</th>
</tr>
{% for row in ordersrange %}
<tr>
<td>{{row.date}}</td>
<td>{{row.time}}</td>
<td>{{row.voltage}}</td>
<td>{{row.ignition}}</td>
</tr>
{% endfor %}
</table>
This is the link for the data which I used in MYSQL DB.
With the code above I am able to get the output like this table below but I am trying for graph as well with same date filtering with X-axis time and Y-axis voltage
Let's start by addressing your database issues. Storing dates and times as strings is a bad idea as they use more space and cannot be handled as efficiently as native DATE / TIME types. A date as string '01-12-2022' stored in a VARCHAR uses 11 Bytes, whereas if you convert it to DATE it is only 3 Bytes. Similarly for your time data - 8 Bytes as VARCHAR or 3 Bytes as TIME. Even better would be to combine the two together as DATETIME requiring only 5 Bytes, but I shall leave that for you to ponder.
-- Update dates from dd-mm-yyyy (note 4 digit year) to yyyy-mm-dd
UPDATE `voltage` SET `date` = STR_TO_DATE(`date`, '%d-%m-%Y');
-- If your existing dates have 2 digit year then use
UPDATE `voltage` SET `date` = STR_TO_DATE(`date`, '%d-%m-%y');
-- update the column types
ALTER TABLE `voltage`
MODIFY COLUMN `date` DATE NOT NULL,
MODIFY COLUMN `time` TIME NOT NULL;
You should also make sure you have a composite index on (date, time).
To avoid this answer getting too long, I am not going to include the full content of the index.html template file but I have made the following changes -
<div id="purchase_order"> to <div id="voltages">
Added <div id="chart"></div> before <div id="voltages">
Added <thead> around the header row and tbody around the rest of the table rows
Added <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> after the 2 jQuery scripts
Renamed From as from in various places
Then the inline script -
<script>
const chartLayout = {
hovermode: 'closest',
xaxis: {
type: 'date',
dtick: 10800000,
hoverformat: '%H:%M:%S',
tickformat: '%H:00\n%d %b',
rangebreaks: [{ pattern: 'hour' }]
}
};
Plotly.react('chart', [{ x: [/* leaving these for you to figure out */], y: [], line: { simplify: false } }], chartLayout);
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from").datepicker();
$("#to").datepicker();
});
$('#range').click(function(){
var from = $('#from').val();
var to = $('#to').val();
if(from != '' && to != '')
{
$.ajax({
url:"/range",
method:"GET",
data:{from:from, to:to},
success:function(data)
{
let x = [], y = [], rows = '';
for (const row of data) {
x[x.length] = `${row.date} ${row.time}`;
y[y.length] = row.voltage;
rows += `<tr><td>${row.date}</td><td>${row.time}</td><td>${row.voltage}</td><td>${row.ignition}</td></tr>`;
}
// update table content
$('#voltages > table > tbody').html(rows);
// update chart
Plotly.react('chart', [{ x: x, y: y, line: { simplify: false } }], chartLayout);
}
});
}
else
{
alert("Please Select the Date");
}
});
});
</script>
And this is the modified /range route -
#app.route('/range')
def range():
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
fromDate = request.args.get('from')
toDate = request.args.get('to')
query = """
SELECT CAST(`date` AS CHAR) AS `date`, CAST(`time` AS CHAR) AS `time`, `voltage`, `ignition`
FROM voltage
WHERE date BETWEEN '{}' AND '{}'
ORDER BY date, time
""".format(fromDate, toDate)
cur.execute(query)
voltages = cur.fetchall()
return jsonify(voltages)
The date and time have been cast to CHARs in the SELECT as json.dumps() (used by jsonify) does not like handling them as their native types. You should switch to using parameterized prepared statements to mitigate the current SQLi vulnerabilities.
I am trying to use an ajax call to update an HTML table every 60 seconds on a flask app.
I am very new to flask and jquery, and followed this similar stackoverflow question:
Python Flask Refresh table every 60 seconds
However my table isn't displaying any data.
Currently my app.py file is setup as below:
import MySQLdb
import sshtunnel
from datetime import date
import json
app = Flask(__name__)
#app.route("/")
def home():
return render_template("nfl_template.html")
#app.route("/nfl")
def nfl():
return render_template("nfl_template.html")
#app.route("/nfl_data")
def nfl_data():
sshtunnel.SSH_TIMEOUT = 10
sshtunnel.TUNNEL_TIMEOUT = 10
data = ((),)
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='USER', ssh_password='***',
remote_bind_address=('USER.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = MySQLdb.connect(
user='USER',
passwd='***',
host='127.0.0.1', port=tunnel.local_bind_port,
db='USER$liveSports',
)
cursor = connection.cursor()
query = ("""
SELECT * FROM nfl_data WHERE DATE(nfl_data.date)='{}'
""".format(str(date.today())))
cursor.execute(query)
data = cursor.fetchall()
return json.dumps(data)
And my nfl_template.html:
<!doctype html>
<html>
<body>
<script>
setInterval(function() {
$.ajax({
type: "GET",
url: "/nfl_data",
}) .done(function( data ) {
console.log(data);
var tableHtml = '';
for (row in data) {
tableHtml += '<tr>';
for (d in row) {
tableHtml += '<td>' + d + '</td>';
}
tableHtml += '</tr>';
}
$("#table-box").html(tableHtml)
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
});
}, 1000 * 60);
</script>
<table border="2" cellpadding="4" cellspacing="5" id="table-box">
<th>Game Date</th>
<th>Game Time</th>
<th>Team 1</th>
<th>Team 2</th>
<th>Team 1 Score</th>
<th>Team 2 Score</th>
<th>Team 1 Odds</th>
<th>Team 2 Odds</th>
{% for row in data %}
<tr>
{% for d in row[:-2] %}
<td>{{ d }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</body>
</html>
When I run the app, I get a page showing just the table headers but no data.
I know that the SQL Query is correct and is returning data as I tested it separately, but using the ajax request I'm not getting any data to display.
If I run the SQL query inside the nfl route function and pass the data as an argument to the render_template the data displays, but it is not updating the table every 60 seconds.
If that is literally your entire template, then the problem is that you haven't imported jQuery, so the "$" function doesn't exist. You need to add:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
I'm very new to this and I ran into a TypeError. I'm trying to simulate a basic web page with flask. I've managed to send the HTML request from a HTML text box to my program. I'm trying to display the response in a table on another page.
This here is my input page:
<!DOCTYPE html>
<html>
<body>
<form action = "/Attendance" method = "POST">
<p>Enter Employee Code:</p>
<p><input type = "text" name = "employee_code" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
The input goes into this program:
import pyodbc
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/')
def attendance_fetch():
return render_template('Attendance_fetch.html')
#app.route('/Attendance', methods=['GET', 'POST'])
def database_file():
if request.method == 'POST':
req = request.form['employee_code']
conn = pyodbc.connect(
r'Driver={Microsoft Access Driver (*.mdb,
*.accdb)};DBQ=E:\xampp\htdocs\S10\SmartOffice.mdb;')
cursor = conn.cursor()
cursor.execute('select * from Employees where EmployeeCode =?', req)
for i in cursor.fetchall():
employee_id = str(i[0])
cursor.execute('select * from AttendanceLogs where EmployeeId=?', employee_id)
columns = [column[0] for column in cursor.description]
results = [columns] + [row for row in cursor.fetchall()]
for result in results:
return result
return render_template('Database_file.html', data=result)
if __name__ == '__main__':
app.run(debug=True)
My desire is for the output to go into here display as a table:
<!DOCTYPE html>
<html>
<head>
<title>Attendance Table</title>
</head>
<body>
<table border = 1>
{% for key, value in data() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>
But I'm getting the error:
" {rv.class.name}.".format(rv=rv)
TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list.
As per my understanding to your question. You are getting some ID in first Attendance_fetch.html page and then getting details from database and want to display that information in table format in Database_file.html page.
Your /Attendance Logic might be like below where you are sending table headers and values in two different lists.
#app.route('/Attendance', methods=['GET', 'POST'])
def database_file():
if request.method == 'POST':
# DB Logic
headers = ["Name", "Emp code"]
values = ["Vikas Saini", "100"]
return render_template('Database_file.html', headers=headers, values=values)
Then In Database_file.html, you can display your table using below like code.
<!DOCTYPE html>
<html>
<head>
<title>Attendance Table</title>
</head>
<body>
<table border = 1>
<tr>
{% for header in headers %}
<th> {{ header }} </th>
{% endfor %}
</tr>
<tr>
{% for value in values %}
<td> {{ value }} </td>
{% endfor %}
</tr>
</table>
</body>
</html>
You return wrong response, should be object Response.
just remove line:
First
columns = [column[0] for column in cursor.description]
results = [columns] + [row for row in cursor.fetchall()]
for result in results:
return result <-- !!!!!REMOVE THIS LINE!!!!!
return render_template('Database_file.html', data=result)
Second
It's because you trying to call list object with data() Just remove brackets from data. Instead data() write data
{% for key, value in data %}
I'm building a Flask app that includes a table where users can change a cell and have those changes 'applied' e.g. updated in the database.
Pictures bellow
I'm having issues getting flask to retrieve this data that has been submitted via form.
The number of rows are dynamic and dependent on the number of Id's in a list.
Here is my html -- sorry for the clunkiness, I am still learning.
<tbody>
<form method="post" name="productCost">
{% for n in range(name_list | length) %}
<tr>
<th scope="row" >{{name_list[n]}}</th>
<td>{{ID_list[n]}}</td>
<td id="cost{{n}}">${{cost_list[n]}}</td>
<td>---</td>
<td id="changes{{n}}"><button onclick="costChanges{{n}}()">Edit</button></td>
</tr>
<script>
function costChanges{{n}}() {
document.getElementById("cost{{n}}").innerHTML = "<input placeholder='{{cost_list[n]}}' name={{ID_list[n]}}>";
document.getElementById("changes{{n}}").innerHTML = "<button onclick='applyChanges{{n}}()' type='submit'>Apply</button><button onclick='cancelChanges{{n}}()'>Cancel</button>";
}
function applyChanges{{n}}() {
docuemnt.getElementById("cost{{n}}").innerHTML = document.forms["productCost"]["{{ID_list[n]}}"]
}
function cancelChanges{{n}}() {
document.getElementById("cost{{n}}").innerHTML = "{{cost_list[n]}}";
document.getElementById("changes{{n}}").innerHTML = "<button onclick='costChanges{{n}}()'>Edit</button>";
}
</script>
{%endfor%}
</form>
</tbody>
Here is my python/flask code:
app.route('/expenses', methods=['GET', 'POST'])
def expenses():
if 'email' not in session:
return redirect(url_for('login_now'))
list_of_product_dicts = get_name_id()
name_list = []
asin_list =[]
cost_list=[]
for p in list_of_product_dicts:
name_list.append(p['name'])
id_list.append(p['id'])
cost = get_landing_cost(p['id'])
cost_list.append(cost)
if request.method == 'POST':
print(request.form['name'])
return flask.render_template('expenses.html', name_list = name_list, id_list=id_list,
cost_list=cost_list)
I need python to recognize the change that has been made and store it in a variable. This is for the purpose of updating it in a database-- but I do not need assistance with the database code. I only need help getting python to grab the cell that has been changed and recognize what row it was in.
It is a bit simpler to use jquery with ajax. The latter enables you to dynamically update the table by communicating with a backend script to update your database.
First, create the HTML script (the code below creates a different table layout for this example, however, you can substitute your own, based on the one below). The jquery cleanly handles the Apply, Cancel, and Edit button functionalities, and communicates with the backend via ajax:
tables.html:
<html>
<body>
<table>
<tr>
<th>ID</th>
<th>Cost</th>
<th>Effective Date</th>
<th>Make Changes</th>
</tr>
{%for row in data%}
<tr>
<td>{{row.id}}</td>
<td class='cost{{row.rowid}}'>{{row.price}}</td>
<td>{{row.date}}</td>
<td>
<div id='options{{row.rowid}}'>
<button id='mutate{{row.rowid}}'>Edit</button>
</div>
<td>
</tr>
{%endfor%}
</table>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div[id^='options']").on('click', 'button', function(){
var the_id = this.id.match('\\d+');
var the_type = this.id.match('[a-zA-Z]+');
if (the_type == "mutate"){
$('#options'+the_id).html('<button id="cancel'+the_id+'">Cancel</button>\n<button id="apply'+the_id+'">Apply</button>');
var current_cost = $('.cost'+the_id).text();
$('.cost'+the_id).html('\n<input type="text" class="newval'+the_id+'" value="'+current_cost+'">')
}
else if (the_type == 'cancel'){
$('#options'+the_id).html('<button id="mutate'+the_id+'">Edit</button>');
}
else{
var value = $(".newval"+the_id).val();
$.ajax({
url: "/update_cell",
type: "get",
data: {newval: value, rowid:the_id},
success: function(response) {
$('.cost'+the_id).html(value);
$('#options'+the_id).html('<button id="mutate'+the_id+'">Edit</button>');
},
error: function(xhr) {
//Do Something to handle error
}
});
}
});
});
</script>
</html>
Then, create the app and routes:
import flask, sqlite3, collections
app = flask.Flask(__name__)
#app.route('/', methods=['GET'])
def home():
dummy_data = [['hvVlNnAW', '$6.00', '--'], ['UqBzqLho', '$10.00', '--'], ['tuEdqldI', '$3.00', '--'], ['MIHLFWDS', '$1.00', '--'], ['rUnjpHiJ', '$8.00', '--'], ['lHVHxgZF', '$1.00', '--'], ['nFfaHkHj', '$3.00', '--'], ['rRWqXqVh', '$8.00', '--'], ['rdzCRozr', '$4.00', '--'], ['MGojGbtW', '$9.00', '--']]
#substitute dummy_data with a database query
product = collections.namedtuple('product', ['id', 'price', 'date', 'rowid'])
return flask.render_template('tables.html', data = [product(*a, i) for i, a in enumerate(dummy_data, 1)])
#app.route('/update_cell')
def update_row():
new_val = flask.request.args.get('newval')
prod_id = int(flask.request.args.get('rowid[]'))
#commit new_val to database
return flask.jsonify({'success':True})
Now, in '/update_cell', you have the new price value, and the product row id, which tells you which sqlite row's price you are to update. Note that in home, the row id, which is garnered by enumerate is vital to the application as it enables the jquery to know what table and sqlite row to update.
Demo:
I want to display each row from a database in a <td> in the following index.html page:
$def with(items)
<h1></h1>
<br/>
<br>
<table border="1">
<tr>
<th>Name</th>
<th>address</th>
<th>number</th>
</tr>
<tr>
<td>//want name here</td>
<td>//address here</td>
<td>//number here</td>
</tr>
</table>
app.py code:
import web
import MySQLdb
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class Index(object):
def GET(self):
return render.hello_form()
def POST(self):
form = web.input(name="a", newname="s", number="d")
conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb")
x = conn.cursor()
x.execute("SELECT * FROM details WHERE name = '%s'" % (form.name))
conn.commit()
items = x.fetchall()
for row in items:
conn.rollback()
conn.close()
return render.index(items)
if __name__ == "__main__":
app.run()
items (results fetched) will be an array of tuples. Return the array as it is as you want to display whole data on the html and HTML is only rendered once.
app.py code
import web
import MySQLdb
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class Index(object):
def GET(self):
return render.hello_form()
def POST(self):
form = web.input(name="a", newname="s", number="d")
conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb")
x = conn.cursor()
x.execute("SELECT * FROM details WHERE name = '%s'" % (form.name))
items = x.fetchall()
conn.close()
return render.index(items) // return the array of results as a whole
if __name__ == "__main__":
app.run()
On index.html
$def with(items)
<h1></h1>
<br/>
<br>
<table border="1">
<tr>
<th>Name</th>
<th>address</th>
<th>number</th>
</tr>
$for row in items:
<tr>
<td>$row[0]</td>
<td>$row[1]</td>
<td>$row[2]</td>
</tr>
</table>
Iterate over the items and display them