from flask import Flask, jsonify, request, make_response, redirect import datetime app = Flask(__name__) app.config["JSON_AS_ASCII"] = False # jsonify返回的中文正常显示 # 第一步 @app.route("/") def test1(): return "你好flask" # 返回json数据 @app.route('/json') def do_json(): hello = {"name": "stranger", "say": "hello"} return jsonify(hello) # 状态码设置 @app.route('/status_500') def status_500(): return "hello", 500 # cookie @app.route('/set_cookie') def set_cookie(): response = make_response('这个页面携带cookie') out_date = datetime.datetime.today() + datetime.timedelta(days=30) # cookie的有效时长30天 response.set_cookie('username', 'li1236', expires=out_date) return response # 重定向 @app.route('/redir') def redir(): return redirect('https://www.baidu.com') # 设置请求方法 @app.route("/users", methods=["GET"]) def get_all_users(): """获取所有用户信息""" return jsonify({"code": "200", "data": {"id": 3, "username": "大白", "password": "666666"}, "msg": "操作成功"}) # 控制用户输入数据格式 # 普通的values值传输 @app.route("/values", methods=['POST']) def values(): values1 = request.values.get('values1') values2 = request.values.get('values2') if values1 and values2: return jsonify({"code": 200, "msg": "values传参方式访问成功"}) else: return jsonify({"code": 2001, "msg": "values1/values2不能为空,请检查"}) # form值传输 @app.route("/form", methods=['POST']) def form(): form1 = request.form.get('form1') form2 = request.form.get('form2') if form1 and form2: return jsonify({"code": 200, "msg": "from传参方式访问成功"}) else: return jsonify({"code": 2001, "msg": "form1/form2不能为空,请检查"}) # 传参方式必须是application/json @app.route("/register", methods=['POST']) def userRegister(): username = request.json.get("username").strip() # 用户名 password = request.json.get("password").strip() # 密码 if username and password: if username == "李帅哥": return jsonify({"code": 2002, "msg": "用户名已存在"}) elif len(password) < 6: return jsonify({"code": 2002, "msg": "密码长度必须大于或者等于6位"}) else: return jsonify({"code": 200, "msg": "恭喜,注册成功!"}) else: return jsonify({"code": 2001, "msg": "用户名/密码不能为空,请检查"}) # 控制用户的请求方法 # delete方法 # delete和get的传参直接写在方法名后面 @app.route("/delete/<int:userId>", methods=['DELETE']) def delete(userId): if userId > 0 and userId < 10: return jsonify({"code": 200, "msg": "删除" + str(userId) + "成功"}) else: return jsonify({"code": 200, "msg": "该用户不存在"}), 200 # put方法方法 @app.route("/put", methods=['PUT']) def put(): put1 = request.values.get('put1') put2 = request.values.get('put2') if put1 and put2: return jsonify({"code": 200, "msg": "put请求方式访问成功,信息修改成功"}) else: return jsonify({"code": 2001, "msg": "put1/put2不能为空,请检查"}) #登录生成cookie @app.route('/login', methods=["POST"]) def login(): name = request.json.get('name') pwd = request.json.get('pwd') if name and pwd: if name == "li" and pwd == "123": response = make_response(jsonify({"msg": "恭喜,注册成功"})) out_date = datetime.datetime.today() + datetime.timedelta(days=30) # cookie的有效时长30天 response.set_cookie('username', 'li1236', expires=out_date) return response, 200 else: return '登陆失败' if __name__ == '__main__': app.run(debug=True)