python tornado 框架写接口

  app.py
---------------------------------------------
import tornado.ioloop
import tornado.web
from api.Api_Get import Api_Get
from api.GetIndex import GetIndex

if __name__ == "__main__":
    application = tornado.web.Application([
        ("/",GetIndex),
        ("/api", Api_Get),
    ])

    application.listen(8888)
    tornado.ioloop.IOLoop.current().start()
-----------------------------------------------
api/Api_Get.py

import tornado.web
from api.Getjson import *
from api.sql import *
class Api_Get(tornado.web.RequestHandler):
    def get(self):
        data={
            'msg':'ok',
            'data':RedSql("sheet1"),
            'code':1


        }
        GetJson(self,data)
------------------------------------------
api/GetJson.py

import json
def set_default_header(self):
    # 后面的*可以换成ip地址,意为允许访问的地址
    self.set_header('Access-Control-Allow-Origin', '*')
    self.set_header('Access-Control-Allow-Headers', 'x-requested-with')
    self.set_header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE')
def GetJson(self,data):
    set_default_header(self)
    self.set_header('Content-Type', 'application/json; charset=UTF-8')
    return self.write(json.dumps(data,ensure_ascii=False))
-----------------------------------------------
api/sql.py

import pymysql
# 连接数据库
sqlr = pymysql.connect(host='127.0.0.1',
                       user='root',
                       password='root',
                       database='820012',
                       charset='utf8')
def mysql():
    if sqlr:
         print('mysql连接成功')
         return sqlr.cursor()
    else:
        print('mysql连接失败')

# 查询数据
# table为表名
# cur.fetchall()返回所有内容
def RedSql(table):
    cur =mysql()
    cur.execute('select * from '+str(table))
    return cur.fetchall()
# # 删除数据
# id为目标id
# table为目标表名
def DelSql(table,id):
    cur =mysql()
    cur.execute('DELETE FROM '+str(table)+' WHERE id='+str(id))
    if sqlr.commit():
        return {'msg':'ok'}
    else:
        return {'msg':'no'}
    cur.close()
    sqlr.close()
# 修改数据
# data为sql语句 update my_school set name = %s where id = %s'
def UpSql(data):
    cur =mysql()
    cur.execute(data)
    if sqlr.commit():
        return {'msg':'ok'}
    else:
        return {'msg':'no'}
    cur.close()
    sqlr.close()
# 添加数据
# data为sql语句 insert into table(id, name) values(%s, %s)
def AddSql(data):
    cur =mysql()
    cur.execute(data)
    if sqlr.commit():
        return {'msg':'ok'}
    else:
        return {'msg':'no'}
    cur.close()
    sqlr.close()
----------------------------------------------
index.html

<html>
<head>
<title>接口测试</title>
<style type="text/css">
table{
width:50%;
	font-family: verdana,arial,sans-serif;
	font-size:11px;
	color:#333333;
	border-width: 1px;
	border-color: #666666;
	border-collapse: collapse;
}
th {
	border-width: 1px;
	padding: 8px;
	border-style: solid;
	border-color: #666666;
	background-color: #dedede;
}
td {
	border-width: 1px;
	padding: 8px;
	border-style: solid;
	border-color: #666666;
	background-color: #ffffff;
}
</style>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js">
</script>
<script>
$(document).ready(function(){

 $.get('http://127.0.0.1:8888/api',function(data){
       //console.log(JSON.parse(data)["data"])
	   data =data['data'];
	   console.log(data)
	   var html="<table>"
	   for (var i in data){
	   html+="<tr>"
	   for (var t in data[i]){
	html+="<td>"+data[i][t]+"</td>";
	   console.log(data[i][t]);
	   }
	   html+="</tr>"
	   }
	      html+="</table>"
	    $('#value').html(html)
	   <!-- if(JSON.parse(data)['code']=="1"){ -->
	   <!-- da=JSON.parse(data)["data"] -->
	   <!-- $('#value').html(da.toString()) -->
	   <!-- }else{ -->
	    <!-- alert(JSON.parse(data)['msg']);  -->
	   <!-- } -->
	   
     
 
 })
});


</script>
</head>

<span id="value"></span>

   
        <!-- <h1>Upload new File</h1> -->
        <!-- <form method="post" enctype="multipart/form-data" action="http://127.0.0.1:5000/"> -->
          <!-- <input type="file" name="file"> -->
          <!-- <input type="submit" value="Upload"> -->
        <!-- </form> -->

</html>


评论

刷新

友情链接