代码优化
Git效果
def get_object(self) -> IMUser:
user_id = (member := self.request.member).imuser
if not (obj := IMUser.normal.filter(user_id=user_id).first()):
- obj = IMUser(
+ obj = IMUser.objects.create(
origin_id=member.id,
role=member.role,
nickname=member.nickname,
open_id=member.openid,
user_id=user_id,
+ phone=member.phone
)
- obj.phone = member.phone
- obj.save()
- return IMUserLoginOrCreate.build_rc_token(obj)
+ elif obj.phone != member.phone:
+ obj.phone = member.phone
+ obj.save()
+ self.build_rc_token(obj)
+ return obj
@staticmethod
- def build_rc_token(obj: IMUser) -> IMUser:
+ def build_rc_token(obj: IMUser) -> None:
if not obj.im_token:
res = RongUser.register(
- obj.user_id, name=obj.nickname, portrait_uri=obj.portrait_url
+ obj.user_id, name=obj.nickname, portrait_uri=obj.portrait_uri
)
if res and res.get("code") == 200:
obj.im_token = res.get("token")
obj.save()
- return obj
优化前的代码
class IMUserLoginOrCreate(generics.RetrieveUpdateAPIView):
"""
get: 注册IM用户
post: 修改用户
"""
queryset = IMUser.normal.filter()
serializer_class = IMUserSerializer
def get_object(self) -> IMUser:
user_id = (member := self.request.member).imuser
if not (obj := IMUser.normal.filter(user_id=user_id).first()):
obj = IMUser(
origin_id=member.id,
role=member.role,
nickname=member.nickname,
open_id=member.openid,
user_id=user_id,
)
obj.phone = member.phone
obj.save()
return IMUserLoginOrCreate.build_rc_token(obj)
@staticmethod
def build_rc_token(obj: IMUser) -> IMUser:
if not obj.im_token:
res = RongUser.register(
obj.user_id, name=obj.nickname, portrait_uri=obj.portrait_url
)
if res and res.get("code") == 200:
obj.im_token = res.get("token")
obj.save()
return obj
优化后的代码
class IMUserLoginOrCreate(generics.RetrieveUpdateAPIView):
"""
get: 注册IM用户
post: 修改用户
"""
queryset = IMUser.normal.filter()
serializer_class = IMUserSerializer
def get_object(self) -> IMUser:
user_id = (member := self.request.member).imuser
if not (obj := IMUser.normal.filter(user_id=user_id).first()):
obj = IMUser.objects.create(
origin_id=member.id,
role=member.role,
nickname=member.nickname,
open_id=member.openid,
user_id=user_id,
phone=member.phone
)
elif obj.phone != member.phone:
obj.phone = member.phone
obj.save()
self.build_rc_token(obj)
return obj
@staticmethod
def build_rc_token(obj: IMUser) -> None:
if not obj.im_token:
res = RongUser.register(
obj.user_id, name=obj.nickname, portrait_uri=obj.portrait_uri
)
if res and res.get("code") == 200:
obj.im_token = res.get("token")
obj.save()
优化原因:
- 应该判断phone是否有变化再决定是否save,数据库操作是很耗时的,尽量减少数据库操作
- build_rc_token顾名思义是用来创建token的,让它成为一个动作就好,不应返回obj;如果要返回obj应该换一个函数名
待优化:
- 不应使用GET来注册,应该用POST,然后PATCH或PUT来修改用户