python - 如何使用用户名来自mysql数据库的flask创建会话
问题描述
if (username==aname or username==aemail) and userpass==apass:
session['user'] = username
这里 aname 和 apass 是来自数据库的用户名和密码
解决方案
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
推荐阅读
- node.js - 如果条件与反应量
- ios - 如何解析 JSON 以填充 tableview 部分和 indexpath?
- python - 在 python 中使用 re 时忽略大小写的最快方法是什么?
- ruby-on-rails - 使用 Rails 中的 Turbolinks 在自定义控制器中形成表单
- java - 将 JUnit 5 参数注入 @BeforeEach
- linux - 如何使用 inotifywait 监视带有时间和文件的目录?
- intellij-idea - IntelliJ:在多行的开头添加相同的文本?
- reactjs - 使用 mui-rte 进行聊天消息输入时如何将内部状态设置为空字符串
- algorithm - Big -oh 的定义中的 No 是否应该是两条曲线的交点?
- javascript - 我可以在 Javascript 中制作 Javascript 吗?