How to get MySQL database values in dropdown using python cgi? - python

I've created a webpage using Python cgi, now I want fill my HTML dropdown with database values. I don't know how get MySQL database values into dropdown.
#!/usr/bin/python
import MySQLdb
import cgi
import cgitb; cgitb.enable()
print "content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<meta charset="utf-8">'
print '<meta http-equiv="X-UA-Compatible" content="IE=edge">'
print '<meta name="viewport" content="width=device-width, initial-scale=1">'
print '<link rel="stylesheet" href="/powersupply/cssmenu/styles.css">'
print '<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>'
print '<script src="/powersupply/cssmenu/script.js"></script>'
print '<title>Power Supply Testing</title>'
print '<link rel="stylesheet" href="css/newstyle.css">'
print '</head>'
print '<body>'
print '<form name="myform" method="post" action="">'
print '<div>'
print '<fieldset class="fieldset">'
print '<legend>Power Supply Testing</legend>'
print '<table>'
print '<tr>'
print '<td>'
print '<label class="label">Serial Num Option:</label>'
print '</td>'
print '<td>'
print '<select class="textbox">'
print '<option value="serialno">Serial Num Auto Generate</option>'
print '<option value="barcode">Barcode Scanner Capture</option>'
print '</select>'
print '</td>'
print '<td>'
print '<label class="label">Serial Num:</label>'
print '</td>'
print '<td>'
print '<input class="textbox" type="text" name="serial" id="serial"/>'
print '</td>'
print '<td>'
print '<label class="label">PartNum:</label>'
print '</td>'
print '<td>'
print '<select class="textbox">'
print '<option value=""></option>'
print '</select>'
print '</td>'
print '</tr>'
print '<tr>'
print '<td>'
print '<label class="label">Revision No:</label>'
print '</td>'
print '<td>'
print '<select class="textbox">'
print '<option value=""></option>'
print '</select>'
print '</td>'
print '<td>'
print '<label class="label">Description:</label>'
print '</td>'
print '<td>'
print '<input class="textbox" type="text" name="description" id="description"/>'
print '</td>'
print '</tr>'
print '</table>'
print '<table>'
print '<tr>'
print '<td>'
print '<input class="clicktosave" type="submit" value="CLICK TO RECORD"/>'
print '</td>'
print '</tr>'
print '<tr>'
print '<td>'
print '<input class="cancelbutton" type="reset" name="cancel" value="CANCEL" id="cancel"/>'
print '</td>'
print '</tr>'
print '</table>'
print '</fieldset>'
print '</div>'
print '</form>'
print '</body>'
print '</html>'
I want to add MySQL database values in the dropdown. in between Python code PHP script is not working. Is there any way to get database values?

You are going to want to use something like this.
Here is an example of how to use this package:
import MySQLdb
def db_dropdown(): # Execute query
db = MySQLdb.connect(user='root', db='test', passwd='test', host='ip-address') # Your DB details here
cursor = db.cursor()
sql = 'SELECT SUM(regressnum) FROM testlog WHERE buildnumber = %s AND productid = 41))' \
% build_number # Parse in a variable into the query
cursor.execute(sql)
list_tested = cursor.fetchall() # Get query response and store in variable
list_tested = [i for sub in list_tested for i in sub] # Convert to list from tuple
return list_tested
def print_dropdown(data): # Print the dropdown
print '<div>'
print '<select>'
for i in data:
print '<option value="%s"selected>%s</option>' % (i, i)
print '</select>'
print '</div>'
Example usage:
print_dropdown(db_dropdown())
Obviously this can be expanded upon and can be made to query anytihng and produce anything.

Related

IndentationError expected an indented block for Network automication

