Ejemplo n.º 1
0
    def post(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            if user:
                return Response(serializer.data,
                                status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 2
0
    def put(self, request, user_id):
        try:
            beneficiary = UserProfile.objects.get(user__id=user_id)
            if 'alt_mobile' in request.data.keys():
                new_mobile = request.data['alt_mobile']

                if isinstance(new_mobile,
                              list) and not isinstance(new_mobile,
                                                       (str, unicode)):
                    for n_mob in new_mobile:
                        if not any(n_mob == mobile
                                   for mobile in beneficiary.alt_mobile):
                            beneficiary.alt_mobile.append(n_mob)
                else:
                    if not any(new_mobile == mobile
                               for mobile in beneficiary.alt_mobile):
                        beneficiary.alt_mobile.append(new_mobile)

                beneficiary.save()

            return Response(data=UserSerializer(beneficiary).data,
                            status=status.HTTP_200_OK)
        except UserProfile.DoesNotExist:
            return Response(data={'Error': 'User not found.'},
                            status=status.HTTP_404_NOT_FOUND)
        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Ejemplo n.º 3
0
    def get(self, request):
        args_dict = dict(request.GET.iterlists())
        user_types = []

        if 'user_types' in args_dict.keys():
            user_types = args_dict['user_types']

        data = UserProfile.objects.filter(
            user_type__in=user_types).order_by('user_type')
        serializer = UserSerializer(data, many=True)

        return Response(serializer.data)
Ejemplo n.º 4
0
class PostSerializer(serializers.ModelSerializer):
    user = UserSerializer(required=False)
    likes = serializers.SerializerMethodField()
    dislikes = serializers.SerializerMethodField()

    def get_likes(self, instance: PostModel):
        return PostReactionsRepository().get_likes(instance)

    def get_dislikes(self, instance: PostModel):
        return PostReactionsRepository().get_dislikes(instance)

    def create(self, validated_data):
        validated_data['user'] = globals.request.user
        return PostsRepository().create(**validated_data)

    class Meta:
        model = PostModel
        fields = ('id', 'user', 'text', 'likes', 'dislikes')
Ejemplo n.º 5
0
 def create(self, request):
     try:
         print "Inside creating user profile"
         userprofile = UserProfile.objects.get(
             user__auth_token__key=request.data['token'])
         user = userprofile.user
         if 'first_name' in request.data.keys():
             user.first_name = request.data['first_name']
         if 'last_name' in request.data.keys():
             user.last_name = request.data['last_name']
         user.save()
         return Response(data=UserSerializer(userprofile).data,
                         status=status.HTTP_202_ACCEPTED)
     except UserProfile.DoesNotExist:
         user = None
         return Response(data={'Error': 'User not found.'},
                         status=status.HTTP_404_NOT_FOUND)
     return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Ejemplo n.º 6
0
 def put(self, request, user_id):
     try:
         userprofile = UserProfile.objects.get(id=user_id)
         user = userprofile.user
         if 'first_name' in request.data.keys():
             user.first_name = request.data['first_name']
         if 'last_name' in request.data.keys():
             user.last_name = request.data['last_name']
         if 'mobile' in request.data.keys():
             userprofile.mobile = request.data['mobile']
         if 'points' in request.data.keys():
             userprofile.points = request.data['points']
         if 'user_type' in request.data.keys():
             userprofile.user_type = request.data['user_type']
         user.save()
         userprofile.save()
         return Response(data=UserSerializer(userprofile).data,
                         status=status.HTTP_202_ACCEPTED)
     except UserProfile.DoesNotExist:
         return Response(data={'Error': 'User not found.'},
                         status=status.HTTP_404_NOT_FOUND)
     return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Ejemplo n.º 7
0
 def get(self, request):
     return Response(UserSerializer(request.user).data,
                     status=status.HTTP_200_OK)
Ejemplo n.º 8
0
    def handle(self, *args, **options):
        exported_data = []
        username = get_env_variable('ELASTIC_USERNAME')
        password = get_env_variable('ELASTIC_PASSWORD')
        index_name = get_env_variable('INDEX_NAME')

        es = Elasticsearch([{
            'host': 'localhost',
            'post': 9200
        }],
                           timeout=30,
                           http_auth=(username, password))

        last_updated = datetime.now() - timedelta(365 * 10)

        with open('/home/ubuntu/vms2/pushToEs_last_updated', 'r') as f:
            rows = csv.reader(f)

            for row in rows:
                last_updated = datetime.strptime(row[0],
                                                 "%Y-%m-%d %H:%M:%S.%f")

        tasks = Task.objects.filter(updated_at__gt=last_updated).exclude(
            task_type__task_type='Retention Survey').order_by(
                'updated_at')[:1000]
        # tasks = Task.objects.filter(updated_at__gt=last_updated).order_by('updated_at')[:2500]

        for task in tasks:
            task_doc = dict(TaskListTaskSerializer(task).data)

            task_doc['timestamp'] = datetime.now()
            task_doc['form_data'] = dict(
                FormDataSerializer(task.form_data).data)
            task_doc['task_status_category'] = dict(
                TaskStatusCategorySerializer(task.status.category).data)

            if task.beneficiary and hasattr(task.beneficiary, 'profile'):
                task_doc['beneficiary'][
                    'date_joined'] = task.beneficiary.date_joined
                task_doc['beneficiary']['profile'] = dict(
                    UserSerializer(task.beneficiary.profile).data)
                task_doc['beneficiary']['notes'] = json.loads(
                    json.dumps(
                        NoteSerializer(
                            task.beneficiary.beneficiary_notes.all(),
                            many=True).data))

            if task.beneficiary and hasattr(task.beneficiary,
                                            'persistent_data'):
                task_doc['beneficiary']['persistent_data'] = dict(
                    PersistentFormDataSerializer(
                        task.beneficiary.persistent_data).data)
                if 'Address' in task_doc['beneficiary']['persistent_data'][
                        'data'].keys():
                    try:
                        location = Location.objects.get(
                            pk=task_doc['beneficiary']['persistent_data']
                            ['data']['Address'])
                        task_doc['beneficiary']['location'] = dict(
                            LocationSerializer(location).data)
                        task_doc['beneficiary']['location'][
                            'geocordinates'] = {}
                        task_doc['beneficiary']['location']['geocordinates'][
                            'lat'] = location.lat
                        task_doc['beneficiary']['location']['geocordinates'][
                            'lon'] = location.lng
                    except:
                        pass

            calls = Call.objects.filter(task=task)
            task_doc['calls'] = []
            for call in calls:
                call_dict = dict(CallSerializer(call).data)
                if call_dict['end']:
                    call_duration = (call.end_time - call.start_time).seconds
                    call_dict['duration'] = call_duration
                    call_dict['caller'] = dict(
                        UserSerializer(call.caller.profile).data)
                    task_doc['calls'].append(call_dict)

            if task.beneficiary:
                task_doc['beneficiary']['tags'] = []

                tags = task.beneficiary.tags.all()
                for tag in tags:
                    task_doc['beneficiary']['tags'].append(
                        dict(LightTagSerializer(tag).data))

                if hasattr(task.beneficiary.profile, 'stage'):
                    task_doc['beneficiary']['stage'] = dict(
                        StageSerializer(task.beneficiary.profile.stage).data)

            if task.assignee and hasattr(task.assignee, 'profile'):
                task_doc['assignee']['profile'] = dict(
                    UserSerializer(task.assignee.profile).data)

            if task.assignee and hasattr(task.assignee, 'profile') and hasattr(
                    task.assignee.profile, 'guild'):
                task_doc['assignee']['guild'] = dict(
                    GuildSerializer(task.assignee.profile.guild).data)

            # print task_doc
            try:
                res = es.index(index=index_name,
                               doc_type='task',
                               id=task.id,
                               body=task_doc)
            except Exception as e:
                if e.error == 'mapper_parsing_exception':
                    print task_doc
                    task_doc['beneficiary']['persistent_data']['data'][
                        'Children'][0]['Date of Birth'] = datetime.strptime(
                            task_doc['beneficiary']['persistent_data']['data']
                            ['Children'][0]['Date of Birth'], '%d/%m/%Y')
                    res = es.index(index='ia',
                                   doc_type='task',
                                   id=task.id,
                                   timestamp=task_doc['timestamp'],
                                   body=task_doc)
                    # print task_doc
                    continue
                last_updated = task.updated_at
                # print task_doc
                break
            last_updated = task.updated_at

        with open('/home/ubuntu/vms2/pushToEs_last_updated', 'w') as f:
            f.write(last_updated.strftime("%Y-%m-%d %H:%M:%S.%f"))
Ejemplo n.º 9
0
 def get(self, request, guild_pk):
     data = UserProfile.objects.filter(guild=guild_pk)
     serializer = UserSerializer(data, many=True)
     return Response(serializer.data)
Ejemplo n.º 10
0
 def get(self, request, user_type):
     data = UserProfile.objects.filter(user_type=user_type)
     serializer = UserSerializer(data, many=True)
     return Response(serializer.data)
Ejemplo n.º 11
0
 def get(self, request, token, format=None):
     data = UserProfile.objects.get(user__auth_token__key=token)
     serializer = UserSerializer(data)
     return Response(serializer.data)