python+mysql實現簡單的web程式

來源:互聯網
上載者:User
這次要為我的python程式加上資料庫,主要是實現從mysql中查詢出資料並在頁面上顯示出來。

首先是mysql的設定檔config.py

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

然後是從資料庫中讀取資料的aService.py

import MySQLdbimport sysimport configclass 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 webimport aServiceimport 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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.