importflask,json,pymysqlfrom flask importrequest, jsonify, Responsefrom datetime importdatetimefrom flask_cors importCORS
db=pymysql.Connect(
host='localhost',
port=3306,
user='root',
passwd='24576946',
db='school',
)
cursor=db.cursor()
server= flask.Flask(__name__)#允许跨域访问
CORS(server, resources=r'/*')classJSONResponse(Response):
@classmethoddef force_type(cls, response, environ=None):ifisinstance(response, (list, dict)):
response=jsonify(response)
response.headers['Access-Control-Allow-Credentials'] = 'true'response.headers['Access-Control-Allow-Origin'] = '*'response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'response.headers['Access-Control-Allow-Headers'] = 'X-Requested-With'
returnsuper(Response, cls).force_type(response, environ)
server.response_class=JSONResponse#查询成绩列表
@server.route('/grade',methods=['get'])defgrade():
sql= "SELECT id,name,email,point,regdate FROM grade"cursor.execute(sql)
res=cursor.fetchall()
keys= ['id','name','email','point','regdate']
arr=[]for index,item inenumerate(res):
dict1={}for indexd,itemd inenumerate(item):if keys[indexd] == 'regdate':print(itemd)
dict1[keys[indexd]]= itemd.strftime('%Y-%m-%d %H:%M')else:
dict1[keys[indexd]]=itemd
arr.append(dict1)return json.dumps(arr,ensure_ascii=False)#添加单个成绩
@server.route('/grade',methods=['post'])defadd():
option=json.loads(request.get_data())if option['name'] == '':return jsonify({"code": 500,"error":'name不能为空!'})
sql= "INSERT INTO grade (name, email, point, regdate) VALUES ( '%s', '%s', '%d','%s' )"data= (option['name'], option['email'], option['point'],datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M'))
cursor.execute(sql%data)
db.commit()return jsonify({"code": 200,"data":{"name": option['name'], "email": option['email'], "point": option['point']}})#add()
#查询单个成绩
@server.route('/grade/',methods=['get'])defsearch(post_id):print(post_id)
sql= "SELECT id,name,email,point,regdate FROM grade WHERE id = %s" %(post_id)
cursor.execute(sql)
res=cursor.fetchone()
keys= ['id','name','email','point','regdate']
dict1={}for index,item inenumerate(res):if keys[index] == 'regdate':
dict1[keys[index]]= item.strftime('%Y-%m-%d %H:%M')else:
dict1[keys[index]]=itemreturn json.dumps(dict1,ensure_ascii=False)#删除单个成绩
@server.route('/grade/',methods=['post'])defdelete(post_id):print(post_id)
sql= "DELETE FROM grade WHERE id = %s" %(post_id)
cursor.execute(sql)
res=cursor.fetchone()return jsonify({"code":200,"data":'删除成功!'})#delete(24)
#查询老师列表
@server.route('/teacher',methods=['get'])defgetTeacher():
sql= "SELECT id,name,description,student,regdate FROM teacher"cursor.execute(sql)
res=cursor.fetchall()
keys= ['id','name','description','student','regdate']
arr=[]for index,item inenumerate(res):
dict1={}for indexd,itemd inenumerate(item):if keys[indexd] == 'regdate':print(itemd)
dict1[keys[indexd]]= itemd.strftime('%Y-%m-%d %H:%M')else:
dict1[keys[indexd]]=itemd
arr.append(dict1)return json.dumps(arr,ensure_ascii=False)#查询老师有哪几个学生
@server.route('/teacher/',methods=['get'])defsearchStudent(teacher_id):
student_id= request.args.get('studentId')
sql= "SELECT id,name,email,point FROM grade WHERE id = %s" %(student_id)
cursor.execute(sql)
res=cursor.fetchone()
keys= ['id','name','email','point']
dict1={}for index,item inenumerate(res):
dict1[keys[index]]=itemreturn json.dumps(dict1,ensure_ascii=False)
server.run(port=9003,debug=True,host='192.168.1.195')#关闭连接
cursor.close()
db.close()