The code is set run a command in my cisco device -- cache the output and query the outcome but if there is another line within the same outcome then to execute it.
peeringip = raw_input("Enter the customer's peering IP : ")
print
print
sitee = raw_input('Enter the Site(/col/ash/')
site = sitee.upper()
def cisco(routername,shrninc,showipint,showtunnel,shipprefix):
conn = SSH2()
conn.connect(routername)
conn.login(account1)
conn.execute('Terminal Length 0')
bgpstatements = shrninc + peeringip
print "Router Name: ",routername
conn.execute(bgpstatements)
showcomoutputbgp = conn.response
if 'neighbor' in showcomoutputbgp:
print "============"
print "-------------------"
print "============"
print "-------------------"
print
print "BGP configuration : ",conn.response
print
print "CHECKING PREFIX-LIST"
elif 'ROUTE' in showcomoutputbgp:
chkprefix = re.search("ROUTE",showcomoutputbgp)
prefix_name = chkprefix.group()
locate_prefix = shipprefix + prefix_name
conn.execute(locate_prefix)
print "PREFIX-LIST INFO : "
else:
print "No BGP neighbor"
No output for the Elif...
You need to indent this section because of the if statement. Also, instead of all the blank prints you can add \n to your previous prints. It makes it look neater and easier to read.
def cisco(routername,shrninc,showipint,showtunnel,shipprefix):
conn = SSH2()
conn.connect(routername)
conn.login(account1)
conn.execute('Terminal Length 0')
bgpstatements = shrninc + peeringip
print "Router Name: ",routername
conn.execute(bgpstatements)
showcomoutputbgp = conn.response
if 'neighbor' in showcomoutputbgp:
print "============"
print "-------------------"
print "============"
print "-------------------\n"
print "BGP configuration : ",conn.response + "\n"
print "CHECKING PREFIX-LIST"
elif 'prefix-list' in showcomoutputbgp:
chkprefix = re.search(r'(prefix-list)',showcomoutputbgp)
prefix_name = chkprefix.group()
locate_prefix = shipprefix + prefix_name
conn.execute(locate_prefix)
print "PREFIX-LIST INFO : ",conn.response + "\n"
else:
print "No BGP neighbor""
def cisco(routername,shrninc,showipint,showtunnel,shipprefix):
conn = SSH2()
conn.connect(routername)
conn.login(account1)
conn.execute('Terminal Length 0')
bgpstatements = shrninc + peeringip
print "Router Name: ",routername
conn.execute(bgpstatements)
showcomoutputbgp = conn.response
if 'neighbor' in showcomoutputbgp:
print "============"
print "-------------------"
print "============"
print "-------------------"
print
print "BGP configuration : ",conn.response
print
print "CHECKING PREFIX-LIST"
elif 'prefix-list' in showcomoutputbgp:
chkprefix = re.search(r'(prefix-list)',showcomoutputbgp)
prefix_name = chkprefix.group()
locate_prefix = shipprefix + prefix_name
conn.execute(locate_prefix)
print "PREFIX-LIST INFO : ",conn.response
print
else:
print "No BGP neighbor"

How exit from cgi?

