SoFunction
Updated on 2024-11-21

python+mysql implementation of simple web programs

This time I'm going to add a database to my python program, mainly to enable querying data from mysql and displaying it on the page.

First the mysql configuration file

host="127.0.0.1"
user="root"
password=""
charset="utf8"
database="service"
port=3306

Then the data is read from the database

import MySQLdb
import sys
import config
class AService(object):
    def getA(self,id):
      conn = (host=,user=,passwd=,port=,db=,charset=)
      result=[]
      try:
        cursor = ();
        ("select id,code,title from test_a where id='%d'"%(id))
        result = ()
      except Exception,e:
        print "System error: ",e
        result = "error"
      finally:
        ()
        ()
      return result

Which () return is the number of lines affected by the execution of the statement, at first I thought it was the result of the return, resulting in a long detour. Really for the return result is (), said to get the first execution results. There is also (), which means get all results. If you get more than one field, the results are an array type, sorted by the order of the fields in the query results.

MySQLdb is a module for python to connect to databases. This module does not exist in the first place, but needs to be downloaded and installed in the python directory, and the MAC has a strange requirement that mysql must be installed locally, even if the program is actually using an external database. If you get an error installing mysqldb and get a mysql directory not found error when mysql is already installed, you can fix it as follows:

In the user's home directory vi .profile

Add export PATH=$PATH:/user/local/mysql/bin, exit and save

Execute the source . /.profile command and exit the terminal.

After this, reinstalling mysqldb shouldn't give you the error about not finding the mysql directory.

Next is the main program

import web
import aService
import sys
 
urls = ("/Service/A","hello")
app = (urls,globals())
 
class hello:
    def GET(self):
        mservice = ()
        result = (1)
        json = ""
        json +="{"
        json +="'id':"+str(result[0])+","
        json +="'code':'"+result[1]+"',"
        json +="'title':'"+result[2]+"'"
        json +="}"
        return json;
if __name__=="__main__":
    ()

This section creates an access path /Service/A, which corresponds to the service provided by the hello class. The get method of this class calls the getA method of aService. A text in json format is displayed on the page. The execution steps are as follows

Terminal: python 8080

Browser: localhost:8080/Service/A