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()返回是執(zhí)行語句影響的行數,剛開始我以為是返回的結果,導致繞了很遠的彎路。真正為返回結果的是cursor.fechone(),表示獲取執(zhí)行結果的第一條。同時還有cursor.fetchall(),表示獲取所有結果。如果獲取了多個字段的話,結果為數組類型,按照查詢結果的字段順序排序。
MySQLdb是python與數據庫連接的一個模塊。這個模塊并不是本來就存在的,需要下載并安裝到python得目錄下才行。MAC安裝這個模塊有個奇怪的要求,就是必須在本機安裝了mysql,即便實際上程序使用的外部的數據庫。在已安裝mysql的前提下,發(fā)現安裝mysqldb錯誤,并報了mysql目錄找不到錯誤時,可用以下方法解決:
在用戶的home目錄下vi .profile
加入 export PATH=$PATH:/user/local/mysql/bin,退出并保存
再執(zhí)行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()
這個部分創(chuàng)建了一個訪問路徑/Service/A,該路徑對應的服務是hello類提供的。在這個類的get方法中調用了aService的getA方法。在頁面上顯示出一個json格式的文本。執(zhí)行步驟如下
終端:python hello.py 8080
瀏覽器:localhost:8080/Service/A
相關文章
Python astype(np.float)函數使用方法解析
這篇文章主要介紹了Python astype(np.float)函數使用方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06
使用Tensorflow將自己的數據分割成batch訓練實例
今天小編就為大家分享一篇使用Tensorflow將自己的數據分割成batch訓練實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01