I wrote a python-cgi script (raspberry) that shows a page in the browser with some data. I will enter in this page from an other pc (linux, mac, etc.) entering usual address (//localhost/cgi-bin/myscript.py) in the browser. The page will be shown in fullscreen mode. I would have a button on the page that, as pushed, the page will close and exit the browser. I tried with pygame button and with submit (post or get method) button but with no success (I'm not really expert!).
Anybody can help me?
Thanks
#!/usr/bin/python
import os.path, sys, datetime, time
import cgi, cgitb
import os
import RPi.GPIO as io
import pygame, random, pygame.font, pygame.event, pygame.draw, string
import common
pygame.init()
io.setmode(io.BCM)
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
ctime = datetime.datetime.now()
clock = ctime.strftime("%H:%M")
date = ctime.strftime("%A %d")
form = cgi.FieldStorage()
fileobj = open('/sys/bus/w1/devices/28-0000065fb5c1/w1_slave','r')
lines1 = fileobj.readlines()
fileobj.close()
Temp2 = int(5)
Temp= form.getvalue(Temp2)
print "Content-type: text/html\n\n"
def main():
print "<html>"
print "<head>"
print "<meta http-equiv='refresh' content='5' >"
print "</head>"
print "<body>"
print "<body bgcolor=""#000000"">"
fileobj = open('/sys/bus/w1/devices/28-0000065fb5c1/w1_slave','r')
lines1 = fileobj.readlines()
fileobj.close()
Temp2 = int(5)
if (lines1[0][-4])=='Y':
pos1=lines1[1].index('t=')
Temp2 = int(lines1[1][pos1+2:])/1000
Temp2=round(Temp2,1)
time.sleep(1)
print "<table style=""width:1920px"">"
print "<tr height=""60"">"
print "</tr>"
print "<tr height=""400"">"
print "<td width=""442px"" >"
print "</td>"
if Temp2 <= 32:
print "<td width=""345"" background=""//192.168.10.32/dashblue.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "<b>"
print Temp2
degree = chr(176)
print degree
print "</b>"
print "</p>"
print "</font>"
print "</td>"
elif Temp2 > 32 and Temp2 <= 37:
print "<td width=""345"" background=""//192.168.10.32/dashgreen.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "<b>"
print Temp2
degree = chr(176)
print degree
print "</b>"
print "</p>"
print "</font>"
print "</td>"
if Temp2 > 37:
print "<td width=""345"" background=""//192.168.10.32/dashred.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "<b>"
print Temp2
degree = chr(176)
print degree
print "</b>"
print "</p>"
print "</font>"
print "</td>"
file = open('/home/pi/Downloads/temperat.txt','r')
lines = file.readlines()
file.close()
Temp = float(lines[0][:4])
Temp=round(Temp,1)
if Temp <= 22:
print "<td width=""345"" background=""//192.168.10.32/dashblue.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "<b>"
print Temp
degree = chr(176)
print degree
print "</b>"
print "</p>"
print "</font>"
print "</td>"
elif Temp > 22 and Temp <= 26:
print "<td width=""345"" background=""//192.168.10.32/dashgreen.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "<b>"
print Temp
degree = chr(176)
print degree
print "</b>"
print "</p>"
print "</font>"
print "</td>"
if Temp > 27:
print "<td width=""345"" background=""//192.168.10.32/dashred.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "<b>"
print Temp
degree = chr(176)
print degree
print "</b>"
print "</p>"
print "</font>"
print "</td>"
Hum=int(lines[1])
print "<td width=""345"" background=""//192.168.10.32/dashblue.png"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print"<p align=""center"">"
print "<b>"
print Hum
degree = chr(37)
print degree
print "</b>"
print "</p>"
print "</td>"
print "<td width=""6%"" >"
print "</font>"
print "</td>"
print "</tr>"
print "<tr height=""80"">"
print "<td width=""6%"" >"
print "</td>"
print "<td width=""345"">"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "</p>"
print "<p align=""center"">"
print "Water Temperature"
print "</p>"
print "</font>"
print "</td>"
print "<td width=""345"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print "<p align=""center"">"
print "Bath Temperature"
print "</p>"
print "</font>"
print "</td>"
print "<td width=""345"" >"
print "<font size=""7"" color=""#00FFF"" face=""sans-serif"" >"
print"<p align=""center"">"
print "Bath Humidity"
print "</p>"
print "</font>"
print "</td>"
print "<td width=""442px"" >"
print "</td>"
print "</tr>"
print "</table>"
print "<font size=""10"" color=""#00FFF"" face=""sans-serif"" >"
print "<h1 align=""center"">now..%s&nbsp&nbsp&nbsp&nbsp%s</h1>" % (date,clock)
print "</font>"
print "</body>"
print "</html>"
for event in pygame.event.get():
if event.type == QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_F6):
pygame.quit()
sys.exit()
if (__name__=='__main__'):
main()
Your problem is not a Python problem, it's a JavaScript problem, and like #rob said, it's a duplicate of this question: stackoverflow.com/questions/2076299/...
And to summarize it for you; you'd need JavaScript to close the window, but as it happens JavaScript is sandboxed in a way that prevents it from closing a window that was not opened by the same script on the page, so if you open a tab or a window in your browser and navigate to a page, that page cannot kill itself nor can it kill the browser, it can only close and kill any windows it launches by JavaScript.
The only thing you can do is to navigate to a different page like executing window.location = 'A DIFFERENT URL' in JavaScript; you can even navigate to about:blank which shows a blank page on most browsers.

