一、安装
pip install Flask
二、使用
1、初始化一个flask的对象
app = Flask(__name__)
2、引入装饰器,创建一个接口increaseAs
@app.route("/increaseAs")
def increaseAs():
a={"id": "A0000000001","errmsg":"成功"}
return a
if __name__ == '__main__':
app.run()
3、执行并调用
运行后,会有一个地址
* Running on http://127.0.0.1:5000
在postman中输入这个请求地址http://127.0.0.1:5000,拼接上接口路径名称/increaseAs,如:http://127.0.0.1:5000/increaseAs
发送请求后,接口返参将会返回a的数据
三、入参方式
1、模拟入参方式为params方式
# 引入装饰器,设置接口路径名称/increaseAs,设置接口请求方式methods @app.route("/increaseAs", methods=['GET', 'POST']) # 创建一个接口increaseAs def get_increaseAs(): # 设置入参,模拟入参方式为params方式 sellerAlbumId = request.value.get("sellerAlbumId") shop_name = request.value.get("shop_name") commodityId = request.value.get("commodityId") # 设置为空校验,sellerAlbumId必填 if sellerAlbumId is None or sellerAlbumId == "": a = {"sellerAlbumId": "商品id必填", "errmsg": "成功"} return a else: a = {"sellerAlbumId": sellerAlbumId, "errmsg": "成功"} return a
2、模拟入参方式为body,form-data/x-www-urlencoded方式
@app.route("/getPackageOrderByPage", methods=['GET', 'POST']) def getPackageOrderByPage(): sellerAlbumId = request.form("sellerAlbumId") shop_name = request.form("shop_name") commodityId = request.form("commodityId") picture=request.form("commodityId") a = {"sellerAlbumId": "商品id必填", "errmsg": "成功"} return a
3、入参方式为body,json参数的接口
@app.route("/get_body_json",methods=['GET','POST']) def get_body_json(): json = request.json return json
4、入参方式为body,file参数的接口
@app.route("/get_body_file",methods=['GET','POST']) def get_shop_pictures(): # 获取到上传的文件 shop_pictures = request.files["shop_picture"] #获取文件名 shop_picturesname = shop_pictures.filename #上传 with open("D:\\"+shop_picturesname.split(".")[0]+"_"+str(int(time.time()))+"."+shop_picturesname.split(".")[1],"wb") as f: f.write(shop_pictures.read()) #返回 return shop_picturesname+"上传成功"