python tornado框架实现CRUD
1.本例采用postgresql数据库,创建数据表 user_tbl
create table user_tbl(name varchar(20),signup_date date);
2.webapi接口
(1)tornado框架配置 t_tornado.py
#-*- coding:UTF-8 -*- import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.options import define,options import t_url import psycopg2 app=tornado.web.Application(t_url.url) define("port",default=8000,help="run on port",type=int) if __name__=="__main__": tornado.options.parse_command_line() app.listen(options.port) tornado.ioloop.IOLoop.instance().start()
(2)路径映射 t_url.py
from t_handler import * url=[ (r'/',IndexHandler), (r'/AddUser',AddHandler), (r'/EditUser',EditHandler), (r'/DelUser',DelHandler) ]
(3)处理类 t_handler.py
from tornado.web import RequestHandler from tornado.escape import json_decode,json_encode import psycopg2 #解决js跨域请求问题 class BaseHandler(RequestHandler): def set_default_headers(self): self.set_header('Access-Control-Allow-Origin', '*') self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') self.set_header('Access-Control-Max-Age', 1000) self.set_header('Access-Control-Allow-Headers', '*') self.set_header('Content-type', 'application/json') #删除用户 class DelHandler(BaseHandler): def post(self): name=self.get_argument('name',None) result={} conn=psycopg2.connect(host='127.0.0.1',port=5432,user='leo',password='king',database='testdb') cursor=conn.cursor() try: sqlstr="delete from user_tbl where name='%s'"%name cursor.execute(sqlstr) except(psycopg2.Warning,psycopg2.Error) as error: result["result"]="DB Error:"+error.message result["status"]="false" result["code"]=300 self.write(json_encode(result)) conn.rollback() cursor.close() conn.close() return result["result"]="success" result["status"]="true" result["code"]=200 if(result["status"]=="true"): conn.commit() cursor.close() conn.close() self.write(json_encode(result)) #修改用户 class EditHandler(BaseHandler): def post(self): o_name=self.get_argument('o_name',None) name=self.get_argument('name',None) time=self.get_argument('time',None) result={} conn=psycopg2.connect(host='127.0.0.1',port=5432,user='leo',password='king',database='testdb') cursor=conn.cursor() try: sqlstr="update user_tbl set name='%s',signup_date='%s' where name='%s'"%(name,time,o_name) cursor.execute(sqlstr) except(psycopg2.Warning,psycopg2.Error) as error: result["result"]="DB Error:"+error.message result["status"]="false" result["code"]=300 self.write(json_encode(result)) conn.rollback() cursor.close() conn.close() return result["result"]="success" result["status"]="true" result["code"]=200 if(result["status"]=="true"): conn.commit() cursor.close() conn.close() self.write(json_encode(result)) #新增用户 class AddHandler(BaseHandler): def post(self): time=self.get_argument('time',None) result={} conn=psycopg2.connect(host='127.0.0.1',port=5432,user='leo',password='king',database='testdb') cursor=conn.cursor() try: sqlstr="insert into user_tbl(name,signup_date) values('%s','%s')"%(name,time) cursor.execute(sqlstr) except(psycopg2.Warning,psycopg2.Error) as error: result["result"]="DB Error:"+error.message result["status"]="false" result["code"]=300 self.write(json_encode(result)) conn.rollback() cursor.close() conn.close() return result["result"]="success" result["status"]="true" result["code"]=200 if(result["status"]=="true"): conn.commit() cursor.close() conn.close() self.write(json_encode(result)) class IndexHandler(BaseHandler): def get(self): conn=psycopg2.connect(host='127.0.0.1',port=5432,user='leo',password='king',database='testdb') cursor=conn.cursor() result={} try: sqlstr="select name,signup_date from user_tbl" cursor.execute(sqlstr) if(cursor.rowcount==0): result["total"]=0 result["rows"]="no data." result["status"]="false" result["code"]=300 self.write(json_encode(result)) conn.close() return else: res=cursor.fetchall() content=[] t=1 for item in res: tempItem={} tempItem["id"]=t tempItem["name"]=item[0] try: tempItem["signup_date"]=item[1].strftime("%Y-%m-%d %H:%M:%S") except: tempItem["signup_date"]='' t+=1 content.append(tempItem) result["total"]=1000 result["rows"]=content result["status"]="true" result["code"]=200 except(psycopg2.Warning,psycopg2.Error) as error: result["result"]="DB error:"+error.message result["status"]="false" result["code"]=300 self.write(json_encode(result)) conn.rollback() conn.close() return if(result["status"]=="true"): conn.commit() conn.close() print json_encode(result) self.write(json_encode(result))
3.html请求
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery.min.js" type="text/javascript"></script> <script src="Scripts/jquery.easyui.min.js" type="text/javascript"></script> <link href="Css/easyui.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> var o_name; var userUrl = "http://127.0.0.1:8000"; $(function () { initUser(); $('#dri_grid').datagrid('load', userUrl); $("#dri_tools_add").click(function() { $("#n_name").val(""); $("#n_time").val(""); var a = document.getElementById('driver_add'); a.href = "javascript:driver_adddd()"; $("#adduser").show(); }); $("#dri_tools_edit").click(function() { var row=$("#dri_grid").datagrid('getSelected'); if(row){ var name = row.name; o_name = name; var time = row.signup_date; $("#n_name").val(name); $("#n_time").val(time); var a = document.getElementById('driver_add'); a.href = "javascript:driver_editdd()"; $("adduser").show(); } else{ alert("please select"); } $("#adduser").show(); }); $("#dri_tools_del").click(function() { var row = $('#dri_grid').datagrid('getSelected'); if (row) { if(confirm("really delete?")){ var t_name = row.name; var datas = { name: t_name }; var driver_delurl="http://127.0.0.1:8000/DelUser"; $.post(driver_delurl, datas, function (v) { if (v.status=="true") { $("#dri_grid").datagrid("reload"); alert("success"); } else { alert("error"); } }); } } else { alert("please select"); } }); }); function driver_adddd(){ var n_name = $("#n_name").val(); var n_time = $("#n_time").val(); var userdata = { name: n_name, time: n_time }; var driver_addurl="http://127.0.0.1:8000/AddUser"; $.post(driver_addurl, userdata, function(s) { if (s.status == "true") { $("#dri_grid").datagrid("reload"); alert('新增成功'); } else { alert(s.result); } }); } function driver_editdd(){ var n_name = $("#n_name").val(); var n_time = $("#n_time").val(); var userdata = { o_name:o_name, name: n_name, time: n_time }; var driver_addurl="http://127.0.0.1:8000/EditUser"; $.post(driver_addurl, userdata, function(s) { if (s.status == "true") { $("#dri_grid").datagrid("reload"); alert('更新成功'); } else { alert(s.result); } }); } function initUser() { $('#dri_grid').datagrid({ border: false, fit: true, singleSelect: true, method: 'get', pagination: true, striped: true, pageSize: 20, onBeforeLoad: function() { }, columns: [ [{ field: 'name', title: 't_name', width: '8%', align: 'center' }, { field: 'signup_date', title: 't_signup_date', width: '14%', align: 'center' } ] ], onLoadSuccess: function(data) { } }); } </script> </head> <body> <span id="dri_tools_add"> <a href="#" style="width: 100px">新增</a> </span> <span id="dri_tools_edit"> <a href="#" style="width: 100px">修改</a> </span> <span id="dri_tools_del"> <a href="#" style="width: 100px">删除</a> </span> <div id="adduser" style="display:none;"> <table style="padding-left: 4%; padding-right: 4%"> <tr> <td> <span style="color: red">*</span> <label>姓名:</label> </td> <td style="padding-right: 80px; padding-bottom: 5px;"> <input id="n_name" style="width:100px;" type="text"> </td> <td> <label>注册时间:</label> </td> <td style="padding-bottom: 5px; width: 175px;"> <input id="n_time" style="width:100px;" type="text"> </td> </tr> </table> <div><a id="driver_add" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" href="javascript:void(0)" style="width: 120px">提交</a> </div> </div> <table id="dri_grid"></table> </body> </html>
4.浏览器显示结果:
(1)查询
(2)新增
(3)修改
(4)删除