用Flask定制指令上传Excel数据到数据库

用Flask定制指令上传Excel数据到数据库

假设现在有一张员工信息data.xlsx文件

image-20240618104947478

使用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

上传成功

image-20240618105358496

  • 15
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flask中,可以使用AJAX技术将前端页面中的数据提交到后端Flask应用程序,然后将数据插入到数据库中。下面是一个简单的示例代码: 1.前端页面代码: ```html <!DOCTYPE html> <html> <head> <title>Flask AJAX提交数据数据库</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> </head> <body> <form id="myform"> <input type="text" name="name" placeholder="姓名"><br> <input type="text" name="age" placeholder="年龄"><br> <input type="text" name="gender" placeholder="性别"><br> <button type="button" onclick="submitForm()">提交</button> </form> <script> function submitForm() { var formdata = $("#myform").serialize(); $.ajax({ url: "/submit", type: "POST", data: formdata, success: function(response) { alert(response); }, error: function(xhr) { alert(xhr.responseText); } }); } </script> </body> </html> ``` 2.后端Flask应用程序代码: ```python from flask import Flask, render_template, request, jsonify import pymysql app = Flask(__name__) @app.route("/") def index(): return render_template("index.html") @app.route("/submit", methods=["POST"]) def submit(): name = request.form.get("name") age = request.form.get("age") gender = request.form.get("gender") # 连接数据库 conn = pymysql.connect(host="localhost", user="root", password="123456", database="testdb", charset="utf8") cursor = conn.cursor() # 插入数据 try: sql = "INSERT INTO student(name, age, gender) VALUES (%s, %s, %s)" cursor.execute(sql, (name, age, gender)) conn.commit() return jsonify({"status": 0, "msg": "提交成功"}) except Exception as e: conn.rollback() return jsonify({"status": -1, "msg": "提交失败,错误信息:%s" % e}) finally: cursor.close() conn.close() if __name__ == "__main__": app.run(debug=True) ``` 在上面的代码中,前端页面中的数据会通过AJAX的方式提交到`/submit`路由,然后在后端Flask应用程序中将数据插入到MySQL数据库中。当数据插入成功时,返回JSON格式的数据,否则返回错误信息。最后,在`if __name__ == "__main__":`的条件下运行Flask应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值