首页 > 解决方案 > 如何使用用户名来自mysql数据库的flask创建会话

问题描述

if (username==aname or username==aemail) and userpass==apass:
            session['user'] = username

这里 aname 和 apass 是来自数据库的用户名和密码

标签: pythonmysqlflask

解决方案


I suggest creating a contextmanager to handle database session:

@contextmanager
def get_db_session(aname: str, apass: str):
    connection = None

    try:
        connection = mysql.connector.connect(host='localhost',
                                            database='your_database',
                                            user=aname,
                                            password=apass)
        if connection.is_connected():
            yield connection
    except Exception as e:
        # Catch more appropriate exception
        pass    
    finally:
        if connection.is_connected():
            # Remember to close database
            cursor.close()
            connection.close()

To create a db session:

with get_db_session() as session:
    # Perform tasks with your database 

Connection is closed as soon as the code exits the context (as shown in finally block in get_db_session())

Furthermore, all database connection exceptions can be handled there. Note: code syntax may not be correct, but you get the general idea


推荐阅读