Skip to content
This repository has been archived by the owner on Jul 16, 2021. It is now read-only.

API example #56

Closed
wants to merge 7 commits into from
Closed

API example #56

wants to merge 7 commits into from

Conversation

yulai46
Copy link

@yulai46 yulai46 commented Oct 4, 2019

No description provided.

@proofit404
Copy link
Contributor

Привет!

Предлагаю в существующем пакете django/example создать следующие подпакеты:

  • api - файлы с @model_view_set, определёнными из Injector, ссылаются на те же самые stories из implemented
  • serializers - набор стандартных сериалайзеров ничем не отличающихся от классического drf.
  • urls - из файла превратить в подпакет.
    ** urls/__init__.py - только include'ы никаких роутеров и view.
    ** urls/web.py - большая часть контента из существующего urls.py
    ** urls/api.py - router для всех viewsets из подпакета api.

Начать предлагаю с list и details actions, чтобы заработало основное ядро. После этого уже будем прикручивать stories по одной.

Что думаешь?

Copy link
Contributor

@proofit404 proofit404 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Work in progress. Don't merge.

@yulai46
Copy link
Author

yulai46 commented Oct 4, 2019

С сериализаторами и урлами все ясно, но пока все равно не до конца понимаю как работает Injector. Завтра попробую все реализовать, думаю тогда и разберусь.

P.S. Получается я наследуюсь от Injector, ставлю декоратор @model_view_set и работаю с этим как с обычным ModelViewSet от drf ?

@yulai46
Copy link
Author

yulai46 commented Oct 5, 2019

@proofit404 Привет! Пытаюсь одолеть ошибку:
dependencies.exceptions.DependencyError: 'SignUoModelViewSet' can not resolve attribute 'lookup_field'

serializers/user.py

from rest_framework import serializers
from django.contrib.auth.models import User


class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name', 'password')

urls/api.py

from rest_framework import routers
from example.api.sign_up import SignUoModelViewSet

router = routers.SimpleRouter()
router.register(r'users', SignUoModelViewSet)
urlpatterns = router.urls

api/sign_up.py

from dependencies.contrib.rest_framework import model_view_set
from dependencies import Injector, Package, operation
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.response import Response
from example.serializers.user import UserSerializer

implemented = Package("example.implemented")
functions = Package("example.functions")


@model_view_set
class SignUoModelViewSet(Injector):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    sign_up = implemented.SignUp.register_user

    @operation
    def create(request, sign_up):
        serializer = UserSerializer(request.data)
        serializer.is_valid()
        data = serializer.validated_data
        result = sign_up.run(data, request)

        if result.is_success:
            return Response(status=status.HTTP_201_CREATED)
        elif result.failed_on("compare_passwords"):
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        elif result.failed_on("validate_password_strength"):
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@proofit404
Copy link
Contributor

Привет. Пока всё в верном направлении.

Приложи полный traceback, пожалуйста. Так будет проще понять где засада.

Сорцы можно коммитить даже неработающие. Так будет проще проводить review.

По мелочи:

serializer = UserSerializer(request.data)
serializer.is_valid()
data = serializer.validated_data

В DI scope есть переменная validated_data. Лучше использовать её.

Если нет в документации - это мой косяк.

@proofit404
Copy link
Contributor

В самом @model_view_set из create и update надо возвращать инстансы моделей. Из destroy не надо возвращать ничего. Если дока косячная, буду очень благодарен за PR.

P.S. Куда-нибудь в директ скинь мне свой адрес. Как этот PR смержим, мы тебе вышлем мерч dry-python.

@proofit404
Copy link
Contributor

Any news so far?

Copy link
Contributor

@proofit404 proofit404 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From the architecture point of view it's perfect! Good job. Thanks!

django/example/api/sign_up.py Outdated Show resolved Hide resolved
django/example/services/sign_up_user.py Show resolved Hide resolved
django/example/services/sign_up_user.py Outdated Show resolved Hide resolved
@yulai46
Copy link
Author

yulai46 commented Oct 21, 2019

I have a question about authentification.Do I have to use BasicAuthentification or TokenAuthentication?

@proofit404
Copy link
Contributor

In my opinion, it's better to use token authentication or JWT authentication for APIs.

@yulai46
Copy link
Author

yulai46 commented Oct 21, 2019

And last question for today. Why we talk in english? )

@proofit404
Copy link
Contributor

Потому что я забыл переключиться и ревьювил по умолчанию)).

@proofit404
Copy link
Contributor

@yulai46 any news? 🙏

@proofit404
Copy link
Contributor

Looks like this is going nowhere.

@proofit404 proofit404 closed this Feb 4, 2020
@yulai46
Copy link
Author

yulai46 commented Feb 4, 2020

@proofit404 Простите, на работе завал, думал что смогу совместить но не вышло. Но как будет время я обязательно закончу, если конечно кто то меня не опередит.
P.S. Зато внедрил dry-python в production :)

@proofit404
Copy link
Contributor

Круто! Обязательно напиши feedback по этому поводу)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants