赞
踩
目录
3. 创建一个post请求,默认可以使用params和表单传参
- from flask import Flask, request
-
- # 初始化一个flask的对象
- app = Flask(__name__)
-
- @app.route("/")
- def a():
- return "简单接口" # 注意一定要有返回
-
- if __name__ == '__main__':
- app.run()
- 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()
- 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()
- import time
-
- from 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.json
-
- if 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()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。