官方文档

flask: https://dormousehole.readthedocs.io/en/latest/

flask-sqllite:https://dormousehole.readthedocs.io/en/latest/patterns/sqlite3.html

jinja: https://jinja.palletsprojects.com/en/stable/templates/

 

步骤

1、搭建项目结构

image

2、定义工厂函数,创建flask实例

3、db.py 定义数据库连接、关闭

4、schema.sql,编写sql创建表

5、db.py 定义读取schema.sql,执行sql

6、写视图函数

7、写模版文件、静态文件

8、启动:

waitress-serve --call 'flaskr:create_app'

python+flask连接mysql数据库

# 创建数据库连接
def get_db():
    """
    获取或创建MySQL数据库连接
    使用Flask的g对象存储连接,避免重复创建
    """
    if 'db' not in g:
        try:
            g.db = mysql.connect(
                user='root',
                password='MyPassword123!',
                host='localhost',
                database='blog',
                raise_on_warnings=True
            )


        except Error as e:
            print(f"数据库连接失败: {e}")
            raise

    return g.db


def close_db(e=None):
    db = g.pop('db', None)

    if db is not None:
        db.close()

操作数据库

        db = get_db()
        cursor = db.cursor(dictionary=True)
        cursor.execute(
            'SELECT * FROM user WHERE username = %s', (username,)
        )
        user = cursor.fetchone()
        # 确保关闭游标
        cursor.close()

 

posted @ 2025-08-22 14:31  Alieen617  阅读(9)  评论(0)    收藏  举报