python学习笔记(十七)flask模块写接口
1 import flask,json 2 from tools import op_mysql #op_mysql() 3 # 接口,后台服务 4 server = flask.Flask(__name__) #把咱们这个app这个python文件当做一个server 5 @server.route('/get_user',methods=['get','post']) 6 def get_all_user(): 7 sql = 'select * from bt_stu;' 8 res = op_mysql( 9 host='211.149.218.16', 10 user='jxz', password='123456', # port这里一定要写int类型 11 port=3306, db='jxz', charset='utf8', sql=sql) 12 response = json.dumps(res,ensure_ascii=False) #把list转成json 13 return response #return 的时候只能return字符串 14 15 @server.route('/add_user',methods=['post']) 16 def add_user(): 17 user_id = flask.request.values.get('id') #这里的参数就是调用接口的时候传入的参数 18 username = flask.request.values.get('u') # 19 if user_id and username: 20 sql = "insert into stu values ('%s','%s');"%(user_id,username) 21 res = op_mysql( 22 host='211.149.218.16', 23 user='jxz', password='123456', # port这里一定要写int类型 24 port=3306, db='jxz', charset='utf8', sql=sql) 25 response = {'code':308,'msg':'添加成功'} 26 else: 27 response = {'code':503,'msg':'必填参数未填!'} 28 return json.dumps(response,ensure_ascii=False) 29 30 31 server.run(port=8080,debug=True)