Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 36 additions & 37 deletions example.py
Original file line number Diff line number Diff line change
@@ -1,123 +1,122 @@
import os

import psycopg2
from flask import (
get_flashed_messages,
flash,
Flask,
flash,
get_flashed_messages,
redirect,
render_template,
request,
url_for
url_for,
)

from user_repository import UserRepository

app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
app.config['DATABASE_URL'] = os.getenv('DATABASE_URL')
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
app.config["DATABASE_URL"] = os.getenv("DATABASE_URL")


conn = psycopg2.connect(app.config['DATABASE_URL'])
conn = psycopg2.connect(app.config["DATABASE_URL"])
repo = UserRepository(conn)


@app.route('/')
@app.route("/")
def index():
return render_template('home.html')
return render_template("home.html")


@app.route('/users/')
@app.route("/users/")
def users_get():
messages = get_flashed_messages(with_categories=True)
term = request.args.get('term', '')
term = request.args.get("term", "")
if term:
users = repo.get_by_term(term)
else:
users = repo.get_content()
return render_template(
'users/index.html',
users=users,
search=term,
messages=messages
"users/index.html", users=users, search=term, messages=messages
)


@app.post('/users')
@app.post("/users")
def users_post():
user_data = request.form.to_dict()
errors = validate(user_data)
if errors:
return render_template(
'users/new.html',
"users/new.html",
user=user_data,
errors=errors,
)
repo.save(user_data)

flash('Пользователь успешно добавлен', 'success')
return redirect(url_for('users_get'), code=302)
flash("Пользователь успешно добавлен", "success")
return redirect(url_for("users_get"), code=302)


@app.route('/users/new')
@app.route("/users/new")
def users_new():
user = {'name': '', 'email': ''}
user = {"name": "", "email": ""}
errors = {}
return render_template(
'users/new.html',
"users/new.html",
user=user,
errors=errors,
)


@app.route('/users/<id>/edit')
@app.route("/users/<id>/edit")
def users_edit(id):
user = repo.find(id)
errors = {}

return render_template(
'users/edit.html',
"users/edit.html",
user=user,
errors=errors,
)


@app.route('/users/<id>/patch', methods=['POST'])
@app.route("/users/<id>/patch", methods=["POST"])
def users_patch(id):
user = repo.find(id)
data = request.form.to_dict()

errors = validate(data)
if errors:
return render_template(
'users/edit.html',
"users/edit.html",
user=user,
errors=errors,
), 422
data['id'] = user['id']
data["id"] = user["id"]
repo.save(data)
flash('Пользователь успешно обновлен', 'success')
return redirect(url_for('users_get'))
flash("Пользователь успешно обновлен", "success")
return redirect(url_for("users_get"))


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


@app.route('/users/<id>')
@app.route("/users/<id>")
def users_show(id):
user = repo.find(id)
return render_template(
'users/show.html',
"users/show.html",
user=user,
)


def validate(user):
errors = {}
if not user['name']:
errors['name'] = "Can't be blank"
if not user['email']:
errors['email'] = "Can't be blank"
if not user["name"]:
errors["name"] = "Can't be blank"
if not user["email"]:
errors["email"] = "Can't be blank"
return errors
26 changes: 13 additions & 13 deletions user_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ def get_content(self):
cur.execute("SELECT * FROM users")
return cur.fetchall()

def get_by_term(self, search_term=''):
def get_by_term(self, search_term=""):
with self.conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute("SELECT * FROM users WHERE name ILIKE %s", (f'%{search_term}%',))
cur.execute(
"SELECT * FROM users WHERE name ILIKE %s",
(f"%{search_term}%",),
)
return cur.fetchall()

def find(self, id):
Expand All @@ -21,33 +24,30 @@ def find(self, id):
return cur.fetchone()

def save(self, user_data):
if 'id' not in user_data:
if "id" not in user_data:
id = self._create(user_data)
else:
id = self._update(user_data)
return id


def _update(self, user_data):
with self.conn.cursor() as cur:
cur.execute(
"UPDATE users SET name = %s, email = %s WHERE id = %s",
(user_data['name'], user_data['email'], user_data['id'])
)
"UPDATE users SET name = %s, email = %s WHERE id = %s",
(user_data["name"], user_data["email"], user_data["id"]),
)
self.conn.commit()
return user_data['id']

return user_data["id"]

def _create(self, user_data):
with self.conn.cursor() as cur:
cur.execute(
"INSERT INTO users (name, email) VALUES (%s, %s) RETURNING id",
(user_data['name'], user_data['email'])
(user_data["name"], user_data["email"]),
)
user_data['id'] = cur.fetchone()[0]
user_data["id"] = cur.fetchone()[0]
self.conn.commit()
return user_data['id']

return user_data["id"]

def destroy(self, id):
with self.conn.cursor() as cur:
Expand Down
Loading