This time I'm going to add a database to my Python program, mainly to get the data from MySQL and display it on the page.
The first is the MySQL profile config.py
Host= "127.0.0.1"
user= "root"
password= "" charset= "UTF8" database= "
service"
port=3306
And then the aservice.py that reads the data from the database.
Import mysqldb
import sys
import config
class Aservice (object):
def geta (self,id):
conn = MySQLdb.connect (Host=config.host,user=config.user,passwd=config.password,port=config.port,db=config.database, Charset=config.charset)
result=[]
try:
cursor = Conn.cursor ();
Cursor.execute ("Select Id,code,title from test_a where id= '%d"% (IDS)) Result
= Cursor.fetchone ()
except Exception,e:
print "System error:", e result
= "error"
finally:
cursor.close ()
conn.close ( ) Return result
where Cursor.execute () returns the number of rows affected by the execution of the statement, at first I thought it was the result of the return, leading to a long detour. The real return result is cursor.fechone (), which represents the first rule to get execution results. There is also Cursor.fetchall (), which indicates that all results are obtained. If more than one field is obtained, the result is an array type sorted by the field order of the query results.
MySQLdb is a module that Python connects to the database. This module does not exist and needs to be downloaded and installed into the Python directory. The MAC installation of this module has a strange requirement that MySQL must be installed on this machine, even if the program is actually using an external database. MySQL installed on the premise of the discovery of the installation MySQLdb error, and reported that the MySQL directory can not find errors, the following ways to resolve:
Under the user's home directory Vi. profile
Add Export path= $PATH:/user/local/mysql/bin, Exit and save
Then execute the source./.profile Command and exit the terminal
After that, MYSQLDB should not be able to find the MySQL directory error in the reinstall.
Next up is the main program hello.py
Import Web
import aservice
import sys
URL = ("/service/a", "Hello")
app = Web.application (URLs, Globals ())
class Hello:
def get (self):
Mservice = aservice.aservice () result
= Mservice.geta (1)
JSON = ""
json = = {"
json = =" ' id ': "+str (result[0]) +",
"JSON + +" ' Code ': ' "+result[1]+" ', "
json = =" ' title ': ' +result[2]+ ' '
JSON + +} ' return
json;
If __name__== "__main__":
App.run ()
This section creates an access path/service/a, which corresponds to a service that is provided by the Hello class. The Aservice Geta method is invoked in the Get method of this class. Displays a JSON-formatted text on the page. The following steps are performed
Terminal: Python hello.py 8080
Browser: localhost:8080/service/a