mirror of
https://github.com/avatao-content/test-tutorial-framework
synced 2024-11-14 02:57:18 +00:00
Improve db Session logic
This commit is contained in:
parent
ccf348e5c5
commit
d4f4d5b288
@ -14,16 +14,17 @@ session_factory = sessionmaker(
|
||||
|
||||
|
||||
@contextmanager
|
||||
def Session():
|
||||
session = session_factory()
|
||||
def Session(factory=session_factory):
|
||||
session = factory()
|
||||
try:
|
||||
yield session
|
||||
session.commit()
|
||||
except:
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
# session is closed by flask
|
||||
# finally:
|
||||
# session.close()
|
||||
|
||||
|
||||
Base = declarative_base()
|
||||
|
@ -1,8 +1,9 @@
|
||||
from os import urandom, getenv
|
||||
from functools import partial
|
||||
|
||||
from flask import Flask, render_template, request, session, url_for, g
|
||||
|
||||
from model import init_db, session_factory
|
||||
from model import init_db, session_factory, Session
|
||||
from user_ops import UserOps
|
||||
from errors import InvalidCredentialsError, UserExistsError
|
||||
|
||||
@ -20,6 +21,8 @@ def get_db_session():
|
||||
g.db_session = session_factory()
|
||||
return g.db_session
|
||||
|
||||
Session = partial(Session, get_db_session)
|
||||
|
||||
|
||||
@app.teardown_appcontext
|
||||
def close_db_session(err): # pylint: disable=unused-argument
|
||||
@ -31,9 +34,12 @@ def close_db_session(err): # pylint: disable=unused-argument
|
||||
def index():
|
||||
if request.method == 'POST':
|
||||
try:
|
||||
UserOps(request.form.get('username'),
|
||||
with Session() as db_session:
|
||||
UserOps(
|
||||
request.form.get('username'),
|
||||
request.form.get('password'),
|
||||
get_db_session()).authenticate()
|
||||
db_session
|
||||
).authenticate()
|
||||
except InvalidCredentialsError:
|
||||
return render_template('login.html', alert='Invalid credentials!')
|
||||
|
||||
@ -61,11 +67,12 @@ def register():
|
||||
return render_template('register.html', alert='Passwords do not match! Please try again.')
|
||||
|
||||
try:
|
||||
UserOps(
|
||||
request.form.get('username'),
|
||||
request.form.get('password'),
|
||||
get_db_session()
|
||||
).register()
|
||||
with Session() as db_session:
|
||||
UserOps(
|
||||
request.form.get('username'),
|
||||
request.form.get('password'),
|
||||
db_session
|
||||
).register()
|
||||
except UserExistsError:
|
||||
return render_template('register.html', alert='Username already in use.')
|
||||
|
||||
|
@ -62,6 +62,5 @@ class UserOps:
|
||||
passwordhash=PasswordHasher.hash(self.password)
|
||||
)
|
||||
self.db_session.add(user)
|
||||
self.db_session.commit()
|
||||
|
||||
self.log(f'User "{self.username}" registered!')
|
||||
|
Loading…
Reference in New Issue
Block a user