How to print value from db in python CGI - python

I am beginner and trying constantly to print value on web page through cgi-bin but i dont know what i am doing wrong. I gone through different tutorials like:
http://www.inmotionhosting.com/support/website/python/how-to-use-python-to-connect-to-a-database
http://ianhowson.com/a-quick-guide-to-using-mysql-in-python.html
http://www.tutorialspoint.com/python/python_database_access.htm
and some threads as well like: Returning Output of Python CGI MySQL Script because i think i am doing wrong somewhere but fail to print.
here is my code and it only prints "hello":
#!C:\Python27\python.exe
import cgi
import cgitb
print "Content-type: text/html\n"
print """
<html>
<head>
<p> hello</p>
</head>
"""
import MySQLdb
db = MySQLdb.connect(host="127.0.0.1",port=3306, user="root", passwd="",db="project")
cursor = db.cursor()
cursor2 = db.cursor()
# execute SQL select statement
#sql = "SELECT stid,firstname FROM student WERE stid IN(SELECT stid FROM stobt WHERE stid=%s" % (0)
sql2 = "SELECT stid FROM student WHERE firstname = '%s'" % ('User')
# Execute the SQL command
cursor2.execute(sql2)
# Fetch all the rows in a list of lists.
result2 = cursor2.fetchall()
#print result2
row2 = result2[0]
#print 'r1',row[1]
#print 'r2',row2[0]
sql = "SELECT * FROM stobt WHERE stid = '%d'" % (row2)
cursor.execute(sql)
results = cursor.fetchall()
row = results[1]
tc = 56
for row in results:
if row2[0] == row[1]:
idd = row[0]
stid = row[1]
obtained = row[2]
subject = row[3]
# Now print fetched result
print( "<h1>id=%s,stid=%s,obtained=%f,subject=%s</h1>" %(idd, stid, obtained, subject ))
print """
<body>
<p> idd</p>
</body>
</html>
"""
# if obtained <= 50:
# if tc >= 50:
# print tc
db.close()
Any idea?

Related

How can i run all my code in one function

