import flask,json,pymysql from flask import request, jsonify, Response from datetime import datetime from flask_cors import CORS db = pymysql.Connect( host='localhost', port=3306, user='root', passwd='24576946', db='school', ) cursor = db.cursor() server = flask.Flask(__name__) #容許跨域訪問 CORS(server, resources=r'/*') class JSONResponse(Response): @classmethod def force_type(cls, response, environ=None): if isinstance(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' return super(Response, cls).force_type(response, environ) server.response_class = JSONResponse #查詢成績列表 @server.route('/grade',methods=['get']) def grade(): 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 in enumerate(res): dict1 = {} for indexd,itemd in enumerate(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']) def add(): 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/<int:post_id>',methods=['get']) def search(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 in enumerate(res): if keys[index] == 'regdate': dict1[keys[index]] = item.strftime('%Y-%m-%d %H:%M') else: dict1[keys[index]] = item return json.dumps(dict1,ensure_ascii=False) #刪除單個成績 @server.route('/grade/<int:post_id>',methods=['post']) def delete(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']) def getTeacher(): 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 in enumerate(res): dict1 = {} for indexd,itemd in enumerate(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/<int:teacher_id>',methods=['get']) def searchStudent(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 in enumerate(res): dict1[keys[index]] = item return json.dumps(dict1,ensure_ascii=False) server.run(port=9003,debug=True,host='192.168.1.195') # 關閉鏈接 cursor.close() db.close()