Skip to content

Commit

Permalink
feat: Implements BaseRepository and BaseService
Browse files Browse the repository at this point in the history
  • Loading branch information
drorganvidez committed Feb 19, 2024
1 parent 45fa040 commit 1bd7d83
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 56 deletions.
12 changes: 0 additions & 12 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,18 +66,6 @@ def load_user(user_id):
def inject_flask_app_name():
return dict(FLASK_APP_NAME=os.getenv('FLASK_APP_NAME'))

# Injecting methods
@app.context_processor
def handle_service_response(result, errors, success_url, success_msg, error_template, form):
if result:
flash(success_msg, 'success')
return redirect(url_for(success_url))
else:
for error_field, error_messages in errors.items():
for error_message in error_messages:
flash(f'{error_field}: {error_message}', 'error')
return render_template(error_template, form=form)

return app


Expand Down
9 changes: 5 additions & 4 deletions app/blueprints/profile/routes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from flask import request, render_template, flash, redirect, url_for
from flask import request, render_template, flash, redirect, url_for, current_app
from flask_login import login_required

from app.blueprints.profile import profile_bp
Expand All @@ -8,14 +8,15 @@
from app.blueprints.profile.services import UserProfileService



@profile_bp.route('/profile/edit', methods=['GET', 'POST'])
@login_required
def edit_profile():
form = UserProfileForm()
service = UserProfileService()
if request.method == 'POST':

service = UserProfileService()
result, errors = service.update_profile(get_authenticated_user_profile().id, form)
return handle_service_response(result, errors, 'profile.view_profile', 'Profile updated successfully', 'profile/edit.html', form)
return service.handle_service_response(result, errors, 'profile.edit_profile', 'Profile updated successfully',
'profile/edit.html', form)

return render_template('profile/edit.html', form=form)
4 changes: 3 additions & 1 deletion app/blueprints/profile/services.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from app.blueprints.profile.repositories import UserProfileRepository
from app.services.BaseService import BaseService

from flask import current_app


class UserProfileService(BaseService):
def __init__(self):
Expand All @@ -11,4 +13,4 @@ def update_profile(self, user_profile_id, form):
updated_instance = self.update(user_profile_id, **form.data)
return updated_instance, None
else:
return None, form.errors
return None, form.errors
41 changes: 19 additions & 22 deletions app/blueprints/profile/templates/profile/edit.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,29 @@

<h1 class="h3 mb-3">Edit profile</h1>

{% with messages = get_flashed_messages() %}
{% if messages %}

<div class="row">
<div class="col-12 mb-3">
<div class="alert alert-success" role="alert">
<div class="alert-message">

<h4 class="alert-heading"><i class="align-middle" data-feather="pocket"></i>
The operation was successfully completed
</h4>
<p class="p-0 m-0">
{% for message in messages %}
{{ message }}
<br>
{% endfor %}
</p>
</div>
</div>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="row">
<div class="col-12 mb-3">
<!-- Aquí se elige la clase en función de la categoría del mensaje -->
<div class="alert alert-{{ category }}" role="alert">
<div class="alert-message">
{% if category == 'success' %}
<h4 class="alert-heading"><i class="align-middle" data-feather="check-circle"></i> Success</h4>
{% elif category == 'error' %}
<h4 class="alert-heading"><i class="align-middle" data-feather="x-circle"></i> Error</h4>
{% endif %}
<p style="margin-bottom: 0px">{{ message }}</p>
</div>

</div>
</div>

{% endif %}
</div>
{% endfor %}
{% endif %}
{% endwith %}


<div class="row">

<div class="col-12 col-lg-6">
Expand Down
37 changes: 20 additions & 17 deletions app/repositories/BaseRepository.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,37 @@
from flask_sqlalchemy import SQLAlchemy
from typing import TypeVar, Generic, Optional

db = SQLAlchemy()
import app

T = TypeVar('T')

class BaseRepository:
def __init__(self, model):

class BaseRepository(Generic[T]):
def __init__(self, model: T):
self.model = model

def create(self, **kwargs):
instance = self.model(**kwargs)
db.session.add(instance)
db.session.commit()
def create(self, **kwargs) -> T:
instance: T = self.model(**kwargs)
app.db.session.add(instance)
app.db.session.commit()
return instance

def get_by_id(self, id):
return self.model.query.get(id)
def get_by_id(self, id: int) -> Optional[T]:
instance: Optional[T] = self.model.query.get(id)
return instance

def update(self, id, **kwargs):
instance = self.get_by_id(id)
def update(self, id: int, **kwargs) -> Optional[T]:
instance: Optional[T] = self.get_by_id(id)
if instance:
for key, value in kwargs.items():
setattr(instance, key, value)
db.session.commit()
app.db.session.commit()
return instance
return None

def delete(self, id):
instance = self.get_by_id(id)
def delete(self, id: int) -> bool:
instance: Optional[T] = self.get_by_id(id)
if instance:
db.session.delete(instance)
db.session.commit()
app.db.session.delete(instance)
app.db.session.commit()
return True
return False
13 changes: 13 additions & 0 deletions app/services/BaseService.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from flask import flash, redirect, url_for, render_template


class BaseService:
def __init__(self, repository):
self.repository = repository
Expand All @@ -13,3 +16,13 @@ def update(self, id, **kwargs):

def delete(self, id):
return self.repository.delete(id)

def handle_service_response(self, result, errors, success_url_redirect, success_msg, error_template, form):
if result:
flash(success_msg, 'success')
return redirect(url_for(success_url_redirect))
else:
for error_field, error_messages in errors.items():
for error_message in error_messages:
flash(f'{error_field}: {error_message}', 'error')
return render_template(error_template, form=form)

0 comments on commit 1bd7d83

Please sign in to comment.