Skip to content
This repository has been archived by the owner on Aug 31, 2023. It is now read-only.

Commit

Permalink
Переработан manage.py #188 #108 #48 (#207)
Browse files Browse the repository at this point in the history
* feat(manage): add "init", "run", "client", "db" group

- command "runserver" rename to "devserver"
- add command "server"

* feat: add new parameter for disable logging in ConfigHandler

* feat (manage): add 4 main commad: "run", "create", "delete" and "client"

Regroup all command. Expanded description of commands, the number of options, help message. In the "Client" command, the list of available API methods is shortened.

* fix (manage): fixed type hinting in click_async()

* feat(lib): Hash class has removed the binding to the config file.

Added two parameters size_password, size_auth_id to __init__

* fix(manage): fixed create_user(), create_flow(), create_admin()

* fix(tests): fixed all test for coomand "create" and "delete"

* fix: Update manage.py and test_manage.py and fixed tests

* feat(manage): add "clean" command

and add checking file in copy_config()

* feat(tests): add new test for command "clean" and "init"

* feat(config): added new parameter "directory" for ConfigHandler

- and update test

* feat(tests): added new tests for manage.py

for command "run" with options: devserver, server
for command client with options send

* doc: update documentation

* fixed section Contact

* Исправлено падение теста, тикет issue #187 (#208)

* fixed(dbhandler): add singlton to DBHandler class

* fix: fixed type for __instance

* fixed enable logging in class ConfigHandler

* feat(manage): add "init", "run", "client", "db" group

- command "runserver" rename to "devserver"
- add command "server"

* feat: add new parameter for disable logging in ConfigHandler

* feat (manage): add 4 main commad: "run", "create", "delete" and "client"

Regroup all command. Expanded description of commands, the number of options, help message. In the "Client" command, the list of available API methods is shortened.

* fix (manage): fixed type hinting in click_async()

* feat(lib): Hash class has removed the binding to the config file.

Added two parameters size_password, size_auth_id to __init__

* fix(manage): fixed create_user(), create_flow(), create_admin()

* fix(tests): fixed all test for coomand "create" and "delete"

* fix: Update manage.py and test_manage.py and fixed tests

* feat(manage): add "clean" command

and add checking file in copy_config()

* feat(tests): add new test for command "clean" and "init"

* feat(config): added new parameter "directory" for ConfigHandler

- and update test

* feat(tests): added new tests for manage.py

for command "run" with options: devserver, server
for command client with options send

* doc: update documentation

* fixed section Contact

* fixed enable logging in class ConfigHandler

* fixed(tests) disable some test
  • Loading branch information
stepanskryabin authored Jun 9, 2022
1 parent 58aff06 commit bb2da08
Show file tree
Hide file tree
Showing 11 changed files with 752 additions and 454 deletions.
102 changes: 25 additions & 77 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,30 +121,24 @@ pipenv install --ignore-pipfile
Перед запуском сервера необходимо выполнить некоторые настройки (создать БД, таблицы и добавить первого пользователя - администратора)

Откройте файл `example_config.ini`, найдите параметр URI, замените его на путь к базе данных, пример:
`URI = 'sqlite:db_sqlite.db' `, сохраните файл как `config.ini`
`URI = 'sqlite:db_sqlite.db' `

Создаём базу данных с пустыми таблицами:
Создание `config.ini`, файла БД и учётной записи администратора сервера:

```cmd
pipenv run python ./manage.py --db create
pipenv run python ./manage.py run init
```

Если необходимо удалить все таблицы в созданной базе данных (ВНИМАНИЕ удаляются только таблицы, БД не удаляется):

```cmd
pipenv run pipenv run python ./manage.py --db delete
pipenv run python ./manage.py delete db
```

Добавляем администратора в созданную БД:
Дополнительно можно создать тестовый `flow`:

```cmd
python ./manage.py superuser-create
```

Дополнительно можно создать `flow` с типом группа:

```cmd
pipenv run python ./manage.py --table flow
pipenv run python ./manage.py create flow
```

