import flask # web框架
from day06.tools import op_mysql
import json
# 接口,后台服务
server = flask.Flask(__name__) # 把咱们这个python文件当做一个server
# 127.0.0.1:8080/get_user
@server.route('/get_user', methods=['get', 'post'])
def get_all_user():
sql = 'select * from bt_stu;'
res_sql = op_mysql(
host='211.149.218.16',
user='jxz', password='123456', # port这里一定要写int类型
port=3306, db='jxz', charset='utf8', sql=sql)
response = json.dumps(res_sql, ensure_ascii=False) # 把list转为json
return response # return的时候只能return字符串
@server.route('/add_user', methods=['post'])
def add_user():
user_id = flask.request.values.get('id') # 这里的参数就是调用接口的时候传入的参数
username = flask.request.values.get('u') # 这里的参数就是调用接口的时候传入的参数
if user_id.strip() and username.strip():
sql = 'insert into stu values ("%s", "%s")' % (user_id, username)
op_mysql(
host='211.149.218.16',
user='jxz', password='123456', # port这里一定要写int类型
port=3306, db='jxz', charset='utf8', sql=sql)
response = {'code': '200', 'msg': '添加成功!'}
return json.dumps(response, indent=4, ensure_ascii=False)
else:
response = {'code': '503', 'msg': '必填参数未填写!'}
return json.dumps(response, indent=4, ensure_ascii=False)
# 启动服务
server.run(port=8080, debug=True) # debug加上以后改代码不需要重启
server.run(port=8080, host='0.0.0.0', debug=True) # host 0.0.0.0 代表一个局域网里面所有的
# 别人访问用自己本机ip地址