Skip to content

Commit

Permalink
feat: simplify start of development with cli
Browse files Browse the repository at this point in the history
  • Loading branch information
dantetemplar committed Nov 21, 2024
1 parent 60a72ae commit c6e7bc7
Show file tree
Hide file tree
Showing 21 changed files with 913 additions and 641 deletions.
1 change: 0 additions & 1 deletion .env.example

This file was deleted.

3 changes: 0 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,3 @@ public.pem

### OS ###
.DS_Store

### Compiled translations ###
*.mo
17 changes: 14 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ default_stages:
repos:
# Fix some errors with Ruff
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.2.2
rev: v0.7.4
hooks:
- id: ruff
args: [ --fix, --exit-zero ]
Expand All @@ -23,14 +23,14 @@ repos:

# Lint Python files with Ruff
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.2.2
rev: v0.7.4
hooks:
- id: ruff
name: "ruff: linting"

# Check other files
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
rev: v5.0.0
hooks:
- id: trailing-whitespace
exclude: alembic/
Expand All @@ -47,3 +47,14 @@ repos:
entry: poetry run python ./scripts/generate_settings_schema.py
pass_filenames: false
files: ^src/config_schema.py$

# Compile translation files with pybabel
- repo: local
hooks:
- id: compile-translations
name: Compile Translations
language: system
entry: pybabel compile -d locales -D messages
pass_filenames: false
always_run: true
files: ^locales/
131 changes: 40 additions & 91 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,120 +34,55 @@ This is the API for music room service in InNoHassle ecosystem.

## Development

### Getting started
### Set up for development

