Git Product home page Git Product logo

cyberbox's Introduction

Cyberbox

Contents:

About

Cyberbox - REST API для файлохранилища с возможностью создавать ссылки на файлы.

pipeline status

coverage report

Реализовано

Общее:

  • Alembic: ORM миграции.
  • Проверять соответствие sql-схемы alembic миграций и sqlalchemy метадаты.
  • Версионирование по git тегам.

Администрирование:

  • Создание админа через коммандную оболочку.
  • Управление пользователями:
    • Просмотр списка пользователей;
    • Изменение пользователей: блокировка, назначение суперпользователей.

Аутентификация:

  • Регистрация пользователей. Пользователи по умолчанию создаются заблокированными.
  • Логин: отправка имени и пароля - получение jwt токена. Защищённые ендпоинты проверяют валидность токена, время действия токена, заблокирован ли пользователь.

Файлы (доступны только для владельца файлов):

  • Просмотр списка.
  • Сохранение файла на сервере.
  • Загрузка файла с сервера.
  • Удаление файла.

Ссылки:

  • Просмотр списка.
  • Создание ссылки на файл (для владельца файла) с опциями:
    • Ограничение времени жизни - параметр valid_until;
    • Сделать одноразовой - параметр is_onetime. После загрузки файла по ссылке, ссылка будет удалена;
    • Также у ссылки есть параметр, показывающий сколько раз был загружен по ней файл.
  • Загрузка файла по ссылке - любой, у кого есть ссылка.
  • Удаление ссылки (для владельца файла).

Installation

To install package locally firstly you need to install these:

  1. Python 3.7. You can install it with pyenv. I suggest also to install virtualenv plugin.
  2. Poetry to manage dependencies.
pyenv install 3.7.4
pyenv virtualenv 3.7.4 cyberbox
# in project root directory:
pyenv local cyberbox
# now virtualenv cyberbox should be active
poetry install

If you had active virtualenv while running poetry install one of following commands should work:

poetry run uvicorn --version
uvicorn --version

So if first command is working and second is not, it means you should prepend all commands with poetry run. That`s why I suggested a way to install packages to local virtualenv so there is no need to call poetry run every time.

Running backend

Create copy of alembic config and override default values:

cp cyberbox/migrations/alembic.example.ini cyberbox/migrations/alembic.ini
cp cyberbox/migrations/alembic.example.ini cyberbox/migrations/alembic-docker.ini
ln -s cyberbox/migrations/alembic.ini

Create config file for local development (config-dev.yaml) and for docker (config-docker.yaml). Examples is in configs dir. Validation can be found in cyberbox/config.py file.

Do not forget to change secret key! Use following command to generate new one:

openssl rand -hex 32

Running service in docker:

docker-compose up -d --build
docker-compose exec cyberbox alembic -c cyberbox/migrations/alembic-docker.ini upgrade head
docker-compose exec cyberbox python cyberbox/dev/pre_create_data.py
# optional: execute test script to show service capabilities
docker-compose exec cyberbox python cyberbox/dev/demonstrate-capabilities.py

You can now access http://127.0.0.1:9000/docs or http://127.0.0.1:9000/redoc.

To run locally provide path to config it in CYBERBOX_CONFIG_FILE environment variable (also you can create copy of export-vars-example.sh and source it):

export CYBERBOX_CONFIG_FILE="$(pwd)/configs/config-dev.yaml"
uvicorn 'cyberbox.asgi:app' --reload

Then go to http://127.0.0.1:8000/docs or http://127.0.0.1:8000/redoc.

CLI

Package should be installed to run cli. For usage info run cyberbox --help. Cli can be invoked by cyberbox or python -m cyberbox.

To create superuser run following command:

cyberbox create-admin --username "admin_username"
# or alternative approach:
python -m cyberbox

Testing

Tests require database:

docker-compose up -d
export CYBERBOX_TEST_DB_URL="postgresql://testuser:testpass@localhost:6432/cyberbox-test"
pytest

Also you can install gitlab-runner locally and use it:

# gitlab-runner exec <executor> <job-name>
gitlab-runner exec docker tests

For load tests:

gunicorn -w 10 -k uvicorn.workers.UvicornWorker 'cyberbox.asgi:app'
locust -f tests/load_testing/script.py --host http://127.1:8000 -u 100 -r 5

Building docker image for CI

Use following commands:

tag='registry.gitlab.com/artslob/cyberbox/ci-image:latest'
docker login registry.gitlab.com
docker build -f .ci/Dockerfile -t "$tag" .
docker push "$tag"

Stack

Cyberbox made with these tools:

  1. FastAPI (starlette + pydanntic) - asyncio web framework with cool validation powered by python type hinting.
  2. encode/databases for asyncio database interaction (alternative to GINO).
  3. aiofiles - asyncio interface for file IO.
  4. SqlAlchemy and Alembic - sql query builder and migrations.

Testing:

  1. pytest-asyncio - pytest plugin for testing asyncio code.
  2. encode/httpx - asyncio client with support for ability to make requests directly to ASGI applications (alternative to async-asgi-testclient). Asynchronous client is used because it allows to interact with database using asyncio like in apps code. But this client requires asgi-lifespan for ASGI events.
  3. asgi-lifespan - startup/shutdown of ASGI apps.
  1. encode/starlette#104
  2. encode/httpx#350
  3. tiangolo/fastapi#58

Notes

  1. To view .rst format use restview.

    # runs restview in background without creating nohup.out file
    nohup restview README.rst > /dev/null 2>&1 &
  2. Use following symbols to create headings:
    • H1 - Part - # with overline
    • H2 - Chapter - * with overline
    • H3 - Section - =
    • H4 - Subsection - -
    • H5 - Subsubsection - ^
    • H6 - Paragraph - "

cyberbox's People

Contributors

artslob avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.