英文:
Flask_SQLAlchemy Initialization, Sessions vs Engine
问题
新手使用Flask和Web应用程序,有人可以帮助我了解会话如何处理吗?
在这里,我正在初始化Flask应用程序,然后将应用程序传递给SQLAlchemy。
我理解的是,正在创建数据库引擎,以便我可以开始对我的数据库运行事务。当前的代码运行并按预期执行,但我不确定如果为每个事务创建多个会话是否是一个好方法。
在lookup_user()函数的一部分中,我需要执行多个数据库操作,以便在系统中添加输入的用户或更新现有用户。是否有更好的方法来处理Flask-SQLAlchemy的会话?
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = pg_dbstring
db = SQLAlchemy(app)
@app.route('/player', methods=['POST'])
def lookup_user():
if request.method == 'POST':
entered_user = request.form["username"]
user_check = db.session.query(Users).filter(Users.username == request.form["username"]).count()
if user_check > 0:
user_id = db.session.query(Users).filter(Users.username == request.form["username"]).with_entities(Users.userid)
...
继续的代码
英文:
New to flask and web apps, can anyone help me understand how sessions will be handled?
Here I am initializing the flask app and then passing the app to SQLAlchemy.
My understanding is the db engine is being created so I can then start running transactions against my DB. The current code runs and does what is expected but I am not sure if this is a good approach if multiple sessions are being created for each transaction.
In part of the lookup_user() function, I am having to do multiple DB actions in order to add the entered user or update the existing one in the system. Is there a better way to handle sessions with flask_sqlalchemy?
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = pg_dbstring
db = SQLAlchemy(app)
@app.route('/player', methods=['POST'])
def lookup_user():
if request.method == 'POST':
entered_user = request.form["username"]
user_check = db.session.query(Users).filter(Users.username == request.form["username"]).count()
if user_check > 0:
user_id = db.session.query(Users).filter(Users.username == request.form["username"]).with_entities(Users.userid)
...
Code continues
答案1
得分: 1
Flask_Sqlalchemy会为您处理会话,详见应用上下文。您的会话与您的请求相关联,因此虽然您可以在一个请求中执行多个事务,但不会创建多个会话。
英文:
Flask_Sqlalchemy takes care of the sessions for you, see app context. Your session is scoped to your request, so while you can do multiple transactions per request, you wont create multiple sessions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论