一、Flask 最简单的案例
- 安装 flask 模块
pipinstallflask
- 导入 flask 模块,实现最简单的案例
fromflaskimportFlask app=Flask(__name__)@app.route('/')defhello():return'Hello World'if__name__=='__main__':app.run()
二、Flask 处理跨域
- 安装 flask-cors 模块
pipinstallflask-cors
- 导入 flask-cors 模块,处理跨域
fromflask_corsimportCORS...CORS(app)
三、Flask 基础接口
1、不带参数的 GET 请求
@app.route('/test')deftest():return'Test Page'
// Promise 风格fetch("http://127.0.0.1:5000/test",{method:"GET",}).then((response)=>response.text())// 解析数据.then((data)=>console.log(data))// 处理数据.catch((error)=>console.error("Error:",error));// 处理错误
// async await 风格try{constresponse=awaitfetch("http://127.0.0.1:5000/test",{method:"GET",});constdata=awaitresponse.text();console.log(data);}catch(error){console.error("Error:",error);}
2、带参数的 GET 请求
- 路径参数
@app.route('/showUsername/<username>')defshow_username(username):print(f'username type:{type(username)}')returnf'username:{username}'
try{constresponse=awaitfetch("http://127.0.0.1:5000/showUsername/test123",{method:"GET",});constdata=awaitresponse.text();console.log(data);}catch(error){console.error("Error:",error);}
- 查询参数
@app.route('/showUserId')defshow_userId():userId=request.args.get('userId')print(f'userId type:{type(userId)}')returnf'userId:{userId}'
try{constresponse=awaitfetch("http://127.0.0.1:5000/showUserId?userId=test123",{method:"GET",});constdata=awaitresponse.text();console.log(data);}catch(error){console.error("Error:",error);}
3、POST 请求
- 表单数据
@app.route('/login',methods=['POST'])deflogin():username=request.form['username']password=request.form['password']print(f'username type:{type(username)}')print(f'password type:{type(password)}')print(f'username:{username}, password:{password}')return'Login Page'
constformData=newFormData();formData.append("username","admin");formData.append("password","123456");try{constresponse=awaitfetch("http://127.0.0.1:5000/login",{method:"POST",body:formData,});constdata=awaitresponse.text();console.log(data);}catch(error){console.error("Error:",error);}
- JSON 数据
@app.route('/login',methods=['POST'])deflogin():data=request.get_json()username=data['username']password=data['password']print(f'username type:{type(username)}')print(f'password type:{type(password)}')print(f'username:{username}, password:{password}')return'Login Page'
try{constresponse=awaitfetch("http://127.0.0.1:5000/login",{method:"POST",headers:{"Content-Type":"application/json",},body:JSON.stringify({username:"admin",password:"123456",}),});constdata=awaitresponse.text();console.log(data);}catch(error){console.error("Error:",error);}