-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
АПИ для креш-курса на python #1
Open
VVStanley
wants to merge
7
commits into
master
Choose a base branch
from
crash_course_development
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
18836cc
АПИ для креш-курса на python
VVStanley 035fdcb
Дописал апи для сотрудников
VVStanley ee34deb
Поправил функцию
VVStanley 2aa0e30
Дописал тесты для сотрудников, дописал readme
VVStanley 6feacc6
добавил блок "Подготовка в работе" в README.md
dae16b8
Дописал readme, зафиксировал версии пакетов
VVStanley 4c9e800
Избавился от ArrayField и вернул sqlite
VVStanley File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
[flake8] | ||
inline-quotes = " | ||
max-line-length = 88 | ||
max-cognitive-complexity = 7 | ||
enable-extensions = G | ||
exclude = | ||
.git, | ||
__pycache__, | ||
venv, | ||
migrations, | ||
settings.py | ||
ignore = VNE001, B009, I201, I100, VNE003, A003, B008, I202, E731, W504 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
# Editors | ||
.vscode/ | ||
.idea/ | ||
|
||
# Vagrant | ||
.vagrant/ | ||
|
||
# Mac/OSX | ||
.DS_Store | ||
|
||
# Windows | ||
Thumbs.db | ||
|
||
# Source for the following rules: https://raw.githubusercontent.com/github/gitignore/master/Python.gitignore | ||
# Byte-compiled / optimized / DLL files | ||
__pycache__/ | ||
*.py[cod] | ||
*$py.class | ||
|
||
# C extensions | ||
*.so | ||
|
||
# Distribution / packaging | ||
.Python | ||
build/ | ||
develop-eggs/ | ||
dist/ | ||
downloads/ | ||
eggs/ | ||
.eggs/ | ||
lib/ | ||
lib64/ | ||
parts/ | ||
sdist/ | ||
var/ | ||
wheels/ | ||
*.egg-info/ | ||
.installed.cfg | ||
*.egg | ||
MANIFEST | ||
|
||
# PyInstaller | ||
# Usually these files are written by a python script from a template | ||
# before PyInstaller builds the exe, so as to inject date/other infos into it. | ||
*.manifest | ||
*.spec | ||
|
||
# Installer logs | ||
pip-log.txt | ||
pip-delete-this-directory.txt | ||
|
||
# Unit test / coverage reports | ||
htmlcov/ | ||
.tox/ | ||
.nox/ | ||
.coverage | ||
.coverage.* | ||
.cache | ||
nosetests.xml | ||
coverage.xml | ||
*.cover | ||
.hypothesis/ | ||
.pytest_cache/ | ||
|
||
# Translations | ||
*.mo | ||
*.pot | ||
|
||
# Django stuff: | ||
*.log | ||
local_settings.py | ||
db.sqlite3 | ||
|
||
# Flask stuff: | ||
instance/ | ||
.webassets-cache | ||
|
||
# Scrapy stuff: | ||
.scrapy | ||
|
||
# Sphinx documentation | ||
docs/_build/ | ||
|
||
# PyBuilder | ||
target/ | ||
|
||
# Jupyter Notebook | ||
.ipynb_checkpoints | ||
|
||
# IPython | ||
profile_default/ | ||
ipython_config.py | ||
|
||
# pyenv | ||
.python-version | ||
|
||
# celery beat schedule file | ||
celerybeat-schedule | ||
|
||
# SageMath parsed files | ||
*.sage.py | ||
|
||
# Environments | ||
.env | ||
.venv | ||
env/ | ||
venv/ | ||
ENV/ | ||
env.bak/ | ||
venv.bak/ | ||
|
||
# Spyder project settings | ||
.spyderproject | ||
.spyproject | ||
|
||
# Rope project settings | ||
.ropeproject | ||
|
||
# mkdocs documentation | ||
/site | ||
|
||
# mypy | ||
.mypy_cache/ | ||
.dmypy.json | ||
dmypy.json |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,69 @@ | ||
# python-web-course | ||
Практический курс по построению Web API на python | ||
# Практический курс по построению Web API на python | ||
|
||
## Подготовка в работе | ||
1. Клонировать репозиторий `https://github.com/kontur-web-courses/python-web-course` | ||
2. Развернуть виртуальное окружение и установить зависимости из `requirements.txt`. | ||
C помощью IDE (например PyCharm) или командной строки: | ||
```shell | ||
$ python3 -m venv venv # создание виртуального окрущения | ||
|
||
$ venv\Scripts\activate.bat # активация виртуального окружения для Windows | ||
$ source venv/bin/activate # активация виртуального окружения для Linux и MacOS | ||
|
||
(venv)$ pip3 install -r requirements.txt # установка зависимостей | ||
|
||
(venv)$ deactivate # выход из виртуального окружения, после завершения работы над проектом | ||
``` | ||
|
||
|
||
## Генерация тестовых данных | ||
Для регенерации тестовых данных можно зайти в админку под суперпользователем и на | ||
вкладке "Ключи" нажать "Перегенерировать все данные" выполнится функция ```srvices.data. | ||
regenerate()``` после ее | ||
выполнения БД будет очищена и наполнена тестовыми данными, будет создано три | ||
организации и 19 сотрудников. В каждой из организаций будет добавлено по 4 сотрудника | ||
1 админ, 2 пользователя и 1 утверждающий(approver). Остальные сотрудники останутся | ||
без привязки к организации, трое из них будет с флагом ```deleted=True``` | ||
Каждая роль(Roles) имеет свои операции(Operations) | ||
Также будет перегенерирован ключ для доступа к апи, он будет годен 24 часа, при | ||
запросах в апи его необходимо включать в заголовки ```headers={"Token": api_token}``` | ||
|
||
## Модели | ||
|
||
### Organization - организации | ||
|
||
- В организации можно добавлять несколько сотрудников, только с флагом | ||
```deleted=False``` | ||
- У организации есть реквизиты Requisites | ||
|
||
### Requisites - реквизиты организации | ||
|
||
- Реквизиты привязываются к организации и выбираются из списка RequisitesName | ||
|
||
### Employee - сотрудники | ||
|
||
- Сотрудники это User с флагом ```is_superuser = False``` | ||
- Сотрудник может быть помечен как удаленный ```deleted=False``` | ||
- У сотрудника назначаются в организации определенные роли(RoleOperations) | ||
|
||
### RoleOperations - операции для роли | ||
|
||
- Список операции(Operations) привязанных к роли(Roles) | ||
|
||
|
||
## АПИ | ||
|
||
Для работы с апи необходимо использовать апи-ключ, он генерируется и доступен в админке | ||
|
||
### Сотрудники | ||
- Получение списка сотрудников | ||
- Получение одного сотрудника по portal_user_id | ||
- Создание сотрудника | ||
- Обновление сотрудника | ||
|
||
### Организации | ||
- Получение списка организаций | ||
- Получение одной организации по id | ||
- Создание организации | ||
- Обновление организации | ||
- Добавление сотрудника в организацию |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
from datetime import datetime | ||
|
||
import jwt | ||
from django.conf import settings | ||
from django.utils import timezone | ||
from rest_framework.permissions import BasePermission | ||
|
||
from tokens.models import Token | ||
|
||
|
||
class KeyPermissions(BasePermission): | ||
def has_permission(self, request, view) -> bool: | ||
if "Token" in request.headers: | ||
token_request = request.headers.get("Token") | ||
token_db = Token.objects.first() | ||
try: | ||
payload = jwt.decode( | ||
token_request, token_db.secret, algorithms=[settings.JWT_ALGORITHM] | ||
) | ||
except Exception: | ||
return False | ||
expired: int = payload.get("exp", 0) | ||
if datetime.fromtimestamp(expired, tz=timezone.utc) > datetime.now( | ||
tz=timezone.utc | ||
): | ||
return True | ||
|
||
return False |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
from api.serializers.employees import ( | ||
CreateEmployeeSerializer, | ||
ListEmployeeSerializer, | ||
UpdateEmployeeSerializer, | ||
) | ||
from api.serializers.organizations import ( | ||
CreateOrganizationSerializer, | ||
ListOrganizationSerializer, | ||
OrganizationAddEmployeeSerializer, | ||
UpdateOrganizationSerializer, | ||
) | ||
|
||
__all__ = ( | ||
"ListEmployeeSerializer", | ||
"CreateEmployeeSerializer", | ||
"UpdateEmployeeSerializer", | ||
"OrganizationAddEmployeeSerializer", | ||
"CreateOrganizationSerializer", | ||
"ListOrganizationSerializer", | ||
"UpdateOrganizationSerializer", | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
from django.contrib.auth import get_user_model | ||
from rest_framework.fields import SerializerMethodField | ||
from rest_framework.serializers import ModelSerializer | ||
|
||
from users.models import RoleOperations | ||
|
||
User = get_user_model() | ||
|
||
|
||
class ListEmployeeSerializer(ModelSerializer): | ||
operations = SerializerMethodField() | ||
|
||
class Meta: | ||
model = User | ||
fields = ( | ||
"portal_user_id", | ||
"email", | ||
"phone", | ||
"role", | ||
"operations", | ||
"deleted", | ||
"created_at", | ||
"updated_at", | ||
) | ||
|
||
@staticmethod | ||
def get_operations(obj): | ||
return RoleOperations.objects.filter(role__in=obj.role).values_list( | ||
"operations", flat=True | ||
) | ||
|
||
|
||
class CreateEmployeeSerializer(ModelSerializer): | ||
class Meta: | ||
model = User | ||
fields = ( | ||
"portal_user_id", | ||
"email", | ||
"phone", | ||
"role", | ||
) | ||
extra_kwargs = { | ||
"portal_user_id": {"required": True}, | ||
"email": {"required": True}, | ||
"role": {"required": True}, | ||
"phone": {"required": False}, | ||
} | ||
|
||
|
||
class UpdateEmployeeSerializer(ModelSerializer): | ||
class Meta: | ||
model = User | ||
fields = ( | ||
"phone", | ||
"role", | ||
"deleted", | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
from django.contrib.auth import get_user_model | ||
from rest_framework.fields import CharField, ListField | ||
from rest_framework.serializers import ModelSerializer | ||
|
||
from api.serializers.employees import ListEmployeeSerializer | ||
from api.validations import ValidateEmployeeMixin | ||
from organizations.models import Organization, Requisites | ||
|
||
User = get_user_model() | ||
|
||
|
||
class RequisitesSerializer(ModelSerializer): | ||
class Meta: | ||
model = Requisites | ||
fields = ("name", "value") | ||
|
||
|
||
class ListOrganizationSerializer(ModelSerializer): | ||
employees = ListEmployeeSerializer(many=True, required=False) | ||
requisites = RequisitesSerializer(many=True) | ||
|
||
class Meta: | ||
model = Organization | ||
fields = ( | ||
"id", | ||
"product_name", | ||
"requisites", | ||
"employees", | ||
"created_at", | ||
"updated_at", | ||
) | ||
extra_kwargs = { | ||
"id": {"required": False, "read_only": True}, | ||
"created_at": {"read_only": True}, | ||
"updated_at": {"read_only": True}, | ||
} | ||
|
||
|
||
class UpdateOrganizationSerializer(ModelSerializer): | ||
requisites = RequisitesSerializer(many=True) | ||
|
||
class Meta: | ||
model = Organization | ||
fields = ("requisites",) | ||
|
||
|
||
class OrganizationAddEmployeeSerializer(ModelSerializer, ValidateEmployeeMixin): | ||
employees = ListField( | ||
child=CharField(), | ||
required=False, | ||
) | ||
|
||
class Meta: | ||
model = Organization | ||
fields = ("employees",) | ||
|
||
|
||
class CreateOrganizationSerializer(ModelSerializer, ValidateEmployeeMixin): | ||
requisites = RequisitesSerializer(many=True) | ||
employees = ListField( | ||
child=CharField(), | ||
required=False, | ||
) | ||
|
||
class Meta: | ||
model = Organization | ||
fields = ( | ||
"product_name", | ||
"requisites", | ||
"employees", | ||
) | ||
extra_kwargs = {"employees": {"required": False}} |
Empty file.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Давай добавил в README.md блок с описанием вспомогательных вещей, типо вот линтер, он нужен для того-то того-то, вот так его можно запустить, а вот в этой файле он конфигурируется. И пример как его запустить. И аналогично для mypy.