随笔记录防止后面用到找不到资源
<form action="/addteacher" method="post" enctype="multipart/form-data">
enctype选用multipart/form-data否则报错
图片名采用时间戳+随机数写法,保证不重名
读入了两张图片,所以代码看着重复的地方可以砍一半
basedir = os.path.abspath(os.path.dirname(__file__))
@app.route('/addteacher', methods=['POST'])
def add_And_Show_Teacher():
if request.method == 'POST':
dic = {}
tname = request.form.get('tname')
ImgData = request.files['tpic']
InfoData = request.files['tinfo']
tcommon = request.form.get('common')
# # 设置图片的保存路径
path = basedir + '/static/pic/addteacher/'
# # 获取图片名及后缀名
timgname = ImgData.filename
iimgname = InfoData.filename
# # 把文件名打乱,避免save函数重名覆盖问题 时间戳加随机数
splittname = os.path.splitext(timgname)[0] # # 文件名
tsuffix = os.path.splitext(timgname)[1] # # 后缀
splittname = int(time.time()) + random.randint(0, 99999)
timgname = str(splittname) + tsuffix
isplittname = os.path.splitext(iimgname)[0] # # 文件名
isuffix = os.path.splitext(iimgname)[1] # # 后缀
isplittname = int(time.time()) + random.randint(0, 99999)
iimgname = str(isplittname) + isuffix
# # 图片path和名称组成图片的保存路径
tea_path = path + timgname
info_path = path + iimgname
# # 保存图片路径
ImgData.save(tea_path)
InfoData.save(info_path)
turl = '/static/pic/addteacher/' + timgname
iurl = '/static/pic/addteacher/' + iimgname
global tlst # # 解决退出登录再添加教师数据不保留问题,先读后写,即使退出登录再登陆也能保留数据
with open('teacher_info.txt', 'r') as f:
if f.read() == '':
pass
else:
f.seek(0)
tlst = eval(f.read())
dic['name'] = tname
dic['turl'] = '..' + turl # # 本项目的完整路径,上级目录用../
dic['iurl'] = '..' + iurl
dic['common'] = tcommon
dic['authorname'] = session['username'] # # 保存是谁添加的老师,后面进行注销的时候一次性删完
dic['id'] = tname + str(int(time.time())) # # 老师名字加时间戳,解决重名问题
tlst.append(dic)
with open('teacher_info.txt', 'w') as f:
f.write(str(tlst))
with open('teacher_info.txt', 'r') as f:
if f.read() == '':
pass
else:
f.seek(0)
tealst = eval(f.read())
vist = {} # # 记录访问次数和时间
# # 教师姓名对应添加时间
# # count+教师姓名对应访问次数
# # name对应是谁添加的教师
vist['count' + tname] = 0 # # 初始化访问次数
vist[tname] = datetime.datetime.now().strftime('%F %T') # # 获取提交老师的时间,并保存下来
vist['count'+tname] += 1
vist['name'] = session['username'] # # 记录是谁添加的
time_vist.append(vist) # # 记录第一次访问的时间和次数,次数刚创建时为1
# # 写入文件
with open('time_vist.txt', 'w') as f:
f.write(str(time_vist))
return redirect(url_for('go_First_Page', tealst=tealst))