flask定制Excel命令

定制excel命令并插入到数据库中

import os

from flask import Flask
from flask.cli import AppGroup
import click
import pymysql
from openpyxl import load_workbook

app = Flask(__name__)


@app.cli.group()
def excel():
    """Excel related commands."""
    pass


@excel.command("import")
@click.argument("excel_path", type=click.Path(exists=True))
def create_user(excel_path):
    """Import data from Excel to the 'user' table."""
    try:
        # 数据库连接配置
        db_config = {
            "host": "127.0.0.1",
            "user": "root",
            "password": "123456",
            "db": "flask_base",
            "port": 3307,
        }

        # 连接数据库
        with pymysql.connect(**db_config) as connection:
            with connection.cursor() as cursor:
                # 加载Excel文件
                if not os.path.isfile(excel_path) or not excel_path.endswith(('.xlsx', '.xls')):
                    click.echo("Invalid Excel file path or format.")
                    return

                wb = load_workbook(excel_path)
                sheet = wb.active

                # 假设Excel的第一行为表头,从第一行开始为数据
                for row in sheet.iter_rows(min_row=1, values_only=True):
                    name, email, ctime = row  # 根据实际Excel结构调整
                    sql = "INSERT INTO user (name, email, ctime) VALUES (%s, %s, %s)"
                    cursor.execute(sql, (name, email, ctime))

                # 提交事务
                connection.commit()
                click.echo("Data imported successfully.")
    except Exception as e:
        click.echo(f"An error occurred: {e}")


if __name__ == "__main__":
    app.run()
#执行  flask --app app.py excel import .\user.xlsx    

image-20240614172402432

image-20240614172502135

django中自定制命令

# 1 app下新建文件夹
	management和commands
# 2 在该文件夹下新建py文件,随便命名(命令名)

# 3 在py文件中写代码
from django.core.management.base import BaseCommand
class Command(BaseCommand):
    help = '命令提示'

    def add_arguments(self, parser):
        parser.add_argument('path', nargs='*', type=str,)

    def handle(self, *args, **kwargs):
        print('开始导入')
        print(args)
        print(kwargs)
# 4 使用命令
python manage.py  py文件(命令名)
image-20240614200208119

缓存到redis里面

from flask import Flask
from flask_caching import Cache,SimpleCache

config = {
    "CACHE_REDIS_URL": "redis://localhost:6379/0",  # Redis服务器的URL和数据库号,默认端口6379,数据库0
    "DEBUG": True,  # some Flask specific configs
    "CACHE_TYPE": "redis",  # Flask-Caching related configs ,可以缓存到redis
    "CACHE_DEFAULT_TIMEOUT": 300
}
# 初始化Flask应用
app = Flask(__name__)
app.config.from_mapping(config)

# 初始化缓存
cache = Cache(app)

@app.route('/')
def index():
    cache.set('name', 'hope')
    return 'index'

#取值
@app.route('/get')
def get():
    res=cache.get('name')
    return res


if __name__ == '__main__':
    app.run()
image-20240614184807330 image-20240614184735767

posted @ 2024-06-27 19:09  -半城烟雨  阅读(2)  评论(0编辑  收藏  举报