python mysql实现简单的web程序


这次要为我的python程序加上数据库,主要是实现从mysql中查询出数据并在页面上显示出来。

首先是mysql的配置文件config.py

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

然后是从数据库中读取数据的aService.py

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'"%(id))
        result = cursor.fetchone()
      except Exception,e:
        print "System error: ",e
        result = "error"
      finally:
        cursor.close()
        conn.close()
      return result

其中cursor.execute()返回是执行语句影响的行数,刚开始我以为是返回的结果,导致绕了很远的弯路。真正为返回结果的是cursor.fechone(),表示获取执行结果的第一条。同时还有cursor.fetchall(),表示获取所有结果。如果获取了多个字段的话,结果为数组类型,按照查询结果的字段顺序排序。

MySQLdb是python与数据库连接的一个模块。这个模块并不是本来就存在的,需要下载并安装到python得目录下才行。MAC安装这个模块有个奇怪的要求,就是必须在本机安装了mysql,即便实际上程序使用的外部的数据库。在已安装mysql的前提下,发现安装mysqldb错误,并报了mysql目录找不到错误时,可用以下方法解决:

在用户的home目录下vi .profile

加入 export PATH=$PATH:/user/local/mysql/bin,退出并保存

再执行source ./.profile命令并退出终端

这样过后,在重新安装mysqldb应该就不会报找不到mysql目录的错误了。

接下来是主程序hello.py

import web
import aService
import sys

urls = ("/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()

这个部分创建了一个访问路径/Service/A,该路径对应的服务是hello类提供的。在这个类的get方法中调用了aService的getA方法。在页面上显示出一个json格式的文本。执行步骤如下

终端:python hello.py 8080

浏览器:localhost:8080/Service/A