Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

init lesson database #9

Merged
merged 1 commit into from
Aug 15, 2024
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
29 changes: 21 additions & 8 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,23 +1,36 @@
FROM python:3.12-slim

RUN apt-get update && apt-get install make -yqq \
RUN apt-get update && apt-get install -yqq \
make \
postgresql-15 \
sudo
sudo \
curl

RUN pip install poetry

ENV POETRY_VIRTUALENVS_IN_PROJECT=true

COPY ./pg_hba.conf /etc/postgresql/15/main/pg_hba.conf

WORKDIR /app

COPY . .
COPY pyproject.toml .

RUN poetry install

#USER postgres
COPY . .

COPY init.sql /docker-entrypoint-initdb.d/

# postgres config
RUN echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/15/main/pg_hba.conf && \
echo "listen_addresses='*'" >> /etc/postgresql/15/main/postgresql.conf

# create docker user and db
RUN service postgresql start && \
su postgres -c "psql --command \"CREATE USER docker WITH SUPERUSER PASSWORD 'docker';\"" && \
su postgres -c "createdb -O docker docker" && \
service postgresql stop

COPY run.sh ./run.sh
RUN chmod +x ./run.sh

#COPY ./run.sh .
#CMD ./run.sh
CMD ./run.sh
21 changes: 4 additions & 17 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,7 @@ run:
prod:
poetry run gunicorn --workers=4 --bind 0.0.0.0:$(PORT) example:app --log-file -

compose:
docker compose up

compose-setup: compose-build
docker compose run app make install

compose-build:
docker compose build

compose-down:
docker compose down -v

compose-dev:
docker compose run app make run

compose-bash:
docker compose run app bash
compose-production-run-app:
docker compose -p python_page_analyzer_ru-production -f docker-compose.production.yml down
docker compose -p python_page_analyzer_ru-production -f docker-compose.production.yml build
docker compose -p python_page_analyzer_ru-production -f docker-compose.production.yml up
10 changes: 6 additions & 4 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ services:
app:
build:
context: .
ports:
- 8000:8000
command: make prod
dockerfile: Dockerfile
environment:
DATABASE_URL: postgres://postgres:password@db:5432/postgres
DATABASE_URL: postgresql://docker:docker@localhost:5432/docker
PORT: 3000
SECRET_KEY: supersecretkey
ports:
- "3000:3000"
12 changes: 5 additions & 7 deletions example.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
from flask import (
get_flashed_messages,
flash,
Expand All @@ -10,7 +11,10 @@
from user_repository import UserRepository

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

repo = UserRepository(app.config['DATABASE_URL'])


@app.route('/')
Expand All @@ -22,7 +26,6 @@ def index():
def users_get():
messages = get_flashed_messages(with_categories=True)
term = request.args.get('term', '')
repo = UserRepository()
users = repo.get_content()
filtered_users = [user for user in users if term in user['name']]
return render_template(
Expand All @@ -43,7 +46,6 @@ def users_post():
user=user_data,
errors=errors,
)
repo = UserRepository()
repo.save(user_data)

flash('Пользователь успешно добавлен', 'success')
Expand All @@ -63,7 +65,6 @@ def users_new():

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

Expand All @@ -76,7 +77,6 @@ def users_edit(id):

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

Expand All @@ -95,15 +95,13 @@ def users_patch(id):

@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)
return render_template(
'users/show.html',
Expand Down
80 changes: 79 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ package-mode = false
python = "^3.10"
Flask = "^3.0.3"
gunicorn = "^23.0.0"
psycopg2-binary = "^2.9.9"

[tool.poetry.group.dev.dependencies]
flake8 = "^7.1.1"
Expand Down
15 changes: 9 additions & 6 deletions run.sh
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
#!/bin/bash

set -m
set -e

/usr/lib/postgresql/15/bin/postgres \
-D /var/lib/postgresql/15/main \
-c config_file=/etc/postgresql/15/main/postgresql.conf &
service postgresql start

sleep 5 && psql -a -f init.sql && make run
until su postgres -c "pg_isready"; do
echo "Waiting for postgres..."
sleep 2
done

fg %1
su postgres -c "psql -d docker -a -f /docker-entrypoint-initdb.d/init.sql"

make prod
63 changes: 39 additions & 24 deletions user_repository.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,47 @@
import json
import sys
import uuid
from flask import session
import psycopg2
from psycopg2.extras import RealDictCursor


class UserRepository():
def __init__(self):
if 'user' not in session:
session['user'] = {}
class UserRepository:
def __init__(self, db_url):
self.db_url = db_url

def get_connection(self):
return psycopg2.connect(self.db_url)

def get_content(self):
return session['user'].values()
with self.get_connection() as conn:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute("SELECT * FROM users")
return cur.fetchall()

def find(self, id):
try:
return session['user'][id]
except KeyError:
sys.stderr.write(f'Wrong user id: {id}')
raise
with self.get_connection() as conn:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute("SELECT * FROM users WHERE id = %s", (id,))
return cur.fetchone()

def destroy(self, id):
del session['user'][id]
def save(self, user_data):
with self.get_connection() as conn:
with conn.cursor() as cur:
if 'id' not in user_data:
# New user
cur.execute(
"INSERT INTO users (name, email) VALUES (%s, %s) RETURNING id",
(user_data['name'], user_data['email'])
)
user_data['id'] = cur.fetchone()[0]
else:
# Existing user
cur.execute(
"UPDATE users SET name = %s, email = %s WHERE id = %s",
(user_data['name'], user_data['email'], user_data['id'])
)
conn.commit()
return user_data['id']

def save(self, user):
if not (user.get('name') and user.get('email')):
raise Exception(f'Wrong data: {json.loads(user)}')
if not user.get('id'):
user['id'] = str(uuid.uuid4())
session['user'][user['id']] = user
session['user'] = session['user']
return user['id']
def destroy(self, id):
with self.get_connection() as conn:
with conn.cursor() as cur:
cur.execute("DELETE FROM users WHERE id = %s", (id,))
conn.commit()
Loading