def get(self, request, filename, format=None): # open file, ignore header filepath = './media/' + filename try: f = open(filepath, 'r') except OSError: print "Could not open/read file:", fname sys.exit() goodcount = 0 badcount = 0 with f as read_obj: csv_dict_reader = DictReader(f) header = next(csv_dict_reader) # Check file as empty if header != None: for row in csv_dict_reader: # foreach line in the file, put data into request object and run through serializer. serializer = MemberSerializer(data=row) # if valid, great if serializer.is_valid(): serializer.save() goodcount += 1 # serializer.save() else: # if invalid, bad, flag it, and continue badcount += 1 # return link to processed file return Response(u'Good:' + str(goodcount) + ' Bad: ' + str(badcount))
def put(self, request, pk, format=None): member = self.get_object(pk) serializer = MemberSerializer(member, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk1, pk2): member = self.get_member(request, pk1, pk2) try: request.data.pop('competition') except: pass serializer = MemberSerializer(instance=member, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors)
class UserSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ('id', 'username', 'name', 'image', 'image_thumbnail', 'image_large', 'fav_groups', 'fav_member_sakura', 'fav_member_hinata') image = serializers.URLField(source='profile_image_uri') image_thumbnail = serializers.URLField( source='profile_image_thumbnail_uri') image_large = serializers.URLField(source='profile_image_large_uri') fav_groups = GroupSerializer(many=True, read_only=True) fav_member_sakura = MemberSerializer(read_only=True) fav_member_hinata = MemberSerializer(read_only=True)
def test_get_item(self): request = factory.get('/api/teams/dev/members/8/') force_authenticate(request, user=self.admin_user) view = MemberViewSet.as_view({'get': 'retrieve'}) response = view(request, parent_lookup_team=str(self.dev_team.id), pk='8') response.render() expected_data = MemberSerializer(self.member).data self.assertEqual(response.status_code, status.HTTP_200_OK, 'expected HTTP 200') for rk, ek in zip(response.data.keys(), expected_data.keys()): self.assertEqual(str(response.data[rk]), str(expected_data[ek]), 'expected correct member data')
def update(self, request: Request, pk: int = None, *args: Any, **kwargs: Any) -> Response: """Update a member. Args: request: request sent by the client. pk: id of the object to be updated. args: Variable length argument list. options: Arbitrary keyword arguments. Returns: Response from the server. """ datas = request.data member = Member.objects.get(id=pk) self.check_object_permissions(request=request, obj=member) for attr, value in datas.items(): if attr == "password": member.set_password(value) else: setattr(member, attr, value) member.save() serializer = MemberSerializer(member) return Response(serializer.data, status=status.HTTP_200_OK)
def list(self, request): generating_data() queryset = self.get_queryset() serializer = MemberSerializer(queryset, many=True) #Write json data in an output.json file. with open("output.json", "w") as fw: json.dump(serializer.data, fw) return Response(serializer.data, status=status.HTTP_200_OK)
def member_list(request): if request.method == "GET": members = Member.objects.all() ser = MemberSerializer(members, many=True) return JsonResponse(ser.data, safe=False) elif request.method == "POST": data = JSONParser().parse(request) ser = MemberSerializer(data=data) if ser.is_valid(): ser.save() return JsonResponse(ser.data, status=201) return JsonResponse(ser.errors, status=400)
def member_all_data(request, format=None): if request.method == 'GET': snippets = Member.objects.all() serializer = MemberSerializer(snippets, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = MemberSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def member_list(request): """ List all members, or create a new member. """ if request.method == 'GET': members = Member.objects.all() serializer = MemberSerializer(members, many=True) return Response(serializer.data) if request.method == "POST": serializer = MemberSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, request: Request, *args: Any, **kwargs: Any) -> Response: """Create a member. Args: request: request sent by the client. args: Variable length argument list. options: Arbitrary keyword arguments. Returns: Response from the server. """ datas = request.data datas["id"] = get_max_id("Member") new_member = Member.objects.create_user(**datas) serializer = MemberSerializer(new_member, many=False) return Response(serializer.data, status=status.HTTP_201_CREATED)
def member_detail(request, pk): """ Retrieve, update or delete a member. """ try: member = Member.objects.get(pk=pk) except Member.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = MemberSerializer(user) return Response(serializer.data) if request.method == "PUT": serializer = MemberSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) if request.method == "DELETE": member.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def get(self, request, pk1, pk2): member = self.get_member(request, pk1, pk2) serializer = MemberSerializer(member) return Response(serializer.data)
def get(self, request, client_member_id, format=None): members = Member.objects.filter(client_member_id=client_member_id) serializer = MemberSerializer(members, many=True) return Response(serializer.data)
def get(self, request, pk, format=None): member = self.get_object(pk) serializer = MemberSerializer(member) return Response(serializer.data)
def post(self, request, format=None): serializer = MemberSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, format=None): members = Member.objects.all() serializer = MemberSerializer(members, many=True) return Response(serializer.data)
def get_additional_data(random_seed, request, filter_group_ids=None): data = [] data_length = 50 max_rank = 3 prefix = {'dl': '今日', 'view': '今日', 'popularity': '現在', 'newer': '現在'} modifier = {'dl': 'ダウンロードされた', 'view': '閲覧された', 'popularity': '人気のある', 'newer': '新しい'} suffix = {'image': '画像', 'blog': 'ブログ'} # 推しグループでfilter if filter_group_ids and all([type(g) is int for g in filter_group_ids]): groups = Group.objects.filter( is_active=True, group_id__in=filter_group_ids) else: groups = Group.objects.filter(is_active=True) for group in groups: # images images = Image.objects.filter(publisher__writer__belonging_group=group) most_dl_per_day_images = images.exclude( d1_per_day=0).order_by('-d1_per_day') most_view_per_day_images = images.exclude( v1_per_day=0).order_by('-v1_per_day') most_popular_images = images.exclude(score=0).order_by('-score') images_data = [] images_data.extend(generate_resource_data( most_dl_per_day_images, max_rank, 'dl', 'image', prefix, modifier, suffix, group.name)) images_data.extend(generate_resource_data(most_view_per_day_images, max_rank, 'view', 'image', prefix, modifier, suffix, group.name)) # 注目メンバー決定のため↓ images_data_p = generate_resource_data( most_popular_images, max_rank, 'popularity', 'image', prefix, modifier, suffix, group.name) if images_data_p: most_popular_image = images_data_p[0]['resource'] else: most_popular_image = None images_data.extend(images_data_p) for i, images_data_part in enumerate(images_data): if images_data_part is not None: image_data = ImageSerializer(images_data_part['resource'], context={ 'me': request.user}).data blog_data = BlogSerializer( images_data_part['resource'].publisher).data images_data_part['resource_info'].update( {'image': image_data, 'blog': blog_data}) data.append(images_data_part['resource_info']) # blogs blogs = Blog.objects.filter(writer__belonging_group=group) most_view_per_day_blogs = blogs.exclude( v1_per_day=0).order_by('-v1_per_day') newest_blogs = otapick.sort_blogs(blogs, 'newer_post') most_popular_blogs = blogs.exclude(score=0).order_by('-score') blogs_data = [] blogs_data.extend(generate_resource_data(most_view_per_day_blogs, max_rank, 'view', 'blog', prefix, modifier, suffix, group.name)) blogs_data.extend(generate_resource_data( newest_blogs, max_rank, 'newer', 'blog', prefix, modifier, suffix, group.name)) # 注目メンバー決定のため↓ blogs_data_p = generate_resource_data( most_popular_blogs, max_rank, 'popularity', 'blog', prefix, modifier, suffix, group.name) if blogs_data_p: most_popular_blog = blogs_data_p[0]['resource'] else: most_popular_blog = None blogs_data.extend(blogs_data_p) for i, blogs_data_part in enumerate(blogs_data): if blogs_data_part is not None: blog_data = BlogSerializer(blogs_data_part['resource']).data blogs_data_part['resource_info'].update({'blog': blog_data}) data.append(blogs_data_part['resource_info']) # member if most_popular_image is not None: popular_member = most_popular_image.publisher.writer elif most_popular_blog is not None: popular_member = most_popular_blog.writer else: popular_member = None if popular_member is not None: member_data = MemberSerializer(popular_member).data member_data = {'member': member_data} member_data.update( {'type': 'member', 'message': '注目のメンバー({})'.format(group.name)}) data.append(member_data) # twitter ads for TWITTER_ADS_URL in otapick.TWITTER_ADS_URLS: data.append({'type': 'twitter', 'message': 'ヲタピックの公式Twitterはこちらから!', 'src': TWITTER_ADS_URL, 'url': OTAPICK_TWITTER_URL, 'width': TWITTER_ADS_WIDTH, 'height': TWITTER_ADS_HEIGHT}) data += [None for _ in range(data_length - len(data))] np.random.seed(random_seed) np.random.shuffle(data) return data
def get(self, request, phone_number, format=None): members = Member.objects.filter(phone_number=phone_number) serializer = MemberSerializer(members, many=True) return Response(serializer.data)