def post(self, request, format=None): """ 透過 Facebook access token 建立 Facebook 帳號或是登入 """ serializer = self.serializer_class(data=request.DATA) if serializer.is_valid(): access_token = serializer.data.get('access_token') try: st = SocialToken.objects.get(token=access_token) user = st.account.user user.backend = 'django.contrib.auth.backends.ModelBackend' if user.is_active: login(request, user) serializer = UserInfoSerializer(request.user) return Response(serializer.data, status=status.HTTP_200_OK) except SocialToken.DoesNotExist: pass try: app = providers.registry.by_id(FacebookProvider.id).get_app(request) token = SocialToken(app=app, token=access_token) fb_login = fb_complete_login(request, app, token) complete_login(request, fb_login, app, token) serializer = UserInfoSerializer(request.user) return Response(serializer.data, status=status.HTTP_200_OK) except requests.RequestException as e: return Response(str(e), status=status.HTTP_400_BAD_REQUEST) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): """ 建立 網站 帳號或是登入帳號為email格式 """ serializer = self.serializer_class(data=request.DATA) if serializer.is_valid(): username = serializer.data.get('username') password = serializer.data.get('password') next_url = request.GET.get("next", None) try: User.objects.get(username=username) user = authenticate(username=username, password=password) if user is not None: if user.is_active: #import pdb;pdb.set_trace() login(request, user) else: return Response({"status":False, "msg":u"錯誤的帳號或密碼"}, status=status.HTTP_200_OK) except User.DoesNotExist: return Response({"status":False, "msg":u"使用者帳號錯誤"}, status=status.HTTP_200_OK) serializer = UserInfoSerializer(request.user, context={'request': request}) if next_url: return Response({"status":True, "next":next_url}, status=status.HTTP_201_CREATED) else: return Response({"status":True, "next": False}, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class ChessPartySerializer(serializers.ModelSerializer): """Serializer партии Шахмат""" white = UserInfoSerializer() black = UserInfoSerializer() result = serializers.CharField(source="get_result_display") moves = serializers.SerializerMethodField("get_moves") @staticmethod def get_moves(party: Party) -> dict: serializer = ChessMoveSerializer(party.get_moves(), many=True) return serializer.data class Meta: model = Party exclude = ("game", )
def register(request): recevie = request.data username = recevie.get('username', '') password = recevie.get('password', '') gender = recevie.get('gender', '0') if not password: return Response({'result': 0, 'cause': u'请输入密码'}) try: User.objects.get(username=username) cause = u"用户名已存在" print '1' return Response({'result': 0, 'cause': u"用户名已存在"}) except User.DoesNotExist: USER_RE = re.compile(u'^[a-zA-Z0-9_-]{3,20}$') if not USER_RE.match(username): cause = u"用户名不合法,长度3到20,大小写字母、数字、-、下划线组成" print '2' return Response({'result': 0, 'cause': cause}) avatar = request.FILES.get('avatar', None) if not avatar: print '3' return Response({'result': 0, 'cause': u'必须上传头像'}) ##### "注册到极光即时聊天" ###### JIM = 'https://api.im.jpush.cn/v1/users/' data = [ { "username": username, "password": username }, ] data = json.dumps(data) base64_auth_string = base64.b64encode(app_key + ':' + master_secret) headers = dict() headers['Authorization'] = 'Basic ' + base64_auth_string headers["Content-type"] = "application/json;charset:utf-8" response = requests.post(JIM, data=data, headers=headers, verify=False) if response.status_code != 201: print '4' return Response({ "result": 0, "cause": u"注册失败", }) ############ new_user = User.objects.create_user(username=username, password=password) user_info = UserInfo.objects.create(user=new_user, nickname=new_user.id, gender=gender, avatar=avatar) token = Token.objects.create(user=new_user) serializer = UserInfoSerializer(user_info) response = serializer.data response['token'] = token.key return Response({'result': 1, 'user_info': response}, )
class ChatSerializer(serializers.ModelSerializer): """Serializer чата""" user_1 = UserInfoSerializer() user_2 = UserInfoSerializer() messages = serializers.SerializerMethodField("get_messages") @staticmethod def get_messages(chat: Chat) -> list: messages = chat.message_set.all() serializer = MessageSerializer(messages, many=True) return serializer.data class Meta: model = Chat fields = "__all__"
class MessageSerializer(serializers.ModelSerializer): """Serializer сообщения""" sent_from = UserInfoSerializer() class Meta: model = Message fields = "__all__"
class ChatListSerializer(serializers.ModelSerializer): """Serializer для списка чатов""" user_1 = UserInfoSerializer() user_2 = UserInfoSerializer() last_message = serializers.SerializerMethodField("get_last_message") @staticmethod def get_last_message(chat: Chat) -> dict: last_message = chat.message_set.last() serializer = MessageSerializer(last_message) return serializer.data class Meta: model = Chat fields = "__all__"
class GomokuPartyListSerializer(serializers.ModelSerializer): """Serializer списка партии Гомоку""" player_1 = UserInfoSerializer() player_2 = UserInfoSerializer() winner = serializers.SerializerMethodField("get_winner") moves_count = serializers.SerializerMethodField("get_moves_count") @staticmethod def get_winner(party: Party) -> (dict, None): return GomokuPartySerializer.get_winner(party) @staticmethod def get_moves_count(party: Party) -> int: return party.get_moves().count() class Meta: model = Party fields = "__all__"
class ChessPartyListSerializer(serializers.ModelSerializer): """Serializer списка партии Шахмат""" white = UserInfoSerializer() black = UserInfoSerializer() result = serializers.CharField(source="get_result_display") moves_count = serializers.SerializerMethodField("get_moves_count") @staticmethod def get_moves_count(party: Party) -> int: moves_count = party.get_moves().count() if moves_count % 2 == 1: moves_count -= 1 return moves_count / 2 class Meta: model = Party exclude = ("game", )
class ChessMoveSerializer(serializers.ModelSerializer): """Serializer хода партии Шахмат""" player = UserInfoSerializer() time = serializers.SerializerMethodField("get_time_in_seconds") @staticmethod def get_time_in_seconds(move: Move): hours, minutes, seconds = str(move.time).split(":") return int(hours) * 3600 + int(minutes) * 60 + int(seconds) class Meta: model = Move fields = "__all__"
def set_primary(self, request, *args, **kwargs): user_obj = request.user coach_obj = Coach.objects.get(user_id=request.data["coach"]) ref_queryset = CoachMemberRef.objects.filter(coach=coach_obj, member__user=user_obj) if not ref_queryset: return Response({"detail": "未添加该教练"}) CoachMemberRef.objects.filter( primary=True, member__user=user_obj).update(primary=False) coach_ref = ref_queryset[0] coach_ref.primary = True coach_ref.save() serializer = UserInfoSerializer(coach_obj.user) return Response(serializer.data)
def random_list(request): user = request.user try: phone_friends = PhoneFriend.objects.filter(user=user).order_by('?').all() except: phone_friends = [] boys = [] girls = [] for phone_friend in phone_friends: if phone_friend.friend.userinfo.gender == '0': if len(boys) < 5: boys.append(phone_friend.friend.userinfo) else: if len(girls) < 5: girls.append(phone_friend.friend.userinfo) add_boy_count = 5 - len(boys) add_girl_count = 5 - len(girls) if add_boy_count > 0: add_boys = UserInfo.objects.filter(gender='0').order_by('?')[:add_boy_count] boys.extend(add_boys) if add_girl_count > 0: add_girls = UserInfo.objects.filter(gender='1').order_by('?')[:add_girl_count] # random fetch 5 girls girls.extend(add_girls) boys_serializer = UserInfoSerializer(boys, fields=('user', 'avatar'), many=True) girls_serializer = UserInfoSerializer(girls, fields=('user', 'avatar'), many=True) return Response({ 'result': 1, 'boys': boys_serializer.data, 'girls': girls_serializer.data, })
def match_user_list(request): user = request.user if user.userinfo.gender == '1': random_matchs = RandomMath.objects.filter(girl=user).order_by('-vote')[0:10] random_match_count = random_matchs.count() if random_match_count < 10: random_matchs = random_match_user(user=user, gender='0') boys_name = [random_match.boy.username for random_match in random_matchs] boys_info = [random_match.boy.userinfo for random_match in random_matchs] info_serializer = UserInfoSerializer(boys_info, fields=('nickname', 'avatar'), many=True) for i, item in enumerate(info_serializer.data): item['username'] = boys_name[i] else: random_matchs = RandomMath.objects.filter(boy=user).order_by('-vote')[0:10] random_match_count = random_matchs.count() if random_match_count < 10: random_matchs = random_match_user(user=user, gender='1') girls_name = [random_match.girl.username for random_match in random_matchs] girls_info = [random_match.girl.userinfo for random_match in random_matchs] info_serializer = UserInfoSerializer(girls_info, fields=('nickname', 'avatar'), many=True) # print girls_name # print info_serializer.data for i, item in enumerate(info_serializer.data): item['username'] = girls_name[i] return Response({ 'result': 1, 'match_users': info_serializer.data, })
class GomokuPartySerializer(serializers.ModelSerializer): """Serializer партии Гомоку""" player_1 = UserInfoSerializer() player_2 = UserInfoSerializer() winner = serializers.SerializerMethodField("get_winner") moves = serializers.SerializerMethodField("get_moves") @staticmethod def get_winner(party: Party) -> (dict, None): if party.winner is not None: winner = User.objects.get(username=party.winner) serializer = UserInfoSerializer(winner) return serializer.data @staticmethod def get_moves(party: Party) -> dict: serializer = GomokuMoveSerializer(party.get_moves(), many=True) return serializer.data class Meta: model = Party fields = "__all__"
def post(self, request, format=None): """ 註冊網站帳號或修改帳號資訊 """ serializer = self.serializer_class(data=request.DATA) if serializer.is_valid(): username = serializer.data.get('username') nickname = serializer.data.get('nickname') phone_number = serializer.data.get('phone_number') year = serializer.data.get('year') sex = serializer.data.get('sex') address = serializer.data.get('address') birthday = serializer.data.get('birthday') city = serializer.data.get('city') district = serializer.data.get('district') email = serializer.data.get("email", None) try: user = User.objects.get(username=username) user.nickname = nickname user.phone_number = phone_number user.year = year user.sex = sex user.city = city user.district = district #user.email = Username user.address = address user.birthday = birthday if email: #import pdb;pdb.set_trace() if user.email != email: user.email = email #只有fb帳號可改email redirect = True else: redirect = False user.save() except User.DoesNotExist: return Response({"status":False, "msg":u"使用者帳號錯誤"}, status=status.HTTP_200_OK) serializer = UserInfoSerializer(user) if redirect: return Response({"status":True, "redirect":True}, status=status.HTTP_201_CREATED) else: return Response({"status":True, "redirect":False}, status=status.HTTP_201_CREATED) else: return Response({"status":False, "msg":serializer.errors}, status=status.HTTP_200_OK)
def login(request): receive = request.data username = receive['username'] password = receive['password'] user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: # update the token try: token = Token.objects.get(user=user) token.delete() except Token.DoesNotExist: pass token = Token.objects.create(user=user) user_info = UserInfo.objects.get(user=user) serializer = UserInfoSerializer(user_info) response = serializer.data response['token'] = token.key try: love_show = LoveShow.objects.get(user=user) response['lover'] = love_show.lover.url except LoveShow.DoesNotExist: response['lover'] = '' return Response({ "result": 1, "user_info": response, }) else: try: User.objects.get(username=username) cause = u'密码错误' except User.DoesNotExist: cause = u'用户不存在' return Response( { "result": 0, "cause": cause, #"Token" }, status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION)
def post(self, request, format=None): """ 註冊網站帳號或修改帳號資訊 """ serializer = self.serializer_class(data=request.DATA) if serializer.is_valid(): username = serializer.data.get('username') nickname = serializer.data.get('nickname') password = serializer.data.get('password') #re_password = serializer.data.get('re_password') phone_number = serializer.data.get('phone_number') year = serializer.data.get('year') sex = serializer.data.get('sex') address = serializer.data.get('address') birthday = serializer.data.get('birthday') city = serializer.data.get('city') district = serializer.data.get('district') try: user = User.objects.get(username=username) return Response({"status":False, "msg":u"此帳號以註冊過!"}, status=status.HTTP_200_OK) except User.DoesNotExist: user = User.objects.create( username=username, password=password, nickname=nickname, phone_number=phone_number, year=year, sex=sex, email=username, address=address, birthday=birthday, city=city, district=district, ) user.set_password(password) user.save() user.backend = 'mezzanine.core.auth_backends.MezzanineBackend' login(request, user) #UserVerify.objects.create(user=user) serializer = UserInfoSerializer(user) return Response({"status":True}, status=status.HTTP_201_CREATED) else: return Response({"status":False, "msg":serializer.errors}, status=status.HTTP_200_OK)
def get_winner(party: Party) -> (dict, None): if party.winner is not None: winner = User.objects.get(username=party.winner) serializer = UserInfoSerializer(winner) return serializer.data
class CommentWebSerializer(serializers.ModelSerializer): user = UserInfoSerializer() class Meta: model = Comment