Skip to content

Commit

Permalink
Merge branch 'master' of github.com:EvgVol/foodgram-project-react
Browse files Browse the repository at this point in the history
  • Loading branch information
EvgVol committed Aug 2, 2023
2 parents 526beb4 + 378d345 commit c0baec8
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 73 deletions.
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Евгений Волочек

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
136 changes: 63 additions & 73 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Foodgram - продуктовый помощник
# Foodgram - service for publishing and sharing recipes.
[![Foodgram](https://github.com/evgvol/foodgram-project-react/actions/workflows/foodgram_workflow.yml/badge.svg)](https://github.com/evgvol//foodgram-project-react/actions/workflows/foodgram_workflow.yml)
[![Python](https://img.shields.io/badge/-Python-464646?style=flat-square&logo=Python)](https://www.python.org/)
[![Nginx](https://img.shields.io/badge/-NGINX-464646?style=flat-square&logo=NGINX)](https://nginx.org/ru/)
Expand All @@ -10,111 +10,106 @@
[![Postgres](https://img.shields.io/badge/postgres-%23316192.svg?style=for-the-badge&logo=postgresql&logoColor=white)](https://www.postgresql.org/)
[![codecov](https://codecov.io/gh/EvgVol/foodgram-project-react/branch/master/graph/badge.svg?token=FKKAKXU90C)](https://codecov.io/gh/EvgVol/foodgram-project-react)

Дипломная работа по специальности Python-разработчик курса Яндекс.Практикум. Данная работа является заключительным этапом обучения. *
В данной работе разработан бэкенд проекта согласно спецификации API. В репозитории есть папки frontend, backend, infra, tests:
* В папке `frontend` — файлы, необходимые для сборки фронтенда приложения.
###### Одностраничное приложение на фреймворке [React](https://ru.reactjs.org/), предоставлен [Яндекс.Практикумом](https://practicum.yandex.ru/).
* В папке `infra` — конфигурационные файлы nginx и docker-compose.yml, необходимые для сборки всего проекта.
* В папке `backend` — файлы, необходимые для сборки бэкенд приложения.
* В папке `tests` — файлы, необходимые для тестирования бэкенд приложения.

# Описание
Cервис для публикаций и обмена рецептами.

Авторизованные пользователи могут подписываться на понравившихся авторов, добавлять рецепты в избранное, в покупки, скачивать список покупок. Неавторизованным пользователям доступна регистрация, авторизация, просмотр рецептов других пользователей.
# Descriptions
Service for publishing and sharing recipes.
Authorized users can subscribe to their favorite authors, add recipes to their favorites and shopping list, and download the shopping list. Unregistered users have access to registration, authorization, and viewing other users' recipes.

#

## Подготовка сервера
## Server Preparation

```bash
# В Settings - Secrets and variables создаем переменный с вашими данными
# Это необходимо для работы с CI/CD, DockerHub, GitHub
SECRET_KEY #'< секретный ключ >'
DEBUG #False
ALLOWED_HOSTS #'127.0.0.1, .localhost, 011.222.333.444' - адрес вашего сервера
DB_ENGINE #django.db.backends.postgresql
DB_NAME #postgres
POSTGRES_USER #postgres
POSTGRES_PASSWORD #postgres
DB_HOST #db
DB_PORT #5432
MODE #production
HOST #011.222.333.444
USER #admin
PASSWORD #password
SSH_KEY #Приватный ключ
DOCKER_USERNAME #Логин от докера
DOCKER_PASSWORD #Пароль от докера

#для использование базы данных SQLite3 укажите: MODE=dev
# In Settings - Secrets and variables, we create a variable with your data
# This is necessary to work with CI/CD, DockerHub, GitHub
SECRET_KEY='django-insecure-284jnm=8n5j4^#kfmroc%=@nj+qke7#n$gw54y0iba1-&##f(d'
DEBUG=False
ALLOWED_HOSTS='127.0.0.1, .localhost, 011.222.333.444'
DB_ENGINE='django.db.backends.postgresql'
DB_NAME='postgres'
POSTGRES_USER='postgres'
POSTGRES_PASSWORD='postgres'
DB_HOST='db'
DB_PORT=5432
MODE='production'
HOST=011.222.333.444
USER=admin
PASSWORD=password
SSH_KEY='<< private SSH key >>'
DOCKER_USERNAME='login from DOCKER'
DOCKER_PASSWORD='password from DOCKER'

##to use SQLite3 database, specify: MODE=dev
```

Все действия мы будем выполнять в Docker, docker-compose как на локальной машине так и на сервере ВМ Yandex.Cloud.
Предварительно установим на ВМ в облаке необходимые компоненты для работы:
We will perform all actions in Docker, docker-compose both on the local machine and on the Yandex.Cloud VM server.
We will pre-install the necessary components for work on the VM in the cloud:

*1. Подключитесь к своему серверу*
*1. Connect to your server*

```bash
ssh admin@011.222.333.444
# admin: имя пользователя, под которым будет выполнено подключение к серверу
# 011.222.333.444: IP-адрес сервера
# admin: the name of the user under which the connection to the server will be made
# 011.222.333.444: Server IP address
```

*2. Первым делом обновите существующий список пакетов:*
*2. First update the existing package list:*

```bash
sudo apt update
```

*3. Теперь обновите установленные в системе пакеты и установите обновления безопасности: на ваш сервер была установлена система из внутреннего репозитория Яндекс.Облака, и неизвестно, когда она обновлялась. Доверяй, но обновляй:*
*3. Now update the packages installed in the system and install security updates: the system was installed on your server from the internal repository of Yandex.Cloud, and it is unknown when it was updated. Trust, but update:*

```bash
sudo apt upgrade -y
```

*3. Установите на свой сервер Docker:*
*3. Install Docker on your server:*

```bash
sudo apt install docker.io
```

*4. Следующая команда загружает версию 1.26.0 и сохраняет исполняемый файл в каталоге /usr/local/bin/docker-compose, в результате чего данное программное обеспечение будет глобально доступно под именем docker-compose:*
*4. The following command downloads version 1.26.0 and saves the executable file in the /usr/local/bin/docker-compose directory, as a result of which this software will be globally available under the name docker-compose:*

```bash
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
```

*5. Затем необходимо задать правильные разрешения, чтобы сделать команду docker-compose исполняемой:*
*5. Then you need to set the correct permissions to make the docker-compose command executable:*
```bash
sudo chmod +x /usr/local/bin/docker-compose
```

*6. Чтобы проверить успешность установки, запустите следующую команду:*
*6. To check the success of the installation, run the following command:*

```bash
docker-compose --version
# Вывод будет выглядеть следующим образом:
# The output will look like this:
#docker-compose version 1.26.0, build 8a1c60f6
```

*6. Скопируйте файлы docker-compose.yaml и nginx/default.conf из вашего проекта на сервер в home/<ваш_username>/docker-compose.yaml и home/<ваш_username>/nginx/default.conf соответственно.:*
*6. Copy the docker-compose files.yaml and nginx/default.conf from your project to the server in home/<your_isegame>/docker-compose.yaml and home/<your_isegame>/nginx/default.conf, respectively.:*

```bash
#Эти файлы нужно скопировать из директории infra локальной машины
scp docker-compose.yml nginx.conf admin@011.222.333.444:/home/admin/
#These files need to be copied from the infra directory of the local
scp docker-compose machine.yml nginx.conf admin@011.222.333.444:/home/admin/
```
## Запуск

Комманда git push является триггером workflow проекта. При выполнении команды git push запустится набор блоков комманд jobs (см. файл [foodgram_workflow.yml](https://github.com/evgvol/foodgram-project-react/actions/workflows/foodgram_workflow.yml)). Последовательно будут выполнены следующие блоки:
## Launch

**tests** - тестирование проекта на соответствие PEP8.
The git push command is the project workflow trigger. When executing the git push command, a set of jobs command blocks will be launched (see the file [Workflow](https://github.com/evgvol/websity-by-designer/actions/workflows/main.yml)). The following blocks will be executed sequentially:

**build_and_push_to_docker_hub** - при успешном прохождении тестов собирается образ (image) для docker контейнера и отправлятеся в DockerHub
**build_and_push_to_docker_hub** - upon successful completion of the tests, an image is collected for the docker container and sent to DockerHub

**deploy** - после отправки образа на DockerHub начинается деплой проекта на сервере.
**deploy** - after sending the image to DockerHub, the deployment of the project on the server begins.

После выполнения вышеуказанных процедур необходимо установить соединение с сервером:
After completing the above procedures, you need to establish a connection to the server:

```bash
ssh admin@011.222.333.444
```

Выполните по очереди команды:
Execute the commands one by one:

```bash
sudo docker-compose exec backend python manage.py migrate
Expand All @@ -123,31 +118,31 @@ sudo docker-compose exec backend python manage.py collectstatic --no-input
sudo docker-compose exec backend python manage.py importcsv
```

Теперь проект доступен по адресу http://011.222.333.444/.
The project is now available at http://011.222.333.444/.

#

## Документация к API
Чтобы открыть документацию локально, запустите сервер и перейдите по ссылке:
[http://localhost/api/docs/](http://localhost/api/docs/) или воспользуйтесь докой на моей сервере: [REDOC](http://130.193.41.225/api/docs/)
## Documentation to API
To open the documentation locally, start the server and follow the link:
[[http://localhost/api/docs /](http://localhost/api/docs /) or use the board on my server: [REDOC](http://130.193.41.225/api/docs /)

#

## Покрытие тестами
## Test coverage

![codecov](https://codecov.io/gh/EvgVol/foodgram-project-react/branch/master/graphs/sunburst.svg?token=FKKAKXU90C)


</b></details>
<details>
<summary>Что нужно сделать чтобы установить badge покрытие проекта тестами? </summary><br><b>
<summary>What do I need to do to install a badge covering a project with tests? </summary><br><b>

* #### 1. Регистрируйтесь на сервисе: [codecov.io](https://codecov.io)
* #### 1. Register on the service: [codecov.io ](https://codecov.io )


* #### 2. Настраиваем интеграцию, добавляем шаг для отправки данных на сервис
#### Добавляем в секреты данного репозитория CODECOV_TOKEN
#### Ниже указан код который неободимо добавить в foodgram_workflow.yml (более полный пример см. [здесь](https://github.com/codecov/codecov-action#usage)):
* #### 2. Configure integration, add a step to send data to the service
#### Adding CODECOV_TOKEN to the secrets of this repository
#### #### Below is the code that needs to be added to foodgram_workflow.yml (for a more complete example, see [here](https://github.com/codecov/codecov-action#usage )):
```bash
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v2
Expand All @@ -161,16 +156,11 @@ sudo docker-compose exec backend python manage.py importcsv
verbose: true
```

* #### 3. Как только сделаете pull request, можно получить анализ покрытия тестами на сервисе [codecov.io](https://codecov.io)
* #### 3. As soon as you make a pull request, you can get an analysis of the test coverage on the service [codecov.io ](https://codecov.io )


</b></details>



#


|Автор проекта|[Евгений Волочек](https://github.com/EvgVol)|
|---|---|
|Ревьюер|[Евгений Салахутдинов](https://github.com/EugeneSal)|

0 comments on commit c0baec8

Please sign in to comment.