Exemple #1
0
def blog_detail(request,pk):
    """
    Get,Update, or delete a specific blog
    """
    #If a blog with the specified key not present, it is handled by catching the exception "DOesNotExist"
    try:
        blog=Blog.objects.get(pk=pk)
    except Blog.DoesNotExist:
        logger.error("ID [%s] does not exist"%str(pk))
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        #Get a blog
        serializer = BlogSerializer(blog)
        logger.info("Getting info for [%s]"%str(pk))
        return Response(serializer.data)
    elif request.method == 'PUT':
        #Update a blog
        serializer=BlogSerializer(blog,data=request.data)
        if serializer.is_valid():
            logger.info("Updating info for [%s]"%str(pk))
            serializer.save()
            return Response(serializer.data)
        logger.error("PUT error : %s"%str(serializer.errors))
        logger.error("HTTP_400_BAD_REQUEST")
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        #delete a blog
        blog.delete()
        logger.info("Deleting info [%s]"%str(pk))
        return Response(status=status.HTTP_204_NO_CONTENT)
 def put(self, request, pk, format=None):
     blog = self.get_object(pk)
     serializer = BlogSerializer(blog, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #3
0
 def test_put_or_update_non_existing_blog(self):
     """
         Testcase to test PUT / UPDATE a non existing blog
     """
     # input dict to test the POST
     input_data = BlogSerializer(self.blog).data
     input_data.update({"title": "changed"})
     puturl = '%s%d' % (self.url, 200)
     response = self.client.put(puturl, data=json.dumps(input_data), content_type='application/json')
     self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Exemple #4
0
 def test_put_or_update_non_existing_blog(self):
     """
         Testcase to test PUT / UPDATE a non existing blog
     """
     # input dict to test the POST
     input_data = BlogSerializer(self.blog).data
     input_data.update({"title": "changed"})
     puturl = '%s%d' % (self.url, 200)
     response = self.client.put(puturl,
                                data=json.dumps(input_data),
                                content_type='application/json')
     self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Exemple #5
0
 def test_put_or_update_blog_invalid_input_format(self):
     """
         Testcase to test PUT / UPDATE
         input is not in proper json format
     """
     # input dict to test the POST
     input_data = BlogSerializer(self.blog).data
     input_data.update({'title': 'changed'})
     puturl = '%s%d' % (self.url, self.blog.id)
     response = self.client.put(puturl, data=input_data, content_type='application/json')
     #data = response.json()
     self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
Exemple #6
0
 def test_put_or_update_blog_invalid_input_format(self):
     """
         Testcase to test PUT / UPDATE
         input is not in proper json format
     """
     # input dict to test the POST
     input_data = BlogSerializer(self.blog).data
     input_data.update({'title': 'changed'})
     puturl = '%s%d' % (self.url, self.blog.id)
     response = self.client.put(puturl,
                                data=input_data,
                                content_type='application/json')
     #data = response.json()
     self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
Exemple #7
0
    def test_put_or_update_existing_blog(self):
        """
            Testcase to test PUT / UPDATE a existing blog
        """
        # input dict to test the POST
        input_data = BlogSerializer(self.blog).data
        input_data.update({"title":"changed"})
        puturl='%s%d'%(self.url,self.blog.id)
        response = self.client.put(puturl, data=json.dumps(input_data), content_type='application/json')
        data = response.json()
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn('title', response.json())

        self.assertEqual(data['title'], input_data['title'])
Exemple #8
0
    def test_put_or_update_existing_blog(self):
        """
            Testcase to test PUT / UPDATE a existing blog
        """
        # input dict to test the POST
        input_data = BlogSerializer(self.blog).data
        input_data.update({"title": "changed"})
        puturl = '%s%d' % (self.url, self.blog.id)
        response = self.client.put(puturl,
                                   data=json.dumps(input_data),
                                   content_type='application/json')
        data = response.json()
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn('title', response.json())

        self.assertEqual(data['title'], input_data['title'])
def blog_detail(request, pk):
    """
    Get,Update, or delete a specific blog
    """
    #If a blog with the specified key not present, it is handled by catching the exception "DOesNotExist"
    try:
        blog = Blog.objects.get(pk=pk)
    except Blog.DoesNotExist:
        logger.error("ID [%s] does not exist" % str(pk))
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        #Get a blog
        serializer = BlogSerializer(blog)
        logger.info("Getting info for [%s]" % str(pk))
        return Response(serializer.data)
    elif request.method == 'PUT':
        #Update a blog
        serializer = BlogSerializer(blog, data=request.data)
        if serializer.is_valid():
            logger.info("Updating info for [%s]" % str(pk))
            serializer.save()
            return Response(serializer.data)
        logger.error("PUT error : %s" % str(serializer.errors))
        logger.error("HTTP_400_BAD_REQUEST")
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        #delete a blog
        blog.delete()
        logger.info("Deleting info [%s]" % str(pk))
        return Response(status=status.HTTP_204_NO_CONTENT)
Exemple #10
0
def generate_images_data(images, request):
    data = []
    for image in images:
        if image is not None:
            image_data = ImageSerializer(
                image, context={'me': request.user}).data
            blog_data = BlogSerializer(image.publisher).data
            data.append({'image': image_data, 'blog': blog_data})
        else:
            data.append(None)
    return data
Exemple #11
0
def blog_list(request):
    """
    Lists all blogs, or create a new blog
    """
    if request.method == 'GET':
        logger.info("GET method called")
        blogs = Blog.objects.all()
        serializer = BlogSerializer(blogs,many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        logger.info("POST method called")
        logger.info("Data passed : %s"%str(request.data))
        serializer = BlogSerializer(data=request.data)
        if serializer.is_valid():
            logger.info("Valid data passed and created the record")
            serializer.save()
            return Response(serializer.data,status=status.HTTP_201_CREATED)
        else:
            logger.error("%s"%str(serializer.errors))
            logger.error("HTTP_400_BAD_REQUEST")
            return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
Exemple #12
0
def blog_detail(request, blog_id):

    blog = Blog.objects.get(pk=blog_id)

    if request.method == "GET":
        ser = BlogSerializer(blog)
        return JsonResponse(ser.data)

    elif request.method == "PUT":
        data = JSONParser().parse(request)
        ser = BlogSerializer(blog, data)
        if ser.is_valid():
            ser.save()
            return JsonResponse(ser.data)

    elif request.method == "DELETE":
        blog.delete()
        ser = BlogSerializer(blog)
        return JsonResponse(ser.data)
Exemple #13
0
def blog_detail(request, blog_id):
    try:
        blog = BlogApi.objects.get(id=blog_id)
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=400)

    if request.method == "GET":
        ser = BlogSerializer(blog)
        return JsonResponse(ser.data, safe=False)
    elif request.method == "PUT":
        data = JSONParser().parse(request)
        ser = BlogSerializer(blog, data=data)
        if ser.is_valid():
            ser.save()
            return JsonResponse(ser.data, status=201)
    elif request.method == "DELETE":
        blog.delete()
        ser = BlogSerializer(blog)
        return JsonResponse(ser.data, safe=False)
Exemple #14
0
def blog_list(request):
    if (request.method == "GET"):
        blogs = Blog.objects.all()
        serializer = BlogSerializer(blogs, many=True)
        return JsonResponse(serializer.data, safe=False)
    elif (request.method == "POST"):
        blogToAdd = request.POST
        serializer = BlogSerializer(data=blogToAdd)
        if (serializer.is_valid()):
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
def blog_list(request):
    if request.method == 'GET':
        blogs = Blog.objects.all()
        ser = BlogSerializer(blogs, many=True)
        return JsonResponse(ser.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        ser = BlogSerializer(data=data)
    if ser.is_valid():
        ser.save()
        return JsonResponse(ser.data, status=201)

    return JsonResponse(ser.errors, status=400)
Exemple #16
0
def blog_detail(request, pk):
    """
    读取, 更新 或 删除 一个代码片段实例(snippet instance)。
    """
    try:
        snippet = blog.objects.get(pk=pk)
    except blog.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = BlogSerializer(snippet)
        return Response(serializer.data)

    elif request.method == 'DELETE':
        snippet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Exemple #17
0
def blog_list(request):
    """
    列出所有的代码片段(snippets),或者创建一个代码片段(snippet)
    """
    if request.method == 'GET':
        snippets = blog.objects.all()
        serializer = BlogSerializer(snippets, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = BlogSerializer(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)
Exemple #18
0
def blog_list(request):
    try:
        blog = BlogApi.objects.all()
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=400)

    if request.method == "GET":
        blogs = BlogApi.objects.all()
        ser = BlogSerializer(blogs, many=True)
        return JsonResponse(ser.data, safe=False)
    elif request.method == "POST":
        data = JSONParser().parse(request)
        ser = BlogSerializer(data=data)
        if ser.is_valid():
            ser.save()
            return JsonResponse(ser.data, status=201)
        return JsonResponse({"error": str(e)}, status=400)
def blog_list(request):
    """
    Lists all blogs, or create a new blog
    """
    if request.method == 'GET':
        logger.info("GET method called")
        blogs = Blog.objects.all()
        serializer = BlogSerializer(blogs, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        logger.info("POST method called")
        logger.info("Data passed : %s" % str(request.data))
        serializer = BlogSerializer(data=request.data)
        if serializer.is_valid():
            logger.info("Valid data passed and created the record")
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            logger.error("%s" % str(serializer.errors))
            logger.error("HTTP_400_BAD_REQUEST")
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Exemple #20
0
def blogDetail(request, pk):
    blog = Blog.objects.get(id=pk)
    serializer = BlogSerializer(blog, many=False)
    return Response(serializer.data)
Exemple #21
0
def blogList(request):
    blog = Blog.objects.all()
    serializer = BlogSerializer(blog, many=True)
    return Response(serializer.data)
 def get(self, request, format=None):
     blogs = Blog.objects.all()
     serializer = BlogSerializer(blogs, many=True)
     return Response(serializer.data)
 def get(self, request, pk, format=None):
     blog = self.get_object(pk)
     serializer = BlogSerializer(blog)
     return Response(serializer.data)
 def post(self, request, format=None):
     serializer = BlogSerializer(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)
Exemple #25
0
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
Exemple #26
0
def blog_detail(request, blog_id):
    try:
        blog = Blog.objects.get(pk=blog_id)
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=404)
    if (request.method == "GET"):
        serializer = BlogSerializer(blog)
        return JsonResponse(serializer.data)
        blog.delete()
        serializer = BlogSerializer(blog)
        return JsonResponse(serializer.data)
    elif (request.method == "PUT"):
        curBlog = JSONParser().parse(request)
        curBlog = request.POST
        blog.title = curBlog.get('title', '')
        blog.body = curBlog.get('body', '')
        blog.save()
        return JsonResponse(serializer.errors)
        serializer = BlogSerializer(blog, curBlog)
        if (serializer.is_valid()):
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors)
    elif (request.method == "DELETE"):
        blog.delete()
        serializer = BlogSerializer(blog)
        return JsonResponse(serializer.data)