half done docker

This commit is contained in:
b1ek 2023-05-17 06:20:28 +10:00
parent 455cbf921d
commit a29095b68b
Signed by: blek
GPG Key ID: 14546221E3595D0C
24 changed files with 1489 additions and 82 deletions

9
.env.example Normal file
View File

@ -0,0 +1,9 @@
APP_DEBUG=false
APP_PORT=80
DB_HOST=db
DB_PORT=3306a
DB_PASSWORD=
DB_DATABASE=pairent
DJANGO_KEY=

3
.gitignore vendored
View File

@ -28,7 +28,4 @@ local_settings.py
db.sqlite3 db.sqlite3
# macOS moment # macOS moment
pairent_backend/.DS_Store
# macOS moment жиза
.DS_Store .DS_Store

View File

@ -1,76 +1,7 @@
# Аренда квартир для студентов <h1 align='center'>Точка</h1>
Добро пожаловать в репозиторий проекта "точка"
В проекте есть три ветки: # Запуск локального сайта
1. Создайте `.env` файл, рекомендуем использовать для этого шаблон `.env.example`
- main — в эту ветку загружается код после положительного тестирования и ревью. 2. Сгенерируйте ключи `genkeys.sh`
- dev_stable — в эту ветку загружается стабильный код, который будет использоваться в продашкене. 3. Поднимите контейнеры `docker-compose up -d`
- dev_unstable — основная ветка для разработчиков.
## ТУТ НАЗВАНЫ ПАПКИ ПОД РАЗРАБОТКУ И ФРОНТ В БЕК НЕ ЗАХОДИТ И НИЧЕГО НЕ МЕНЯЕТ!
## Как начать работать?
- Устанавливаем [python](https://www.python.org/downloads/) версия 3.11.1 и [git](https://git-scm.com/)
- [Настройте git](https://tproger.ru/curriculum/git-guide/). В основном нужно только ввести имя пользователя и почту, пароль запросит при клонировании
Если не хотите заморачиваться с терминалом. Советую использовать [GitHub Desktop](https://desktop.github.com/)
### Клонирование проекта через терминал
Команды написаны под windows. Вводить в командную строку. Проверяйте, что в терминале вы находитесь в правильной директории
- Клонируем репозиторий
```bash
git clone https://github.com/vvsu-rent-project/dev_rent.github
```
- В консоли переходим в папку проекта
- Далее переходим на ветку unstable
```bash
git switch dev_unstable
```
### Клонирование проекта через GitHub Desktop
- Заходим в настройки
![Заходим в настройки](misc/1_step.png)
- Входим в аккаунт
![Входим в аккаунт](misc/2_step.png)
- Клонируем репозиторий
![Клонируем репозиторий](misc/3_step.png)
![Клонируем репозиторий](misc/4_step.png)
### Подготовка проекта к работе
- Открываем VS Code, открываем папку проекта и запускаем терминал
- В терминале переходим в папку pairent_backend
```bash
cd pairent_backend
```
- Создаем виртуальное окружение
```bash
python -m venv venv
```
- Активируем виртуальное окружение. Активировать окружение нужно: когда запускаете сервер, устанавливаете зависимости, добавляете новое django приложение
```bash
venv\Scripts\activate
```
- После активации, устанавливаем зависимости.
```bash
pip install -r requirements.txt
```

2
conf/nginx/logs/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

48
conf/nginx/mime.types Normal file
View File

@ -0,0 +1,48 @@
types {
text/html html htm shtml;
text/css css;
text/xml xml rss;
image/gif gif;
image/jpeg jpeg jpg;
application/x-javascript js;
text/plain txt;
text/x-component htc;
text/mathml mml;
image/png png;
image/x-icon ico;
image/x-jng jng;
image/vnd.wap.wbmp wbmp;
application/java-archive jar war ear;
application/mac-binhex40 hqx;
application/pdf pdf;
application/x-cocoa cco;
application/x-java-archive-diff jardiff;
application/x-java-jnlp-file jnlp;
application/x-makeself run;
application/x-perl pl pm;
application/x-pilot prc pdb;
application/x-rar-compressed rar;
application/x-redhat-package-manager rpm;
application/x-sea sea;
application/x-shockwave-flash swf;
application/x-stuffit sit;
application/x-tcl tcl tk;
application/x-x509-ca-cert der pem crt;
application/x-xpinstall xpi;
application/zip zip;
application/octet-stream deb;
application/octet-stream bin exe dll;
application/octet-stream dmg;
application/octet-stream eot;
application/octet-stream iso img;
application/octet-stream msi msp msm;
audio/mpeg mp3;
audio/x-realaudio ra;
video/mpeg mpeg mpg;
video/quicktime mov;
video/x-flv flv;
video/x-msvideo avi;
video/x-ms-wmv wmv;
video/x-ms-asf asx asf;
video/x-mng mng;
}

38
conf/nginx/nginx.conf Normal file
View File

@ -0,0 +1,38 @@
user nobody nobody;
worker_processes 5;
error_log logs/error.log;
pid logs/nginx.pid;
worker_rlimit_nofile 8192;
events {
worker_connections 4096;
}
http {
include mime.types;
include /etc/nginx/proxy.conf;
index index.html index.htm;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] $status '
'"$request" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
sendfile on;
tcp_nopush on;
gzip on;
server_names_hash_bucket_size 128; # this seems to be required for some vhosts
server {
listen 80;
location / {
proxy_pass http://back;
}
location /static {
root /var/www/static;
try_files $uri $uri/ index.html;
}
}
}

10
conf/nginx/proxy.conf Normal file
View File

@ -0,0 +1,10 @@
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffers 32 4k;

2
data/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

45
docker-compose.yml Normal file
View File

@ -0,0 +1,45 @@
version: '3'
services:
nginx:
image: nginx:alpine
volumes:
- './conf/nginx:/etc/nginx'
- './static:/var/www/html'
restart: always
ports:
- '${APP_PORT:-80}:80'
networks:
pairent:
aliases:
- nginx
depends_on:
- back
back:
build:
context: ./pairent_backend
dockerfile: Dockerfile
networks:
pairent:
aliases:
- back
volumes:
- './pairent_backend:/opt/code'
environment:
DB_PASS: '${DB_PASSWORD}'
depends_on:
- db
db:
image: mariadb
networks:
pairent:
aliases:
- db
volumes:
- './data/db:/etc/mysql'
environment:
MARIADB_ROOT_PASSWORD: '${DB_PASSWORD}'
MARIADB_DATABASE: 'pairent_db'
networks:
pairent:
driver: bridge

97
genkeys.sh Executable file
View File

@ -0,0 +1,97 @@
#!/bin/bash
# ----- Start commands -----
fatal_err() {
echo -e "\033[31mFatal error $*\033[0m"
}
# ----- End commands -----
# ----- Start safeguards -----
if [[ "$1" != '-a' ]]; then
fatal_err
echo " This script will potentially break any existing instance of Pairent."
echo " To execute this script, re-run it with option -a as first argument."
exit -1
fi
if ! [ -f .env ]; then
fatal_err
echo -e " No .env file was found."
echo -e " Please use the \033[32m.env.example\033[0m to create a dotenv file:"
echo -e " 1. \033[34mcp .env.example .env\033[0m"
echo -e " 2. Edit your \033[32m.env\033[0m in your favourite editor"
exit -1
fi
if ! [ -x "$(command -v python3)" ]; then
fatal_err
echo -e " Python is not installed."
echo -e " Please install Python 3.11 on your system"
exit -1
fi
# ----- End safeguards -----
# ----- Start bootstrap back -----
echo Generating keys...
KEY=$(python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())')
sed -Ei "s/^DJANGO_KEY=.*$/DJANGO_KEY=/" .env
sed -Ei "s/^DJANGO_KEY=.*$/DJANGO_KEY='$KEY'/" .env
DB_PASS=$(tr -dc A-Za-z0-9 </dev/urandom | head -c $(( $RANDOM % 32 + 32 )))
sed -Ei "s/DB_PASSWORD=\w*/DB_PASSWORD=$DB_PASS/" .env
echo Using these keys:
echo -e " \033[32mDjango key: \033[0m$KEY"
echo -e " \033[32mDatabase key: \033[0m$DB_PASS"
ln -s .env pairent_backend/.env
# ----- End bootstrap back -----
exit
# ----- Start bootstrap front -----
echo Building frontend static files...
cd pairent_frontend_react
NPMS=('npm' 'pnpm' 'yarn')
NPM='None'
for n in ${NPMS[@]}; do
if [ -x "$(command -v "$n")" ]; then
NPM=$n
fi
done
if [[ "$NPM" == 'None' ]]; then
fatal_err
echo ' No node package manager was found in your system.'
echo ' Please install one of the following:'
for n in ${NPMS[@]}; do
echo -e " $n"
done
exit -1
fi
rm -rf node_modules
$NPM install
$NPM run build
DIST_FOLDER=$(realpath dist)
cd ..
cp -r $DIST_FOLDER/* static
echo Done building frontend static files
# ----- End bootstrap front -----

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,17 @@
FROM python:alpine
RUN apk add --no-cache \
gcc musl-dev \
mysql mariadb-connector-c-dev && \
mkdir /opt/code
COPY requirements.txt /opt/code/requirements.txt
WORKDIR /opt/code
RUN pip install -r requirements.txt
USER nobody
COPY . /opt/code
CMD [ "/bin/sh", "docker-entry.sh" ]

View File

@ -0,0 +1,6 @@
#!/bin/sh
PYTHON='/usr/bin/env python3'
$PYTHON manage.py migrate
$PYTHON manage.py runserver 0.0.0.0:80

View File

@ -10,6 +10,7 @@ For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/ https://docs.djangoproject.com/en/4.1/ref/settings/
""" """
from dotenv import dotenv_values
from pathlib import Path from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'. # Build paths inside the project like this: BASE_DIR / 'subdir'.
@ -19,11 +20,12 @@ BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret! DOTENV = dotenv_values(BASE_DIR / '..' / '.env');
SECRET_KEY = 'django-insecure-=(7b+4ka=5jak-mokuh4#-6_14f58#^0kjwqsz7wyon$4i@sel'
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = DOTENV['DJANGO_KEY']
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True DEBUG = DOTENV['APP_DEBUG'] == 'true'
ALLOWED_HOSTS = ['*'] ALLOWED_HOSTS = ['*']

View File

@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Pairent</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
rel="stylesheet"
/>
<script type="module" crossorigin src="/assets/index-dc786e36.js"></script>
<link rel="stylesheet" href="/assets/index-b130f2c5.css">
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

View File

@ -13,10 +13,15 @@ Including another URLconf
1. Import the include() function: from django.urls import include, path 1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
""" """
from django.template import loader
from django.contrib import admin from django.contrib import admin
from django.urls import path, include from django.urls import path, include
def root_url(req):
return loader.get_template('index.html').render()
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('api/', include('pairent_app.urls')), path('api/', include('pairent_app.urls')),
path('', root_url)
] ]

View File

@ -4,4 +4,5 @@ djangorestframework
django-cors-headers django-cors-headers
Pillow Pillow
requests requests
python-ipware python-ipware
python-dotenv

View File

@ -5,5 +5,6 @@ export default {
plugins: [ plugins: [
react() react()
], ],
publicDir: '/static/dist'
} }

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

20
static/index.html Normal file
View File

@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Pairent</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
rel="stylesheet"
/>
<script type="module" crossorigin src="/assets/index-dc786e36.js"></script>
<link rel="stylesheet" href="/assets/index-b130f2c5.css">
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>