python flask


前言

记录一些学习经验、遇到的问题


一、基础设置

执行文件目录下需要存在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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值