My python code doesnt work. I get an output for only success mysql connection.
I want to print group id, hostname and other variables. The only output i get is
('Connected to MySQL Server version ', u'5.7.36-0ubuntu0.18.04.1')
("You're connected to database: ")
I cannot print group id or anything else. Im a newbie in python :(
import os
import mysql.connector
import json
execfile("/home/manager/test/mysqlconnector.py")
active_ip = ""
hostname = ""
group_id = 0
def my_funciton():
query = "select value_oid from snmp_trap where name_oid = '1.3.6.1.4.1.14823.2.3.3.1.200.1.17.0'"
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
mac = cursor.fetchone()
mac_string = mac.values()
mac_str = json.dumps(mac_string)
mac_ = mac_str.replace(':','')
mac_ = mac_.replace('"','')
mac_ = mac_.replace(']','')
mac_ = mac_.replace('[','')
return mac_
active_mac = my_function()
query = "select epp_active_ip, epp_hostname, epp_group_id from epp_inventory where epp_active_mac = + 'active_mac.upper()'"
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
rows = cursor.fetchall()
#active_ip = ""
#hostname = ""
#group_id = 0
for row in rows:
active_ip = row["epp_active_ip"]
hostname = row["epp_hostname"]
group_id = row["epp_group_id"]
print(group_id)
query = "select wmic_id from group_wmic where group_id = " + str(group_id)
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
wmic_ids = cursor.fetchall()
for row in wmic_ids:
query = "select command_line from wmic_commands where id = " + row["wmic_id"]
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
command_line = cursor.fetchone()
os.system(command_line)
os.system("ls -al")
#os.system(command)
my_funciton()
Apart from naming and indentation issues, which you should really fix, because it will make your code a nightmare to maintain - the issue is quite simple:
Consider:
def some_function():
print('this prints')
return
print('this does not')
Your code has the exact same problem. In your function my_funciton, you have the following line:
return mac_
Nothing after that will ever execute. You need to put the return statement in the position of the function's code where you expect it to actually return. You cannot put it just anywhere and expect the function to execute the rest of the code.

Loop Through an Table in SQL and Update a row every time

and having lots of trouble trying to figure out how I can update several rows in a SQLite data base.
Efectively I am getting an location on a Database I gathered, and running through Google maps to get the Latitude and Longitude. In general its working, but the loop fails!
It does it once, gets the first line that meet criteria and finish, and I can´t figure it out why it´s not keep going!! Can anyone help? The script below:
# coding=utf-8
import urllib
import sqlite3
import json
conn = sqlite3.connect('ArchDailyProjects.sqlite')
cur = conn.cursor()
#Google Prep
ServiceUrl="https://maps.googleapis.com/maps/api/geocode/json?"
FimDoURL="&key=????????????????????????????????" #I have the key right, this part works fine
#cur.execute('SELECT * FROM Lugares' )
#print type(cur)
#print cur
#row=cur.fetchone()
for row in cur.execute('SELECT * FROM LugareS' ):
print 'Entramos no While'
Loc_id = str(row[0])
Loc_Name = str(row[1])
Loc_Lat = row[2]
print Loc_Name
if Loc_Lat is None:
print Loc_Name
print Loc_Lat
print "Buscando "+Loc_Name+" no Google Maps"
try:
Url = ServiceUrl + urllib.urlencode({"sensor": "false", "address": Loc_Name}) + FimDoURL
Uh = urllib.urlopen(Url)
Dados = Uh.read()
try: js = json.loads(str(Dados))
except: js = None
except: continue
if "status" not in js or js["status"] != "OK":
print "===== Beeehhhh!!! Não conseguimos encontrar essa cidade===="
print Dados
continue
else:
Loc_FormatedAdress = js["results"][0]["formatted_address"]
Loc_Lat = js["results"][0]["geometry"]["location"]["lat"]
Loc_Lon = js["results"][0]["geometry"]["location"]["lng"]
print Dados
print 'Endereço Google: ', Loc_FormatedAdress
print 'Latitude: ', Loc_Lat
print 'Longitude: ', Loc_Lon
cur.execute('''UPDATE Lugares SET Latitude= ?, Longitude=?, GoogleLoc=? WHERE id= ?
''', (Loc_Lat, Loc_Lon, Loc_FormatedAdress, Loc_id))
#row=cur.fetchone()
else: #row=cur.fetchone()
continue
conn.commit()
Thank you guys!
If the file is large, you may not want to load the entire database into memory with "fetchall" but read only one row at a time, and update entries on the go. You can do this by creating two cursors.
import sqlite3 as sq3
conn = sq3.connect(db_name)
cur = conn.cursor()
cur2 = conn.cursor()
for row in cur.execute('SELECT * FROM Table' ):
cur2.execute('''UPDATE Table SET variable = ? WHERE id= ?''', (variable, id))
works fine.
for row in cur.execute('SELECT * FROM LugareS' ):
...
cur.execute('''UPDATE Lugares SET Latitude= ?, Longitude=?, GoogleLoc=? WHERE id= ?
You are executing a different query on the same cursor object; the UPDATE does not have any result rows.
Simply read all the data before looping over it:
cur.execute('SELECT id, Name FROM Lugares WHERE Latitude IS NULL')
empty_rows = cur.fetchall()
for row in empty_rows:
...

How to get multiple rows and columns using mysql db through django

Getting single row and single column below code is executed sucessfully. How to get multiple columns and rows?
views.py
def get_db_data(request):
conn = MySQLdb.connect (host = "localhost", user = "test_user", passwd = "test_pwd", db = "myproject")
cursor = conn.cursor ()
cursor.execute ("SELECT email_address, mobile_number,id, city, state FROM user")
if cursor.rowcount == 0:
html = "<html><body>There is no Faculty member with id %s.</body></html>" % email_address
else:
row = cursor.fetchone()
html = "<html><body>E-Mail address %s.</body></html>" % row[0]
return HttpResponse(html)
Please help me with this.
UPD:
def get_db_data(request):
conn = MySQLdb.connect (host = "localhost", user = "test_user", passwd = "test_pwd", db = "myproject")
cursor = conn.cursor ()
cursor.execute ("SELECT email_address, mobile_number,id, city, state FROM user")
if cursor.rowcount == 0:
html = "<html><body>There is no Faculty member with id %s.</body> <html>" % email_address
else:
html = "<html>"
for x in cursor.fetchone():
html += "<body>E-Mail address %s.</body>" % x
html += "<html>"
return HttpResponse(html)
All columns
cursor.execute("SELECT * FROM user")
All rows:
cursor.fetchall()
for row in cursor.fetchall():
html = ...
and there is one more thing it is not about your problem but you should keep in mind while write if
The values 0, None, False all are false for if statement so it's better to write if not cursor.rowcount instead if cursor.rowcount==0
you can use this.
import MySQLdb
import MySQLdb.cursors
def get_db_data(request):
conn = MySQLdb.connect(host="localhost", user="test_user", passwd="test_pwd", db="myproject", cursorclass=MySQLdb.cursors.DictCursor)
cursor = conn.cursor()
cursor.execute("SELECT email_address, mobile_number,id, city, state FROM user")
if cursor.rowcount == 0:
html = "<html><body>There is no Faculty member with id.</body></html>"
else:
htm = "<html><body>"
for row in cursor.fetchall():
html += "Id - {id}, E-Mail address - {email_address}, Mobile Number - {mobile_number}, City - {city}, State {state}. </br>".format(**row)
html += "</body></html>"
return HttpResponse(html)

Error message: End of script output before header while using MYSQL

I am trying to implement MYSQL in python cgi-bin. I dont know why this is coming.
I am doing this on windows 8 and python version 2.7.8. I also visited different but fail to solve.
File name: sqlcgi.py
My code:
#!C:\Python27\python
import cgi
import MySQLdb
db = MySQLdb.connect(host="127.0.0.1",port=3306, user="root", passwd="",db="project")
cursor = db.cursor() #for 1st query
cursor2 = db.cursor()##for 2nd query
# execute SQL select statement
#sql = "SELECT stid,firstname FROM student WERE stid IN(SELECT stid FROM stobt WHERE stid=%s" % (0) #query number 1
#query number 1
sql2 = "SELECT stid FROM student WHERE firstname = '%s'" % ('User')
# Execute the SQL command
cursor2.execute(sql2)
# Fetch all the rows in a list of lists.
result2 = cursor2.fetchall()
print result2
row2 = result2[0]
#print 'r1',row[1]
#print 'r2',row2[0]
sql = "SELECT * FROM stobt WHERE stid = '%d'" % (row2)
cursor.execute(sql)
results = cursor.fetchall()
row = results[1]
tc = 56
for row in results:
if row2[0] == row[1]:
idd = row[0]
stid = row[1]
obtained = row[2]
subject = row[3]
# Now print fetched result
print "id=%s,stid=%s,obtained=%f,subject=%s" % \
(idd, stid, obtained, subject )
if obtained <= 50:
if tc >= 50:
print tc
print """Content-type: text/html\n
<html><head><title>MySQL and Python on the Web</title></head>
<body bgcolor=#FFCCFF><h1>Message Board Report</h1>
This is a message board report demo.<hr>
<b>This is what has been going on ... </b><br>
"""
print idd
print """
<hr>
<form method=POST>Please enter your comment: <input name=info><br>
<input type=submit>
</form>
<hr>
Demonstration from Well House Consultants.<br>
<a href=http://www.wellho.net/>Website</a>
</body></html>
"""
# disconnect from server
db.close()
Error:
Error message:
End of script output before headers: sqlcgi.py
I dont know whether i am doing wrong or correct because when i remove all sql section and cgi prints but with sql does not.
There is an error somewhere before the first output statement, and your script is aborting.
It will help to find it if you enable trace back reporting. Add this to the top of your script:
import cgitb
cgitb.enable()
When you load the page in a browser, you should see what the error is.
There are also other problems with your script. In a CGI script, standard output is sent as the HTTP reply. Importantly the HTTP headers must be written first, before the actual content.
In this case you have some debug print statements, e.g. line 22, that generate output before the HTTP headers are printed.

Python CGI error trying to execute a sqlite command

I'm not sure why it says that the table ajax_exmaple does not exist... I check sqlite3 to see that the database and the tables along w/ their corresponding datas are all there. Any ideas?
When I try to execute this command:
query_result = c.execute(query, (sex, age, wpm))
...I get:
<class 'sqlite3.OperationalError'>: no such table: ajax_example
args = ('no such table: ajax_example',)
message = 'no such table: ajax_example'
This is my complete code:
#!C:\python27\python.exe
import cgi, cgitb, sqlite3
cgitb.enable()
print "Content-type: text/html"
print ""
conn = sqlite3.connect('../htdocs/ajax_ex.db')
c = conn.cursor()
# Capture URL query
form = cgi.FieldStorage()
age = form.getvalue('age')
sex = form.getvalue('sex')
wpm = form.getvalue('wpm')
# Build SQL
query = "SELECT * FROM ajax_example WHERE ae_sex = ?"
if(isinstance(age, int)):
query += " AND ae_age <= ?"
if(isinstance(wpm, int)):
query += " AND ae_wpm <= ?"
# Execute query
query_result = c.execute(query, (sex, age, wpm))
conn.close()
# Build result string
display_string = '''
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Sex</th>
<th>WPM</th>
</tr>'''
# Insert a new row in the table for each person returned
for row in query_result:
display_string += "<tr>"
display_string += "<td>row['ae_name']</td>"
display_string += "<td>row['ae_age']</td>"
display_string += "<td>row['ae_sex']</td>"
display_string += "<td>row['ae_wpm']</td>"
display_string += "</tr>"
print "Query: ", query, "<br>"
display_string += "</table>"
print display_string

Categories