Skip to content

Commit

Permalink
Merge pull request #7 from hexlet-components/crud-delete
Browse files Browse the repository at this point in the history
init lesson crud-delete
  • Loading branch information
sgmdlt authored Aug 14, 2024
2 parents eb57847 + c74bfe4 commit 0f1de69
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 21 deletions.
15 changes: 10 additions & 5 deletions example.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,19 +87,24 @@ def users_patch(id):
user=user,
errors=errors,
), 422

user['name'] = data['name']
user['email'] = data['email']
repo.save(user)
data['id'] = user['id']
repo.save(data)
flash('Пользователь успешно обновлен', 'success')
return redirect(url_for('users_get'))


@app.route('/users/<id>/delete', methods=['POST'])
def users_delete(id):
repo = UserRepository()
repo.destroy(id)
flash('Пользователь удален', 'success')
return redirect(url_for('users_get'))


@app.route('/users/<id>')
def users_show(id):
repo = UserRepository()
user = repo.find(id)
print(user)
return render_template(
'users/show.html',
user=user,
Expand Down
5 changes: 5 additions & 0 deletions templates/users/show.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,9 @@

<a href="{{ url_for('users_edit', id=user.id) }}">Редактировать пользователя</a>

<form action="{{ url_for('users_delete', id=user.id) }}" method="post"
onsubmit="return confirm('Вы уверены что хотите удалить пользователя? Это действие нельзя отменить.');">
<input type="submit" value="Удалить пользователя">
</form>

<p><a href="{{ url_for('users_get') }}">Назад к списку пользователей</a></p>
40 changes: 24 additions & 16 deletions user_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
import sys
import uuid


class UserRepository():
class UserRepository:
def __init__(self):
self.users = json.load(open("./users.json", 'r'))

Expand All @@ -13,27 +12,36 @@ def get_content(self):
def find(self, id):
try:
for user in self.users:
if id == str(user['id']):
if str(id) == str(user['id']):
return user
except KeyError:
sys.stderr.write(f'Wrong post id: {id}')
raise

def save(self, new_user):
def save(self, user_data):
# repository should know nothing about validation in outer layer
if not (new_user.get('name') and new_user.get('email')):
raise Exception(f'Wrong data: {json.loads(new_user)}')
# replace already existed user
if new_user.get('id'):
for current in self.users:
if new_user['id'] == current['id']:
del current
break
self.users.append(new_user)
# or add new
else:
if not (user_data.get('name') and user_data.get('email')):
raise Exception(f'Wrong data: {json.dumps(user_data)}')

if 'id' not in user_data:
new_user = user_data.copy()
new_user['id'] = str(uuid.uuid4())
self.users.append(new_user)
else:
for i, existing_user in enumerate(self.users):
if str(user_data['id']) == str(existing_user['id']):
self.users[i] = user_data
break
else:
raise Exception(f"User with id {user_data['id']} not found")

with open("./users.json", "w") as f:
json.dump(self.users, f)

return user_data['id']

def destroy(self, id):
current_user = self.find(id)
self.users.remove(current_user)
with open("./users.json", "w") as f:
json.dump(self.users, f)
return new_user['id']

0 comments on commit 0f1de69

Please sign in to comment.