用Flask定制指令上传Excel数据到数据库
假设现在有一张员工信息data.xlsx
文件
使用SQLAlchemy创表
# ExcelModel.py
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
class Emp(Base):
__tablename__ = 'emp'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(32), nullable=False, index=True)
age = Column(Integer, nullable=False)
phone = Column(Integer, nullable=False, index=True)
if __name__ == '__main__':
engine = create_engine("mysql+pymysql://root:1234@localhost/flaskdemo",
max_overflow=0, # 超过连接池大小外最多创建的连接
pool_size=5, # 连接池大小
pool_timeout=30, # 池中没有线程最多等待的时间,否则报错
pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置)
)
Base.metadata.create_all(engine) # 创建表
定义上传类
需要安装pandas模块和openpyxl库
pip install pandas
pip install openpyxl
# getexcel.py
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from ExcelModel import Emp
class ExcelPool:
def __init__(self, file):
self.file = file
self.engine = create_engine("mysql+pymysql://root:7997@localhost/flaskdemo",
max_overflow=0, # 超过连接池大小外最多创建的连接
pool_size=5, # 连接池大小
pool_timeout=30, # 池中没有线程最多等待的时间,否则报错
pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置)
)
def xlsx(self):
# 读取Excel文件
try:
df = pd.read_excel(self.file, sheet_name='Sheet1')
for i in range(len(df)):
emp = Emp(name=df['姓名'][i],
age=df['年龄'][i],
phone=df['手机号'][i],)
session = Session(self.engine)
session.add(emp)
session.commit()
except FileNotFoundError:
print('文件不存在')
定制指令
# FlaskDemo
import click
from flask import Flask
from getexcel import ExcelPool
app = Flask(__name__)
# 关键字绑定i
@click.argument('file')
@app.cli.command('create_emp')
# 将i作为参数
def create_user(file):
# 传入文件名
f = f'{file}.xlsx'
ExcelPool(f).xlsx()
if __name__ == '__main__':
app.run(debug=True)
执行命令
flask --app FlaskDemo:app create_emp data
上传成功