Информация о всех возможностях менеджера настроек:
Expand All @@ -153,77 +147,41 @@ pipenv run python ./manage.py --table flow
pipenv run python ./manage.py --help
```

## Запуск сервера ##
## Запуск сервера в режиме отладки ##

Для запуска сервера используйте команду:

```cmd
uvicorn server:app --host 0.0.0.0 --port 8000 --reload --use-colors --http h11 --ws websockets
pipenv run python ./manage.py run devserver
```

Дополнительные параметры которые можно передать серверу:

`--log-level <str>` - Set the log level. Options: 'critical', 'error', 'warning', 'info', 'debug', 'trace'. Default: 'info'.

`--use-colors / --no-use-colors` - Enable / disable colorized formatting of the log records, in case this is not set it will be auto-detected. This option is ignored if the `--log-config` CLI option is used.

`--loop <str>` - Set the event loop implementation. The uvloop implementation provides greater performance, but is not compatible with Windows or PyPy. Options: 'auto', 'asyncio', 'uvloop'. Default: 'auto'.

`--http <str>` - Set the HTTP protocol implementation. The httptools implementation provides greater performance, but it is not compatible with PyPy, and requires compilation on Windows. Options: 'auto', 'h11', 'httptools'. Default: 'auto'.

`--ws <str>` - Set the WebSockets protocol implementation. Either of the websockets and wsproto packages are supported. Use 'none' to deny all websocket requests. Options: 'auto', 'none', 'websockets', 'wsproto'. Default: 'auto'.

`--lifespan <str>` - Set the Lifespan protocol implementation. Options: 'auto', 'on', 'off'. Default: 'auto'.

`--interface` - Select ASGI3, ASGI2, or WSGI as the application interface. Note that WSGI mode always disables WebSocket support, as it is not supported by the WSGI interface. Options: 'auto', 'asgi3', 'asgi2', 'wsgi'. Default: 'auto'.

`--limit-concurrency <int>` - Maximum number of concurrent connections or tasks to allow, before issuing HTTP 503 responses. Useful for ensuring known memory usage patterns even under over-resourced loads.

`--limit-max-requests <int>` - Maximum number of requests to service before terminating the process. Useful when running together with a process manager, for preventing memory leaks from impacting long-running processes.

`--backlog <int>` - Maximum number of connections to hold in backlog. Relevant for heavy incoming traffic. Default: 2048

`--ssl-keyfile <path>` - SSL key file

`--ssl-certfile <path>` - SSL certificate file
## Запуск сервера в нормально режиме работы ##

`--ssl-version <int>` - SSL version to use (see stdlib ssl module's)

`--ssl-cert-reqs <int>` - Whether client certificate is required (see stdlib ssl module's)

`--ssl-ca-certs <str>` - CA certificates file

`--ssl-ciphers <str>` - Ciphers to use (see stdlib ssl module's)

`--timeout-keep-alive <int>` - Close Keep-Alive connections if no new data is received within this timeout. Default: 5.

## Запуск сервера в режиме DEBUG ##

Для лёгкого запуска сервера в режиме отладки нужно воспользоваться соответствующей опцией в `manage.py`:
Для запуска сервера используйте команду:

```cmd
pipenv run python ./manage.py runserver
pipenv run python ./manage.py run server
```

Опции:
Параметры которые можно передать серверу (и в режиме отладки и в нормальном режиме):

`--host <str>` - адрес хоста
`--host <str>` - адрес сервера, по умолчанию 127.0.0.1.

`--port <int>` - порт, на котором будет запущен сервер
`--port <int>` - порт серврера, по умолчанию 8080.

`--log-level <str>` - устанавливает уровень логирования. Варианты: "critical", "error", "warning", "info", "debug", "trace". По умолчанию: "info".
`--log-level <str>` - уровень логирования: critical, error, warning, info, debugб trace, по умолчанию debug.

`--use-colors <bool>` - включает и выключает цветовое выделение логов
`--use-colors` - включить использования цветного вывода сообщений.

`--reload <bool>` - активирует/деактивирует автоматический перезапуск сервера при изменении его кода
`--reload` - "горячая" перезагрузка.


## Проверка работоспособности сервера с помощью встроенного клиента ##

Для проверки работы сервера запустите встроенный в `manage.py` мини-клиент:

```cmd
pipenv run python manage.py testclient send
pipenv run python manage.py client send
```

Примечание: перед запуском клиента нужно запустить сервер
Expand Down Expand Up @@ -276,28 +234,18 @@ CRITICAL | logger.critical()
pipenv run python -v ./tests/test_*.py
```

## Запуск дебагера ##

Для запуска дебагера в полевых условиях, через консоль

