前言
记录一些学习经验、遇到的问题
一、基础设置
执行文件目录下需要存在template文件夹,如return render_template(“hello.html”)的html文件需要存放在template文件夹里。
from flask import Flask, render_template, send_file, Response
app = Flask(__name__)
#默认路径
@app.route('/')
def hello_world():
return render_template("hello.html")
#其他路径
@app.route('/test1')
def test1():
return render_template("test1.html")
if __name__ == '__main__':
app.run(debug=True)
二、遇到的问题
1.只能通过127.0.0.1:5000登录,不能直接使用本机IP登录
解决方法:设置主机IP和端口号
app.run(host = '0.0.0.0' ,port = 5000, debug = 'True')
2.访问网址直接输出excel文件,而不保存本地
from io import BytesIO
from flask import Flask, render_template, send_file, Response
import os
from openpyxl import Workbook
app = Flask(__name__)
#文件下载
@app.route('/')
def test4():
#生成excel文件数据
wb = Workbook()
ws = wb.worksheets[0]
ws.cell(1, 1, "时间段")
ws.cell(1, 2, "日期")
ws.cell(1, 3, "时间")
ws.cell(1, 4, "工号")
ws.cell(1, 5, "姓名")
ws.cell(2, 1, "上午")
ws.cell(2, 2, "2022-9-15")
ws.cell(2, 3, "12:11:24")
ws.cell(2, 4, "123456789")
ws.cell(2, 5, "测试")
#保存为流
sio = BytesIO()
wb.save(sio)
response = Response()
response.headers.add("Content-Type", "application/vnd.ms-excel")
#filename='123.xlsx'中123.xlsx是下载的文件
response.headers.add('Content-Disposition', 'attachment', filename='123.xlsx'.encode("utf-8").decode("latin1"))
sio.seek(0)
response.data = sio.getvalue()
return response
if __name__ == '__main__':
app.run(debug=True)