目录
1. 创建一个简单的请求,没有写方法时默认为get
2. 创建一个get请求
3. 创建一个post请求,默认可以使用params和表单传参
4. 带有参数的post请求
1. 创建一个简单的请求,没有写方法时默认为get
from flask import Flask, request# 初始化一个flask的对象
app = Flask(__name__)@app.route("/")
def a():return "简单接口" # 注意一定要有返回if __name__ == '__main__':app.run()
2. 创建一个get请求
from flask import Flask, request# 初始化一个flask的对象
app = Flask(__name__)@app.route("/get",methods=['get'])
def get():name = request.values.get('name')age = request.values.get('age')if name is None or name == '':return '姓名必填'elif age is None or age == '':return '年龄必填'else:return {'name为:':name,'age为:':age}if __name__ == '__main__':app.run()
3. 创建一个post请求,默认可以使用params和表单传参
from flask import Flask, request# 初始化一个flask的对象
app = Flask(__name__)@app.route("/post",methods=['post'])
def post():name = request.values.get('name')age = request.values.get('age')if name is None or name == '':return '姓名必填'elif age is None or age == '':return '年龄必填'else:return {'name为:':name,'age为:':age}if __name__ == '__main__':app.run()
4. 带有参数的post请求
import timefrom flask import Flask, request, jsonify# 初始化一个flask的对象
app = Flask(__name__)# form参数的post接口
@app.route("/post_form",methods=['post'])
def post_form():name = request.form.get('name')age = request.form.get('age')if name is None or name == '':return '姓名必填'elif age is None or age == '':return '年龄必填'else:return {'name为:':name,'age为:':age}# json参数的post接口
@app.route("/post_json",methods=['post'])
def post_json():data = request.jsonif not all(key in data for key in ['name', 'age']):return jsonify({'error': '姓名和年龄是必填项'})return jsonify(data)# 文件上传的post接口
@app.route("/post_file",methods=['post'])
def post_file():# 获取需要上传的文件file = request.files.get('files')# 获取文件名filename = file.filename# 上传文件保存路径和格式(保证文件格式正常,使用切片的方式分段获取)with open("D:\\"+filename.split(".")[0]+"_"+str(int(time.time()))+"."+filename.split(".")[1],"wb") as f:f.write(file.read())return filename +'上传成功'if __name__ == '__main__':app.run()