for and in and enumerate and if ...... AHHHHHHH

I have a school project that involves programming. I am transferring between batch and python because that is easiest for me.
This is my code written in python:
for i,x in enumerate(result):
if number in x:
print "Start of 1"
cursor.execute(insert1, (number))
cursor.execute(delete, (number))
f.close()
os.system("extracommands.bat 1")
print "Found Number"
else:
print "Start of 2"
cursor.execute(insert1, (number))
cursor.execute(insert2, (number))
cursor.execute(delete, (number))
f.close()
os.system("emailfine.py 1")
print "Finished 2"
My problem is that I can't find a string in a tuple. What happens is that when there is a result, it runs perfectly. But when there isn't a result, nothing happens.
How can I overcome this?
Thank you in advance.
Edit:
I was probably not specific enough when asking my question.
The result variable is in fact a MySQL execution result using the fetchall() command. The whole code of my program is:
import MySQLdb
import sys
import os
print "=========================="
print "Start Registered_Or_Not.py"
print "=========================="
os.chdir("C:/DisabledParkingSpacesImages/textfiles")
f = open("numberplate.txt", "r")
number = f.read()
print number
try:
db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = 'jordan',
db = 'disabledparking'
)
except Exception as e:
sys.exit("Can't access the database")
print "MySQL Connection OK"
cursor = db.cursor()
cursor.execute("SELECT registration FROM registered WHERE EXISTS (SELECT 1 FROM limbo WHERE limbo.registration = registered.registration)")
result = cursor.fetchall()
insert1 = "INSERT INTO log (registration, time, date) VALUES(%s, CURRENT_TIME, CURRENT_DATE);"
insert2 = "INSERT INTO not_registered (registration, time, date) VALUES(%s, CURRENT_TIME, CURRENT_DATE);"
delete = "DELETE FROM limbo WHERE registration=%s;"
print "-------------"
print "Result:"
print result
print "-------------"
TrueFalse = False
for i,x in enumerate(result):
if number in x:
print "Start of 1"
cursor.execute(insert1, (number))
cursor.execute(delete, (number))
f.close()
os.system("extracommands.bat 1")
print "Found Number"
TrueFalse = True
elif TrueFalse == False:
print "Start of 2"
cursor.execute(insert1, (number))
cursor.execute(insert2, (number))
cursor.execute(delete, (number))
f.close()
os.system("emailfine.py 1")
print "Finished 2"
db.commit()
OK, So I answered my own question.
Here is the problematic code:
for i,x in enumerate(result):
if number in x:
print "Start of 1"
cursor.execute(insert1, (number))
cursor.execute(delete, (number))
f.close()
os.system("extracommands.bat 1")
print "Found Number"
else:
print "Start of 2"
cursor.execute(insert1, (number))
cursor.execute(insert2, (number))
cursor.execute(delete, (number))
f.close()
os.system("emailfine.py 1")
print "Finished 2"
And here is the non problematic code:
for i,x in enumerate(result):
if number in x:
print "Start of 1"
cursor.execute(insert1, (number))
cursor.execute(delete, (number))
f.close()
os.system("extracommands.bat 1")
print "Found Number"
TrueFalse = True
if TrueFalse == False:
print "Start of 2"
cursor.execute(insert1, (number))
cursor.execute(insert2, (number))
cursor.execute(delete, (number))
f.close()
os.system("emailfine.py 1")
print "Finished 2"

How to use QUERYSTRING, Cookies, GET/POST methods in a python cgi script?