1. Install [Python 3.12](https://www.python.org/downloads/)
2. Install [Poetry](https://python-poetry.org/docs/)
3. Install project dependencies with [Poetry](https://python-poetry.org/docs/cli/#options-2).
1. Install [Python 3.12+](https://www.python.org/downloads/) & [Poetry](https://python-poetry.org/docs/)
2. Install project dependencies with [Poetry](https://python-poetry.org/docs/cli/#options-2).
```bash
poetry install
```
4. Set up [pre-commit](https://pre-commit.com/) hooks:

```bash
poetry run pre-commit install --install-hooks -t pre-commit -t commit-msg
```
5. Set up project settings file (check [settings.schema.yaml](settings.schema.yaml) for more info).
3. Start the API:
```bash
cp settings.example.yaml settings.yaml
poetry run python -m src.api
```
Edit `settings.yaml` according to your needs.
6. Set up a [PostgreSQL](https://www.postgresql.org/) database instance.
<details>
<summary>Using docker container</summary>

- Set up database settings for [docker-compose](https://docs.docker.com/compose/) container
in `.env` file:х
```bash
cp .env.example .env
```
- Run the database instance:
```bash
docker compose up -d db
```
- Make sure to set up the actual database connection in `settings.yaml`, for example:
```yaml
db_url: postgresql+asyncpg://postgres:postgres@localhost:5433/postgres
```

</details>
<details>
<summary>Using pgAdmin</summary>

- Connect to the PostgreSQL server using pgAdmin
- Set up a new database in the server: `Edit > New Object > New database`
- Use the database name in `settings.yaml` file, for example `innohassle-events`:
```yaml
db_url: postgresql+asyncpg://postgres:your_password@localhost:5432/innohassle-events
```
</details>
7. Compile translation (`.po`) files:
> Follow provided instructions if needed
4. Start the Bot:
```bash
poetry run pybabel compile -d locales -D messages
poetry run python -m src.bot
```
> Follow provided instructions if needed
> [!IMPORTANT]
> For endpoints requiring authorization click "Authorize" button in Swagger UI
> [!TIP]
> Edit `settings.yaml` according to your needs, you can view schema in
> [config_schema.py](src/config_schema.py) and in [settings.schema.yaml](settings.schema.yaml)
**Set up PyCharm integrations**

1. Ruff ([plugin](https://plugins.jetbrains.com/plugin/20574-ruff)).
It will lint and format your code.
Make sure to enable `Use ruff format` option in plugin settings.
2. Pydantic ([plugin](https://plugins.jetbrains.com/plugin/12861-pydantic)).
It will fix PyCharm issues with
1. Run configurations ([docs](https://www.jetbrains.com/help/pycharm/run-debug-configuration.html#createExplicitly)).
Right-click the `__main__.py` file in the project explorer, select `Run '__main__'` from the context menu.
2. Ruff ([plugin](https://plugins.jetbrains.com/plugin/20574-ruff)).
It will lint and format your code. Make sure to enable `Use ruff format` option in plugin settings.
3. Pydantic ([plugin](https://plugins.jetbrains.com/plugin/12861-pydantic)). It will fix PyCharm issues with
type-hinting.
3. Conventional commits ([plugin](https://plugins.jetbrains.com/plugin/13389-conventional-commit)).
It will help you
4. Conventional commits ([plugin](https://plugins.jetbrains.com/plugin/13389-conventional-commit)). It will help you
to write [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/).

### Run for development [API]

1. Install dependencies for api if needed:
```bash
poetry install
```
2. Run the database if you have not done it yet
3. Upgrade the database schema using [alembic](https://alembic.sqlalchemy.org/en/latest/):
```bash
poetry run alembic upgrade head
```
4. Run the ASGI server
```bash
poetry run python -m src.api
```
OR using uvicorn directly
```bash
poetry run uvicorn src.api.app:app --use-colors --proxy-headers --forwarded-allow-ips=* --port=8001
```

Now the API is running on http://localhost:8001. Good job!

### Run for development [Bot]

1. Install dependencies for bot if needed:
```bash
poetry install
```
2. Run the [API service](#run-for-development-api) or configure the bot to work with the real(production) API.
3. Run the Redis server if needed:
```bash
docker compose up -d redis
```
4. Run the bot:
```bash
poetry run python -m src.bot
```

### Localization

**Aiogram:**

All localized bot messages should be wrapped: `__("Hello world"")`

1. Extract messages:
```bash
poetry run pybabel extract -k __ --input-dirs=. -o locales/messages.pot
```
2. Initialize languages:
2. Update translations:
```bash
poetry run pybabel init -i locales/messages.pot -d locales -D messages -l en
poetry run pybabel init -i locales/messages.pot -d locales -D messages -l ru
poetry run pybabel update -i locales/messages.pot -d locales -D messages --ignore-pot-creation-date
```
3. Translate messages in created `.po` files
4. Compile translations:
Expand All @@ -173,6 +108,20 @@ We use Docker with Docker Compose plugin to run the website on servers.
7. Run the container: `docker compose up --detach`
8. Check the logs: `docker compose logs -f`

# How to update dependencies

## Project dependencies

1. Run `poetry update` to update all dependencies (it may update nothing, so double-check)
2. Run `poetry show --outdated --all` to check for outdated dependencies
3. Run `poetry add <package>@latest` to add a new dependency if needed

## Pre-commit hooks

1. Run `poetry run pre-commit autoupdate`

Also, Dependabot will help you to keep your dependencies up-to-date, see [dependabot.yml](.github/dependabot.yml).

## Contributing

We are open to contributions of any kind.
Expand Down
4 changes: 2 additions & 2 deletions api.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,6 @@ COPY --chown=poetry:poetry . /code
USER poetry
WORKDIR /code

EXPOSE 8000
EXPOSE 8001
ENTRYPOINT [ "/docker-entrypoint-alembic.sh" ]
CMD [ "uvicorn", "src.api.app:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips=*" ]
CMD [ "uvicorn", "src.api.app:app", "--host", "0.0.0.0", "--port", "8001", "--proxy-headers", "--forwarded-allow-ips=*" ]
1 change: 0 additions & 1 deletion bot.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ RUN groupadd -g 1500 poetry && \
COPY --chown=poetry:poetry . /code
USER poetry
WORKDIR /code
RUN pybabel compile -d locales -D messages

LABEL org.opencontainers.image.source="https://github.com/one-zero-eight/music-room"

Expand Down
10 changes: 5 additions & 5 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,29 +28,29 @@ services:
condition: service_healthy
restart: always
ports:
- "8001:8000"
- "8001:8001"
volumes:
- "./settings.yaml:/code/settings.yaml:ro" # Read-only settings file
env_file: .env # You can specify some Uvicorn settings in .env file
environment:
- TZ=Europe/Moscow # Set the timezone for correct calendar image generation

db:
# See more: https://hub.docker.com/_/postgres
image: "postgres:16.0"
image: "postgres:17.1"
restart: always
# The commits were slow on our servers, so we turned off the synchronous_commit
command: postgres -c synchronous_commit=off
volumes:
- "postgres:/var/lib/postgresql/data"
ports:
- "5433:5432"
env_file: .env # Set POSTGRES_PASSWORD in .env file
- "5432:5432"
healthcheck:
test: [ "CMD-SHELL", "pg_isready -U postgres" ]
interval: 5s
timeout: 5s
retries: 5
environment:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}

redis:
# See more: https://hub.docker.com/_/redis
Expand Down
Binary file added locales/en/LC_MESSAGES/messages.mo
Binary file not shown.
Binary file added locales/ru/LC_MESSAGES/messages.mo
Binary file not shown.
37 changes: 21 additions & 16 deletions locales/ru/LC_MESSAGES/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,21 @@ msgid ""
"Find someone who knows and ask him/her to teach or help you with it.\n"
"⚠️ Unnecessarily, do not move the equipment.\n"
msgstr ""
"После входа в комнату, вы обязаны следовать "
"правилам, описанным ниже. В случае несоблюдения, доступ в комнату для вас "
"будет навсегда заблокирован.\n"
"После входа в комнату, вы обязаны следовать правилам, описанным ниже. В "
"случае несоблюдения, доступ в комнату для вас будет навсегда "
"заблокирован.\n"
"\n"
"🚫 Не выносите имущество из комнаты.\n"
"🚫 Не приносите еду/напитки в комнату. Если вам хочется поесть/попить, вы можете сделать это "
"за пределами комнаты.\n"
"🚫 Не оставляйте мусор в комнате. В комнате нет мусорного ведра, ближайшее находится у "
"входа в спортивный комплекс.\n"
"🚫 Не пытайтесь починить сломанные инструменты (включая порванные струны гитары). "
"Лучше сообщить об этом в чате, чтобы специалист мог починить их позже.\n"
"⚠️ Если вы не знаете, как настраивать инструмент, не настраивайте его сами. "
"Найдите кого-то, кто знает как это делать и попросите его/её научить вас/помочь.\n"
"🚫 Не приносите еду/напитки в комнату. Если вам хочется поесть/попить, вы "
"можете сделать это за пределами комнаты.\n"
"🚫 Не оставляйте мусор в комнате. В комнате нет мусорного ведра, ближайшее"
" находится у входа в спортивный комплекс.\n"
"🚫 Не пытайтесь починить сломанные инструменты (включая порванные струны "
"гитары). Лучше сообщить об этом в чате, чтобы специалист мог починить их "
"позже.\n"
"⚠️ Если вы не знаете, как настраивать инструмент, не настраивайте его "
"сами. Найдите кого-то, кто знает как это делать и попросите его/её "
"научить вас/помочь.\n"
"⚠️ Не передвигайте оборудование без необходимости"

#: src/bot/constants.py:39
Expand All @@ -61,8 +63,8 @@ msgid ""
"You are banned and can't book the music room. In case you believe it's a "
"mistake, please contact: @"
msgstr ""
"Вы заблокированы и не можете бронировать комнату. Если вы уверены, что это "
"ошибка, пожалуйста, обратитесь к: @"
"Вы заблокированы и не можете бронировать комнату. Если вы уверены, что "
"это ошибка, пожалуйста, обратитесь к: @"

#: src/bot/constants.py:45
msgid "Create a booking"
Expand Down Expand Up @@ -121,7 +123,8 @@ msgid ""
"To continue, you need to connect your Telegram account to the InNoHassle "
"account."
msgstr ""
"Чтобы продолжить, вам необходимо подключить ваш аккаунт Telegram к аккаунту InNoHassle"
"Чтобы продолжить, вам необходимо подключить ваш аккаунт Telegram к "
"аккаунту InNoHassle"

#: src/bot/routers/registration.py:74
msgid "If you have already connected your account, just press the button."
Expand All @@ -139,14 +142,16 @@ msgid ""
"users (usually on Monday)."
msgstr ""
"Вы успешно зарегистрировались.\n"
"❗️ Доступ в спортивный комплекс появится после обновления списка пользователей (обычно по понедельникам)"
"❗️ Доступ в спортивный комплекс появится после обновления списка "
"пользователей (обычно по понедельникам)"

#: src/bot/routers/registration.py:113 src/bot/routers/start_help_menu.py:20
msgid ""
"If you have any questions, you can ask them in the chat or read the "
"instructions."
msgstr ""
"Если у вас есть вопросы, вы можете задать их в чате или обратиться к инструкции"
"Если у вас есть вопросы, вы можете задать их в чате или обратиться к "
"инструкции"

#: src/bot/routers/registration.py:119
msgid "You haven't confirmed the rules. Please, try again."
Expand Down
Loading

0 comments on commit c6e7bc7

Please sign in to comment.