#!/usr/bin/python3
from bottle import route,hook,template, run,request,response,get
import pymysql,json
@hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Authorization, Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, X-Requested-By, If-Modified-Since, X-File-Name, X-File-Type, Cache-Control, Origin'
@get('/hello')
def hello():
    db = pymysql.connect(host="172.16.8.224",user= "reader", password="123456",database= "student_information",port=1432)
    cursor = db.cursor()

    banji=request.query.getunicode('class')
    name=request.query.getunicode('name')
    response.set_header('Access-Control-Allow-Origin','*')
    response.set_header('Access-Control-Allow-Methods','GET, POST')
    response.set_header('Access-Control-Allow-Headers','Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token')
    cursor.execute('select stuid from student where classid= %s and name= %s',(banji,name))
    if cursor.rowcount==0:
        db.close()
        return 'E\n找不到该学生的信息'
    
    data = cursor.fetchone()
    stuid=data[0]
    cursor.execute('select*from tice where shenfenzheng= %s',stuid)
    if cursor.rowcount==0:
        db.close()
        return 'E\n该学生没有体测信息'
    
    data=cursor.fetchall()
    outall=[]
    sex=int(stuid[16])%2

    for row in data:
        outrow={}
        outrow['testdate']=str(row[1])
        outrow['nianduan']=str(row[2])
        outrow['shengao']=str(row[3])
        outrow['tizhong']=str(row[4])
        outrow['feihuoliang']=str(row[5])
        outrow['wushimi']=str(row[6])
        outrow['zuoweiti']=str(row[7])
        outrow['lidingtiaoyuan']=str(row[8])
        outrow['yinti_yangwo']=str(row[9])
        outrow['changpao']=str(row[10])
        outrow['sex']=str(sex)
        outall.append(outrow)
    db.close() 
    output=json.dumps(outall)
    return output

run(host='localhost', port=8080, debug=True)