python+mysql实现简单的web程序

yipeiwu_com7年前Python基础

这次要为我的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

相关文章

Python numpy 提取矩阵的某一行或某一列的实例

如下所示: import numpy as np a=np.arange(9).reshape(3,3) a Out[31]: array([[0, 1, 2], [3,...

Python中创建字典的几种方法总结(推荐)

1、传统的文字表达式: >>> d={'name':'Allen','age':21,'gender':'male'} >>> d {'age':...

Pytorch 的损失函数Loss function使用详解

Pytorch 的损失函数Loss function使用详解

1.损失函数 损失函数,又叫目标函数,是编译一个神经网络模型必须的两个要素之一。另一个必不可少的要素是优化器。 损失函数是指用于计算标签值和预测值之间差异的函数,在机器学习过程中,有多种...

Python中getpass模块无回显输入源码解析

本文主要讨论了python中getpass模块的相关内容,具体如下。 getpass模块 昨天跟学弟吹牛b安利Python标准库官方文档的时候偶然发现了这个模块。仔细一看内容挺少的,只有...

Python实现线程池代码分享

原理:建立一个任务队列,然多个线程都从这个任务队列中取出任务然后执行,当然任务队列要加锁,详细请看代码 import threading import time import sig...