```cmd
python -m pdb ./debug_server.py
```

Для получения справки в дебаг-режиме

```cmd
(pdb) help
```

## Контакты ##

[Telegram](https://t.me/+xfohB6gWiOU5YTUy) - группа где обсуждаются насущные вопросы.
[Telegram](https://t.me/+xfohB6gWiOU5YTUy) - группа для обсуждения вопросов разработки.

[Slack](moreliatalk.slack.com) - обсуждение проекта.
[Slack](moreliatalk.slack.com) - дополнительный канал для обсуждения вопросов разработки.

## Лицензия ##

Copyright (c) 2020 - настоящее время [NekrodNIK](https://github.com/NekrodNIK), [Stepan Skriabin](https://github.com/stepanskryabin), [rus-ai](https://github.com/rus-ai) и другие. Смотрите полный список в файле AUTHORS.md.
Copyright (c) 2020 - настоящее время MoreliaTalk team
[NekrodNIK](https://github.com/NekrodNIK),
[Stepan Skriabin](https://github.com/stepanskryabin),
[rus-ai](https://github.com/rus-ai) и другие.
Смотрите полный список в файле AUTHORS.md.

Morelia Server находится под лицензией GNU Lesser General Public License версии 3 или более поздней(LGPL-3.0-or-later). Подробности смотрите в файле COPYING.LESSER.
94 changes: 21 additions & 73 deletions README_ENG.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,30 +121,24 @@ pipenv install --ignore-pipfile
Before starting server, you need to make some settings (create a database, tables and add first user - administrator)

Open `example_config.ini` file, find URI parameter, replace it with database path, example:
`URI = 'sqlite:db_sqlite.db' `, save file as `config.ini`
`URI = 'sqlite:db_sqlite.db' `.

Create a database with empty tables:
Create `config.ini`, database file and create administrator:

```cmd
pipenv run python ./manage.py --db create
pipenv run python ./manage.py run init
```

If you need to delete all tables in created database (WARNING, only tables are deleted, database is not deleted):

```cmd
pipenv run pipenv run python ./manage.py --db delete
```

Add an administrator to created database:

```cmd
python ./manage.py superuser-create
pipenv run python ./manage.py delete db
```

Additionally, you can create a `flow` with a group type:

```cmd
pipenv run python ./manage.py --table flow
pipenv run python ./manage.py create flow
```

Information about all features of settings manager:
Expand All @@ -153,56 +147,20 @@ Information about all features of settings manager:
pipenv run python ./manage.py --help
```

## Start server ##
## Start server in develop mode ##

To start server, use command:

```cmd
uvicorn server:app --host 0.0.0.0 --port 8000 --reload --use-colors --http h11 --ws websockets
pipenv run python ./manage.py run devserver
```

Additional parameters that can be passed to server:

`--log-level <str>` - Set log level. Options: 'critical', 'error', 'warning', 'info', 'debug', 'trace'. Default: 'info'.

`--use-colors / --no-use-colors` - Enable / disable colorized formatting of log records, in case this is not set it will be auto-detected. This option is ignored if `--log-config` CLI option is used.

`--loop <str>` - Set event loop implementation. uvloop implementation provides greater performance, but is not compatible with Windows or PyPy. Options: 'auto', 'asyncio', 'uvloop'. Default: 'auto'.

`--http <str>` - Set HTTP protocol implementation. httptools implementation provides greater performance, but it is not compatible with PyPy, and requires compilation on Windows. Options: 'auto', 'h11', 'httptools'. Default: 'auto'.

`--ws <str>` - Set WebSockets protocol implementation. Either of websockets and wsproto packages are supported. Use 'none' to deny all websocket requests. Options: 'auto', 'none', 'websockets', 'wsproto'. Default: 'auto'.

`--lifespan <str>` - Set Lifespan protocol implementation. Options: 'auto', 'on', 'off'. Default: 'auto'.

`--interface` - Select ASGI3, ASGI2, or WSGI as application interface. Note that WSGI mode always disables WebSocket support, as it is not supported by WSGI interface. Options: 'auto', 'asgi3', 'asgi2', 'wsgi'. Default: 'auto'.

`--limit-concurrency <int>` - Maximum number of concurrent connections or tasks to allow, before issuing HTTP 503 responses. Useful for ensuring known memory usage patterns even under over-resourced loads.

`--limit-max-requests <int>` - Maximum number of requests to service before terminating process. Useful when running together with a process manager, for preventing memory leaks from impacting long-running processes.

`--backlog <int>` - Maximum number of connections to hold in backlog. Relevant for heavy incoming traffic. Default: 2048

`--ssl-keyfile <path>` - SSL key file

`--ssl-certfile <path>` - SSL certificate file
## Starting server in normal mode ##

`--ssl-version <int>` - SSL version to use (see stdlib ssl module's)

`--ssl-cert-reqs <int>` - Whether client certificate is required (see stdlib ssl module's)

`--ssl-ca-certs <str>` - CA certificates file

`--ssl-ciphers <str>` - Ciphers to use (see stdlib ssl module's)

`--timeout-keep-alive <int>` - Close Keep-Alive connections if no new data is received within this timeout. Default: 5

## Starting server in DEBUG mode ##

To easily start server in debug mode, you need to use appropriate option in `manage.py`:
To start server, use command:

```cmd
pipenv run python ./manage.py runserver
pipenv run python ./manage.py run server
```

Options:
Expand All @@ -211,19 +169,19 @@ Options:

`--port <int>` - port on which server will be launched

`--log-level <str>` - sets logging level. Options: "critical", "error", "warning", "info", "debug", "trace". Default: "info".
`--log-level <str>` - sets logging level. Options: "critical", "error", "warning", "info", "debug", "trace". Default: "debug".

`--use-colors <bool>` - turns color highlighting of logs on and off
`--use-colors` - turns color highlighting of logs on and off

`--reload <bool>` - activates/deactivates automatic restart of server when its code changes
`--reload` - activates/deactivates automatic restart of server when its code changes


## Checking health of server using built-in client ##

To check if server is working, run built-in mini-client in `manage.py`:

```cmd
pipenv run python manage.py testclient send
pipenv run python manage.py client send
```

Note: before starting client, you need to start server
Expand Down Expand Up @@ -276,28 +234,18 @@ To run tests, run (instead of an asterisk, substitute name of test)
pipenv run python -v ./tests/test_*.py
```

## Run debugger ##

To run debugger in field, via console

```cmd
python -m pdb ./debug_server.py
```

For help in debug mode

```cmd
(pdb)help
```

## Contacts ##

[Telegram](https://t.me/+xfohB6gWiOU5YTUy) - a group where pressing issues are discussed.
[Telegram](https://t.me/+xfohB6gWiOU5YTUy) - Developer contact group.

[Slack](moreliatalk.slack.com) - project discussion.
[Slack](moreliatalk.slack.com) - an additional channel for communicating with developers.

## License ##

Copyright (c) 2020 - present [NekrodNIK](https://github.com/NekrodNIK), [Stepan Skriabin](https://github.com/stepanskryabin), [rus-ai](https://github .com/rus-ai) and others. See full list in AUTHORS.md file.
Copyright (c) 2020 - present MoreliaTalk team
[NekrodNIK](https://github.com/NekrodNIK),
[Stepan Skriabin](https://github.com/stepanskryabin),
[rus-ai](https://github .com/rus-ai) and others.
See full list in AUTHORS.md file.

Morelia Server is licensed under GNU Lesser General Public License version 3 or later (LGPL-3.0-or-later). See COPYING.LESSER file for details.
10 changes: 0 additions & 10 deletions docs/source/development.rst
Original file line number Diff line number Diff line change
Expand Up @@ -141,16 +141,6 @@ To run tests, run (replace asterisk with test name):
Repository description
----------------------

``/admin/templates`` - templates of admin pages

``/admin/general.py`` -

``/admin/control.py`` -

``/admin/login.py`` -

``/admin/logs.py`` -

``/mod/db/dbhandler.py`` - module is designed to perform queries to the database

``/mod/db/models.py`` - module is responsible for the description of database tables to work through OPM
Expand Down
2 changes: 0 additions & 2 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ For we development uses

* `Python 3.10 <https://www.python.org/>`_ - programming language

* `FastAPI <https://fastapi.tiangolo.com>`_ - basic framework

* `SQLObject <http://sqlobject.org>`_ - ORM for working with the database

* `Pydantic <https://pydantic-docs.helpmanual.io>`_ - data validation
Expand Down
Loading

0 comments on commit bb2da08

Please sign in to comment.