fenya123 / forum123

Flask application written for educational purposes.
http://193.124.115.171/
1 stars 1 forks source link

62: Encapsulate models creation #64

Closed EugeneTurkin closed 1 year ago

EugeneTurkin commented 1 year ago

In order to separate application layers we need to move all "low-level" database related code into models.

In the scope of this task we need to encapsulate all models creation functionality into models methods. We need to get rid of using session.add() and session.commit() in our routes, because this is a database layer responsibility.

Below are changes we expect to be in routes.py. "Before" designates what code we have now, "After" designates what code we want to see after this refactoring.


Before:

@bp.route("/registration", methods=["POST", "GET"])
def registration() -> str:
    ...
    user = User(username=form.username.data)
    user.set_password(form.password.data)
    session.add(user)
    session.commit()
    ...

After:

@bp.route("/registration", methods=["POST", "GET"])
def registration() -> str:
    ...
    User.create_user(form.username.data, form.password.data)
    ...

Before:

@bp.route("/login", methods=["POST", "GET"])
def login() -> str | Response:
    ...
    session_id = str(uuid.uuid4())
    user_session = UserSession(session_id=session_id, user_id=user.id)
    session.add(user_session)
    session.commit()
    response = make_response(redirect(url_for("routes.topics")))
    response.set_cookie("session_id", session_id)
    ...

After:

@bp.route("/login", methods=["POST", "GET"])
def login() -> str | Response:
    ...
    user_session = user.create_session()
    response = make_response(redirect(url_for("routes.topics")))
    response.set_cookie("session_id", user_session.session_id)
    ...

Before:

@bp.route("/topics/create", methods=["POST", "GET"])
def create_topic() -> str | Response:
    ...
    new_topic = Topic(title=form.title.data, description=form.description.data, author_id=current_user.id)
    session.add(new_topic)
    session.commit()
    ...

After:

@bp.route("/topics/create", methods=["POST", "GET"])
def create_topic() -> str | Response:
    ...
    Topic.create_topic(form.title.data, form.description.data, current_user.id)
    ...

Before:

@bp.route("/topics/<int:topic_id>/posts/create", methods=["POST", "GET"])
def create_post(topic_id: int) -> str | Response:  # noqa: CFQ004
    ...
    new_post = Post(body=form.body.data, author_id=current_user.id, topic_id=topic.id)
    session.add(new_post)
    session.commit()
    ...

After:

@bp.route("/topics/<int:topic_id>/posts/create", methods=["POST", "GET"])
def create_post(topic_id: int) -> str | Response:  # noqa: CFQ004
    ...
    topic.create_post(form.body.data, current_user.id, topic)
    ...