本篇内容是本人是学校组织实训期间写的内容,一天的写项目事件,要和小伙伴配合完成一个集vue、python技术flask的前后端交互项目,对于我这个刚刚入门的小白还是有难度的。期间不断地去问老师,总算是写出来了三四个接口,主要实现的功能就是增加、数据展示、根据特定字段去搜索、登录。从大一开始就只学习前端的经历让我这次给前端提供接口变得更加有成就感,就很nice,以下就是我写的代码。
import copy
import json
import pandas as pd
import xlwt,xlrd
from xlutils.copy import copy
from flask import Blueprint, request, render_template, jsonify, redirect
detail = Blueprint('detail', __name__)
@detail.route("/sureLogin/<user>/<pwd>",methods=['POST'])
def login_Sure(user,pwd):
if user=="hcy" and pwd=="123":
return {
"msg":"登录成功!"
}
else:
error='用户名或密码错误'
return {
"msg": error
}
# # 获取数据——————————————————————————————————————
def read_xlsx_data(file_path):
data = pd.read_excel(file_path)
keys =['SuperType','area','name','cost','good','grossMargin','profit','num']
datas = []
for da in data.values:
value = dict(zip(keys,da))
datas.append(value)
return datas
@detail.route('/index',methods=['GET'])
def get_coffe_data():
file_path = '某咖啡公司销售数据 - 副本.xlsx'
data = read_xlsx_data(file_path)
return data
# 查询数据————————————————————————————————————————
@detail.route('/search/<content>',methods=['GET'])
def search_coffe_data(content):
file_path = '某咖啡公司销售数据 - 副本.xlsx'
data = read_xlsx_data(file_path)
res=[]
Allnums=0
for i in data:
if content==i["name"]:
res.append(i)
Allnums+=1
if len(res)==0:
return {
"code":200,
"msg":"没有数据",
"num":0
}
elif len(res)!=0:
return {
"code": 200,
"msg": "有数据",
"data": res,
"nume":Allnums
}
else:
return {
"code": 500,
"msg": "错误",
}
#增加数据——————————————————————————————————————————
@detail.route('/add/<SuperType>/<area>/<name>/<cost>/<good>/<grossMargin>/<profit>/<num>',methods=['POST'])
def add_coffe_data(SuperType,area,name,cost,good,grossMargin,profit,num):
file_path = '某咖啡公司销售数据 - 副本.xlsx'
data = read_xlsx_data(file_path)
newData=[SuperType,area,name,cost,good,grossMargin,profit,num]
# data.append(newData)
xls = xlrd.open_workbook(file_path) # 得到文件
excel = copy(wb=xls) # 完成xlrd对象向xlwt对象转换
excel_table = excel.get_sheet(0) # 获得要操作的页
table = xls.sheets()[0]
nrows = table.nrows # 获得行数
ncols=0
for value in newData:
excel_table.write(nrows, ncols, value) # 因为单元格从0开始算,所以row不需要加一
ncols = ncols + 1
excel.save(file_path)
return {
"code":200,
"msg":"添加成功"
}