Django Get Logged In User Info Outsides Views.py



我一直在研究DRF。我通常更喜欢在另一个python文件上写业务逻辑,而不是在views.py上

self.request.user

但我不知道如何在我的业务逻辑文件中获得相同的用户信息。这是我现在在Views.py 中得到的信息

class AddBusCompanyStaffView(generics.CreateAPIView):
serializer_class = AddBusCompanyUserSerializer

def get_bus_company(self):
return GetBusCompanyUseCase(bus_company_id=self.kwargs.get('bus_company_id')).execute()

def perform_create(self, serializer):
print(self.request.user)
return AddBusCompanyUserUseCase(serializer=serializer,
bus_company=self.get_bus_company()
).execute()

我希望user出现在这里的业务逻辑部分中-->用例.py

User = get_user_model()

class AddBusCompanyUserUseCase(BaseUseCase):
"""
use this to add bus company of specific bus company
"""
def __init__(self,
serializer: bus_company_user_serializers.AddBusCompanyUserSerializer,
bus_company: BusCompany):
self.serializer = serializer
self._data = serializer.validated_data
self._bus_company = bus_company
def execute(self):
self._factory()
def _factory(self):
user_position = self._data.pop('position')
user_password = self._data.pop('password')
user = User(**self._data)
user.set_password(user_password)
user.save()
bus_company_user=BusCompanyStaff(user=user,
position=user_position,
staff_of=self._bus_company,
created_by= #logged in user here
)

如何在created_by中获取self.request.user?我的基本用例是

class BaseUseCase:
"""
Base Use Case
"""
def execute(self):
raise NotImplementedError("Subclasses should implement this!")
def _factory(self):
raise NotImplementedError("Subclasses should implement this!")
def is_valid(self):
return True

由于不能更改BaseUseCase,因此必须将属性添加到AddBusCompanyUserUseCase类中。

这里的关键是在创建时将self.request.user传递给AddBusCompanyUserUseCase,这样您以后就可以作为self.user属性进行访问。

#usecases.py
class AddBusCompanyUserUseCase(BaseUseCase):
"""
use this to add bus company of specific bus company
"""
def __init__(self,
serializer: bus_company_user_serializers.AddBusCompanyUserSerializer,
bus_company: BusCompany,
user: None,
):
self.serializer = serializer
self._data = serializer.validated_data
self._bus_company = bus_company
self.user = user
def execute(self):
self._factory()
def _factory(self):
user_position = self._data.pop('position')
user_password = self._data.pop('password')
user = User(**self._data)
user.set_password(user_password)
user.save()
bus_company_user=BusCompanyStaff(user=user,
position=user_position,
staff_of=self._bus_company,
created_by= self.user
)

# views.py
class AddBusCompanyStaffView(generics.CreateAPIView):
serializer_class = AddBusCompanyUserSerializer

def get_bus_company(self):
return GetBusCompanyUseCase(bus_company_id=self.kwargs.get('bus_company_id')).execute()

def perform_create(self, serializer):
print(self.request.user)
return AddBusCompanyUserUseCase(serializer=serializer,
bus_company=self.get_bus_company(),
user=self.request.user,
).execute()

相关内容

  • 没有找到相关文章

最新更新