I am writing a Quiz app using python Script. My HTML file Contains 1 Question at a time Displayed along with its 4 options. Below there are 2 buttons for Questions to Navigate. "Previous" and "Next". once the option is chosen, user can click next button and the selected value should be stored somewhere for further calculation of score and next Question
should be displayed.
I am new to Cgi stuff. So far i am able to load Question 1. and i am stuck further.
Somebody please help
i am storing questions and options in a seperate file like this
question|optionA|optionB|optionC|optionD|answer
#!/usr/bin/python
import cgi, Cookie, os, cgitb, linecache
cgitb.enable()
cookie = Cookie.SimpleCookie()
attempt = 0
qc= 0
scr = 0
wrng = 0
total = 0
cur = 1
cookie["Attempted"] = attempt
cookie["Correct"] = qc
cookie["Score"] = scr
cookie["Wrong"] = wrng
cookie ["Count"] = total
cookie["Current"] = cur
file = "quest" # my question bank
data = linecache.getline(file,cur)
data = data.strip('\n')
data = data.split('|')
form = cgi.FieldStorage()
if form.getvalue('prev'):
if(cur > 1):
cur = int (cookie["Current"].value) - 1
cookie["Current"] = cur
print cookie
print "Content-type:text/html\r\n\r\n"
HTML CODE
print "<span id=\"disQ\">"
print data[0]
print "</span></br>"
print "<input type=\"radio\" name=\"qstn\" value=\"1\" /><span>" + data[1] + "</span></br>"
print "<input type=\"radio\" name=\"qstn\" value=\"2\" /><span>" + data[2] + "</span></br>"
print "<input type=\"radio\" name=\"qstn\" value=\"3\" /><span>" + data[3] + "</span></br>"
print "<input type=\"radio\" name=\"qstn\" value=\"4\" /><span>" + data[4] + "</span></br>"
print "<input id=\"prev\" name=\"prev\" type=\"submit\" value=\"PREV\" onclick=\"this.form.submit()\">"
print "<input id=\"next\" name=\"next\" type=\"submit\" value=\"NEXT\" onclick=\"this.form.submit()\">"
print "<h5>Total Questions : </h5><span class = \"data\" id=\"total\">"+ cookie["Count"].value + "</span>"
print "<h5>Attempted :</h5><span class = \"data\" id=\"attempt\">" + cookie["Attempted"].value + "</span>"
print "<h5>Correct :</h5><span class = \"data\" id=\"correct\">" + cookie["Correct"].value + "</span>"
print "<h5>Wrong :</h5><span class = \"data\" id=\"wrong\">" + cookie["Wrong"].value + "</span>"
print "<h5>Score :</h5><span class = \"data\" id=\"score\">" + cookie["Score"].value + "</span>"

Python form handling

Could anyone help me find the problem in my Python script? This script simply gets a request posted from an HTML form with a few radio buttons.
import cgi
from file import *
form = cgi.FieldStorage()
print "Content-type: text/html"
print
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">"""
print "<html>"
print "<head>"
print "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">"
print "<title></title>"
print "</head>"
print "<body>"
choice = form.getvalue('option')
f = File("onlineVotes.txt")
if choice is None:
print "<p class='error'>Please choose an option before voting.</p>"
print "<br><a href='onlinePoll.html' class='backVoteAgain'>Go back</a>"
else:
if f.exists() == False:
f.startWrite()
f.write(choice)
print choice
print "<div class='voteBar' style='width: 250px;'>"
print 1
print "</div>"
else:
f.startRead()
choice = f.read() + " " + choice
choiceList = choice.split()
filterList = []
for item in choiceList:
if item not in filterList:
filterList.append(item)
choiceDict = {}
for elem in filterList:
print "<br>" + elem
counts = choiceList.count(elem)
choiceDict['%s' % elem] = counts
maxValue = max(choiceDict.values())
barWidth = counts*250/maxValue
print "<div class='voteBar' style='width: %spx;'>" % str(barWidth)
print counts
print maxValue
print "</div>"
totalVotes = str(sum(choiceDict.values()))
print "<br>Total number of votes: " + totalVotes
f.startWrite()
f.write(choice)
f.close()
print "</body>"
print "</html>"
The problem with this is that when option1 gets 10 votes, option2 gets 5 votes and option3 gets 3 votes, the value of max(choiceDict.values()) is 10, which is good as expected. However, when option1 gets 10 votes, option2 gets 11 votes and option3 gets 5 votes, the max value for option1 stays at 10 while it is 11 for both option2 and option3.
Where did I do wrong?

Categories