def signup(self, request): try: user = User.objects.get(email=request.data['email']) if (user != None): return Response(data={ 'message': 'A user with this email is already registered.' }, status=400) except User.DoesNotExist: pass hashed = bcrypt.hashpw(request.data['password'].encode('utf-8'), bcrypt.gensalt(12)) request.data['password'] = hashed.decode('utf-8') request.data['isVerified'] = 1 request.data['isActive'] = 1 serializer = UserSerializer(data=request.data) if (serializer.is_valid() == False): print(serializer.errors) print(serializer) serializer.save() return Response(data={ 'code': 200, 'message': "You are signed up successfully." }, status=200)
class PlayerSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Player fields = ('id', 'user', 'rating', 'created_at', 'finished_at') read_only_fields = ('rating', 'created_at', 'finished_at')
def post(self, request, format=None): """ Create user, add it to both db and redis leaderboards/hash. :param request: request :param format: format :return: """ serializer = UserSerializer(data=request.data) if serializer.is_valid(): user_obj = serializer.save() user_info = get_hash_item(serializer.data) redis_hash.create_hash(serializer.data['user_id'], user_info) points = 0 if 'points' in request.data: points = request.data['points'] user_score = UserScore.objects.create(user_id=user_obj, score_worth=points) user_score.save() score_mapping = {str(serializer.data['user_id']): points} redis_leaderboard.add_user_score(score_mapping) redis_leaderboard.add_score_to_country(user_info['country'], score_mapping) data = serializer.data data['rank'] = redis_leaderboard.get_rank(data['user_id']) data['points'] = points return Response(data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class BigPictureSerializer(serializers.ModelSerializer): hyperlink = BigPictureChildSerializer(many=False, read_only=True) hyperlink_id = serializers.PrimaryKeyRelatedField( required=False, source='hyperlink', queryset=BigPicture.objects.filter(private=False), ) subject = serializers.PrimaryKeyRelatedField( required=False, queryset=BigPicture.objects.all()) kind = serializers.IntegerField() author = UserSerializer(read_only=True) author_id = serializers.PrimaryKeyRelatedField( source='author', queryset=BaseUser.objects.all(), ) family = serializers.SerializerMethodField() children = serializers.SerializerMethodField() pin = serializers.BooleanField(read_only=True) class Meta: model = BigPicture fields = "__all__" def get_family(self, obj): if obj.subject.id == obj.id: return [ BigPictureChildSerializer(a).data for a in BigPicture.objects.filter(subject=obj.id) ] return None def get_children(self, obj): return [a.id for a in BigPicture.objects.filter(parent=obj.id)]
class SparkJobDetailSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) created = serializers.DateTimeField(read_only=True) started = serializers.DateTimeField(read_only=True) finished = serializers.DateTimeField(read_only=True) class Meta: model = SparkJob fields = ('id', 'name', 'description', 'author', 'state', 'priority', 'iterations', 'inputFile', 'created', 'started', 'finished') def update(self, instance, validated_data): state = validated_data.get('state', instance.state) if state in [SparkJobStates['RUNNING'], SparkJobStates['FINISHED']]: return instance instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) if instance.state is SparkJobStates['SUSPENDED']: instance.priority = validated_data.get('priority', instance.priority) instance.iterations = validated_data.get('iterations', instance.iterations) instance.inputFile = validated_data.get('inputFile', instance.inputFile) instance.state = state instance.save() return instance
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() response = requests.post('http://localhost:8000/auth/jwt/create/', data={ 'username': request.data['username'], 'password': request.data['password'] }) content = response.content.decode('utf-8') content = json.loads(content) token = { "refresh": content.get('refresh'), "access": content.get('access'), } return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": token, "message": "Вы зарегестрировались", })
def get(request): """ List users """ users = User.objects.all() return Response(UserSerializer(users, many=True).data)
class RatingSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer(required=False) project = ProjectSerializer(required=False) class Meta: model = Rating fields = ['user', 'project', 'rating']
def get(self, request, **kwargs): if request.query_params.get('search') is None: users = User.objects.all() else: users = User.objects.filter(Q(username__icontains=request.query_params.get( 'search')) | Q(first_name__icontains=request.query_params.get('search'))) serializer = UserSerializer(instance=users, many=True) return Response(serializer.data)
def profile(self, request, pk=None): user = User.objects.get(id=request.userId) serializer = UserSerializer(user) return Response(data={ 'data': serializer.data, 'code': 200 }, status=200)
def my_jwt_response_handler(token, user=None, request=None): usr = BaseUser.objects.get(id=user.id) return { 'token': token, 'user': UserSerializer(usr, context={ 'request': request }).data }
def get(self, request): user = request.user if not user or user.is_anonymous: raise NotAuthenticated() data = { "detail": _(f"{user.username} session is enabled"), "user": UserSerializer(user).data } return Response(data=data, status=status.HTTP_200_OK)
class GroupDetailSerializer(ModelSerializer): ''' Item Detail Serializer ''' owner=UserSerializer(many=True,read_only=True) user=UserSerializer(many=True,read_only=True) class Meta: model=Groupps fields= ( 'id', 'owner', 'user', 'name', 'base_url', ) read_only_fields=['id',]
class VehicleHistorySerializer( ModelSerializer, EnumSupportSerializerMixin ): create_user = UserSerializer(read_only=True) validation_status = EnumField(VehicleDefinitionStatuses, read_only=True) class Meta: model = VehicleChangeHistory fields = ('create_timestamp', 'create_user', 'validation_status')
def auth(request): user = request.user refresh = RefreshToken.for_user(user) serializer = UserSerializer(user) json_data = { 'refresh': str(refresh), 'access': str(refresh.access_token), 'user': serializer.data, } return Response(json_data, status=status.HTTP_200_OK)
def patch(self, request): """ Обновить поля профиля текущего юзера Обновление частичное (не требуется заполнение всех полей) """ serializer = UserSerializer(request.user, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK)
class ItemDetailSerializer(ModelSerializer): """ Item Deatil Seralizer""" owner = UserSerializer(many=False, read_only=True) class Meta: model = Item fields = ('id', 'title', 'price', 'asset_bundle', 'owner', 'created', 'updated') read_only_fields = ('id', )
class LoginSerializer(serializers.ModelSerializer): """ Login Serializer """ auth_token = serializers.CharField(source='key') user = UserSerializer(many=False, read_only=True) class Meta: model = Token fields = ('auth_token', 'user') read_only_fields = fields
class RatingSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) author_id = serializers.PrimaryKeyRelatedField( source='author', queryset=BaseUser.objects.all(), ) basisCount = serializers.SerializerMethodField(read_only=True) class Meta: model = Rating fields = "__all__" def get_basisCount(self, obj): return obj.endorsments.all().count()
class LikeSerializer(ModelSerializer): owner = UserSerializer(many=False, read_only=False) item = PrimaryKeyRelatedField(queryset=Item.objects.all()) class Meta: model = Like fields = ( 'id', 'item', 'owner', 'created_at', 'updated_at', ) read_only_fields = ['id']
class EndorsmentSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) target = RatingSerializer(read_only=True) target_id = serializers.PrimaryKeyRelatedField( source='target', queryset=Rating.objects.all(), ) author_id = serializers.PrimaryKeyRelatedField( source='author', queryset=BaseUser.objects.all(), ) class Meta: model = Endorsment fields = "__all__"
def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) username = serializer.data['username'] password = serializer.data['password'] user = authenticate(username=username, password=password) if not user or not user.is_active: raise AuthenticationFailed() login(request, user) data = { "detail": _(f"{user.username} session is enabled"), "user": UserSerializer(user).data } return Response(data=data, status=status.HTTP_200_OK)
class Grouppserializer(ModelSerializer): owner=UserSerializer(many=True,read_only=False) class Meta: model=Groupps fields=( 'id', 'owner', 'name', ) read_only_fields=('id',) def create(self, validated_data): return Item.objects.create(**validated_data)
class BigPictureChildSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) author_id = serializers.PrimaryKeyRelatedField( source='author', queryset=BaseUser.objects.all(), ) hyperlink_id = serializers.PrimaryKeyRelatedField( required=False, source='hyperlink', queryset=BigPicture.objects.filter(private=False), ) subject = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = BigPicture fields = "__all__"
class QuizSerializer(serializers.ModelSerializer): tags = CreatableSlugRelatedField(many=True, queryset=Tag.objects.all(), slug_field='tag') user = UserSerializer(read_only=True) questions = QuestionSerializer(many=True) class Meta: model = Quiz fields = ('id', 'title', 'description', 'user', 'tags', 'questions', 'rating', 'version_date') read_only_fields = ('user', 'rating', 'version_date') def create(self, validated_data): return Quiz.objects.create_quiz(**validated_data) def update(self, instance, validated_data): return instance.update(**validated_data)
class AssetBundleDetailSerializer(ModelSerializer): pass owner = UserSerializer(many=False, read_only=True) class Meta: model = AssetBundle fields = ( 'id', 'salt', 'kind', 'base_url', 'owner', 'asset_urls', 'created', 'updated' ) read_only_fields = ('id',)
class ItemSerializer(ModelSerializer): owner = UserSerializer(many=False, read_only=False) class Meta: model = Item fields = ( 'id', 'asset_bundle', 'owner', 'created_at', 'details', ) read_only_fields = ('id', ) def create(self, validated_data): return Item.objects.create(**validated_data)
class BigPictureSerializer(serializers.ModelSerializer): hyperlink = BigPictureChildSerializer(many=False, read_only=True) hyperlink_id = serializers.PrimaryKeyRelatedField( required=False, source='hyperlink', queryset=BigPicture.objects.filter(private=False), ) subject = serializers.PrimaryKeyRelatedField( required=False, queryset=BigPicture.objects.all()) author = UserSerializer(read_only=True) author_id = serializers.PrimaryKeyRelatedField( source='author', queryset=BaseUser.objects.all(), ) children = serializers.SerializerMethodField() ratingCount = serializers.SerializerMethodField() pin = serializers.BooleanField(read_only=True) category = serializers.SerializerMethodField() class Meta: model = BigPicture fields = "__all__" def get_category(self, obj): try: return CategorySerializer( Category.objects.get(label=obj.subject.tags)).data except: return CategorySerializer(Category.objects.get(label="all")).data def get_ratingCount(self, obj): return Rating.objects.filter(target_bp=obj).count() def get_children(self, obj): res = [] for bp in BigPicture.objects.filter(parent=obj.id): if bp.hyperlink is not None: bp_json = BigPictureChildSerializer(bp).data bp_json["reverse_author"] = bp.hyperlink.author.id res.append(bp_json) else: res.append(BigPictureChildSerializer(bp).data) return res
def post(self, request, *args, **kwargs): logger.info('Received registration request with data: {data}'.format( data=request.data)) serializer = self.serializer_class(data=request.data) if serializer.is_valid(): validated_data = serializer.validated_data email = validated_data['email'] try: user = User.objects.get(email=email) return Response({ 'email': self.EXISTING_USER_MESSAGE}, status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: user = serializer.save() email_utils.send_activation_email(request, user) serialized_user = UserSerializer(user, context={'request': request}) return Response({'user': serialized_user.data}, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class SparkJobSerializer(serializers.ModelSerializer): link = serializers.SerializerMethodField() author = UserSerializer(read_only=True) state = serializers.ChoiceField(SparkJob.STATE_TYPES, read_only=True) created = serializers.DateTimeField(read_only=True) started = serializers.DateTimeField(read_only=True) finished = serializers.DateTimeField(read_only=True) iterations = serializers.IntegerField(write_only=True) class Meta: model = SparkJob fields = ('id', 'name', 'description', 'inputFile', 'author', 'state', 'priority', 'iterations', 'created', 'started', 'finished', 'link') def get_link(self, obj): return self.context.get('request').build_absolute_uri( reverse('api:sparkjob-detail', kwargs={ 'pk': obj.pk }) ) def create(self, validated_data): user = self.context.get('request').user md = hashlib.md5() timestamp = int(time.mktime(datetime.datetime.utcnow().timetuple())) md.update(str(user.username).encode('utf-8')) md.update(str(timestamp).encode('utf-8')) filename = "{}.json".format(md.hexdigest()) source = os.path.join(settings.MEDIA_TMP, validated_data['inputFile']) destiny = os.path.join(settings.MEDIA_INPUT, filename) shutil.copy2(source, destiny) os.unlink(source) validated_data['inputFile'] = filename validated_data['state'] = SparkJobStates['SUSPENDED'] validated_data['author'] = user job = SparkJob.objects.create(**validated_data) job.save() return job