Exemplo n.º 1
0
 def put(self, request, pk, format=None):  
       serializer = PostSerializer(data=request.data,context={'user_id': request.user.id,'method':'PUT','id':pk})
       if serializer.is_valid():
           serializer_2 = PostSerializer(serializer.save())
           r.hset("POSTS",pk,json.dumps(serializer_2.data))
           return Response(serializer.data)
       return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 2
0
 def post(self, request, format=None):   
     serializer = PostSerializer(data=request.data,context={'user_id': request.user.id})
     if serializer.is_valid():
         serializer_2 = PostSerializer(serializer.save())
         r.hset("POSTS",serializer_2.data["id"],json.dumps(serializer_2.data))
         return Response(json.dumps(serializer.data), status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 3
0
    def paginated_posts(self, obj):
        request = self.context['request']
        display_type = obj.display_type
        list = None

        if display_type == SideBar.DISPLAY_HTML:
            return None
        elif display_type == SideBar.DISPLAY_LATEST:
            post = Post.lastes_posts()
            serializer = PostSerializer(post,
                                        many=True,
                                        context={'request': request})
            list = serializer.data
        elif display_type == SideBar.DISPLAY_HOT:
            post = Post.hot_posts()
            serializer = PostSerializer(post,
                                        many=True,
                                        context={'request': request})
            list = serializer.data
        elif display_type == SideBar.DISPLAY_COMMENT:
            comment = Comment.objects.filter(status=Comment.STATUS_NORMAL)
            serializer = CommentSerializer(comment,
                                           many=True,
                                           context={'request': request})
            list = serializer.data
        elif display_type == SideBar.DISPLAY_Author:
            if request.user is None:
                list = []
            else:
                serializer = UserSerializer(request.user, )
                list = [serializer.data]
        return list
Exemplo n.º 4
0
def add_new_post(request):
    if request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = PostSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        else:
            return JsonResponse(serializer.errors, status=400)
Exemplo n.º 5
0
    def retrieve(self, request, pk, format='html'):
        try:
            post = PostSerializer(Post.objects.get(pk=pk))
        except Post.DoesNotExist:
            post = PostSerializer()

        edit = format == 'html' and request.query_params.get('edit', False)
        return Response({'post': post if edit else post.data},
                        template_name='blog/post_edit.html'
                        if edit else 'blog/post_detail.html')
Exemplo n.º 6
0
 def create(self, request, format='html'):
     serializer = PostSerializer(data=request.data)
     if serializer.is_valid():
         post = serializer.save(author=request.user,
                                published_date=timezone.now())
         return self.retrieve(request, post.pk, format)
     else:
         return Response({'errors': serializer.errors},
                         template_name='blog/post_edit.html',
                         status=400)
    def post(self, request, *args, **kwargs):
        
        ser_post = PostSerializer(data = request.data)

        if ser_post.is_valid():
            post_obj = ser_post.save()
            ser_obj = PostSerializer(post_obj)
            return Response(ser_obj.data, status = status.HTTP_201_CREATED)
        else:
            return Response(ser_post.errors, status = status.HTTP_400_BAD_REQUEST)
Exemplo n.º 8
0
    def list(self, request, format='html'):
        edit = format == 'html' and request.query_params.get('edit', False)

        if edit:
            return Response({'post': PostSerializer()},
                            template_name='blog/post_edit.html')
        else:
            serializer = PostSerializer(Post.objects.filter(
                published_date__lte=timezone.now()).order_by('published_date'),
                                        many=True)
            return Response({'posts': serializer.data},
                            template_name='blog/post_list.html')
Exemplo n.º 9
0
def PostCreate(request, pk):
    if (':1:blog{}'.format(pk)) in cache:
        queryset = cache.get(':1:blog{}'.format(pk))
        serializer_class = PostSerializer(queryset)
        return JsonResponse(serializer_class.data)

    else:
        try:
            queryset = Post.objects.get(pk=pk)
            cache.set('blog{}'.format(pk), queryset, timeout=CACHE_TTL)
            serializer_class = PostSerializer(queryset)
            return JsonResponse(serializer_class.data)
        except Post.DoesNotExist:
            return HttpResponse(status=404)
Exemplo n.º 10
0
    def test_posts_retrieve(self):
        post = self.posts[0]

        expected = {'post': PostSerializer(post).data}
        response = self.client.get('/posts/{}/'.format(post.id))

        self.assertEqual(response.data, expected)
Exemplo n.º 11
0
class CrossSearchTagSerializer(serializers.ModelSerializer):
    in_posts = PostSerializer(many=True, read_only=True)
    in_events = EventSerializer(many=True, read_only=True)

    class Meta:
        model = Tag
        fields = ['name', 'in_events', 'in_posts']
Exemplo n.º 12
0
def posts_by_tags(request, tags):
    # Filtrando todos os posts que contem as 'tags' enviadas pelo parametro;
    # distinct() para retirar os posts que contem mais de 1 tag buscada
    posts = Post.objects.filter(tags__name__in=tags.split('+')).distinct()
    serializer = PostSerializer(posts, many=True)

    return JSONResponse(serializer.data)
Exemplo n.º 13
0
def PostList(request):
        """
        Create or list Posts
        """
        if request.method=='GET':
                post = Post.objects.all()
                serializer = PostSerializer(post, many=True)
                return Response(serializer.data)
        
        elif request.method=='POST':
                serializer = PostSerializer(data=request.DATA)
                if serializer.is_valid():
                        serializer.save()
                        return Response(serializer.data, status=status.HTTP_201_CREATED)
                else:
                        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 14
0
def post_detail_api(request, pk):
    try:
        one_post = Post.published.get(pk=pk)
    except Post.DoesNotExist:
        return HttpResponse(status=status.HTTP_404_NOT_FOUND)
    if request.method == 'GET':
        post_detail_serializer = PostSerializer(one_post)
        return JSONResponse(post_detail_serializer.data)
Exemplo n.º 15
0
def post_detail(request, pk):
    """
    Retrieve, update or remove specific post
    """
    try:
        post = Post.objects.get(pk = pk)
    except Post.DoesNotExist:
        return Response(status = status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = PostSerializer(post)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = PostSerializer(data = request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)

        return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        post.delete()
        return Response(status = status.HTTP_204_NO_CONTENT)
Exemplo n.º 16
0
    def get(self, request, site):
        post = Post.objects.filter(blog__site=site)

        if not post:
            return create_response(error={"message": "Post not found"},
                                   status=status.HTTP_404_NOT_FOUND)

        serializer = PostSerializer(post, many=True)
        return create_response(data=serializer.data, status=status.HTTP_200_OK)
Exemplo n.º 17
0
    def test_detail_post(self):
        category = Category.objects.create(name='Technology')
        post = Post.objects.create(title='Python',
                                   content='test content',
                                   category_id=category)

        url = detail_url(post.id)
        res = self.client.get(url)
        serializer = PostSerializer(post)
        self.assertEqual(res.data, serializer.data)
Exemplo n.º 18
0
 def test_no_chinese_fields(self):
     post = Post(title_en="Test blog post title",
                 title_zh_TW="",
                 text_en="I love my new blog post!",
                 text_zh_TW="")
     serializer = PostSerializer(post)
     self.assertEqual(serializer.data['title_zh_TW'], post.title_en)
     self.assertEqual(serializer.data['text_zh_TW'], post.text_en)
     self.assertEqual(serializer.data['title_en'], post.title_en)
     self.assertEqual(serializer.data['text_en'], post.text_en)
Exemplo n.º 19
0
 def test_no_english_fields(self):
     post = Post(title_en="",
                 title_zh_TW=u"我去聖安東尼奧",
                 text_en="",
                 text_zh_TW=u"火山口酒廠來自美國西岸的奧勒岡州")
     serializer = PostSerializer(post)
     self.assertEqual(serializer.data['title_en'], post.title_zh_TW)
     self.assertEqual(serializer.data['text_en'], post.text_zh_TW)
     self.assertEqual(serializer.data['title_zh_TW'], post.title_zh_TW)
     self.assertEqual(serializer.data['text_zh_TW'], post.text_zh_TW)
Exemplo n.º 20
0
    def get(self, request,pk, format=None):     
        posts =self.get_object(pk)
        
        serializer = PostSerializer(posts)
        data = json.loads(json.dumps(serializer.data))

        serializer_all = PostSerializer(Post.objects.all(),many=True)
        all_data = json.loads(json.dumps(serializer_all.data))
     
        key = "POSTS" 
        cache_data = eval(r.hget(key,pk))

        if(data["id"] == cache_data["id"]):
            print("cache")
            return Response(cache_data)
        else :  
            print("cache değil")     
            r.hset(key,data["id"],data)
            return Response(serializer.data)
Exemplo n.º 21
0
 def list(self, request, *args, **kwargs):
     queryset = Post.objects.all().order_by('-updateTime')
     # 实例化分页对象,获取数据库中的分页数据
     paginator = StandardResultsSetPagination()
     page_post_list = paginator.paginate_queryset(queryset,
                                                  self.request,
                                                  view=self)
     # 序列化对象
     serializer = PostSerializer(page_post_list, many=True)
     # 生成分页和数据
     response = paginator.get_paginated_response(serializer.data)
     return response
Exemplo n.º 22
0
    def get(self, request):
        query = request.GET.get('query', None)
        if query:
            print(query)
            qs = Post.objects.all().filter(
                Q(title__startswith=query) | Q(text__startswith=query)
                | Q(labelpost__label_name__startswith=query)
                | Q(user__username__startswith=query)).distinct()

            serializer = PostSerializer(qs, many=True)
            print(serializer)
            print(serializer.data)
            return Response(serializer.data)
Exemplo n.º 23
0
def post_list(request, format=None):
    if request.method == 'GET':
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = PostSerializer(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)
Exemplo n.º 24
0
class ProjectDetailSerializer(serializers.ModelSerializer):
    """
    A serializer for the Project model for use when retrieving a single project object and, therefore, includes all of
    its details.
    """
    keywords = KeywordSerializer(many=True, read_only=True)
    posts = PostSerializer(many=True, read_only=True)

    class Meta:
        model = Project
        fields = [
            'pk', 'url', 'title', 'description', 'description_verbose', 'date_created', 'time_created', 'date_changed',
            'time_changed', 'phase', 'category', 'keywords', 'posts'
        ]
def post_list(request):
    if request.method == 'GET':
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = PostSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
Exemplo n.º 26
0
def post_list(request):
    if request.method == "GET":
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)

        return JSONResponse(serializer.data)
    elif request.method == "POST":
        data = JSONParser.parse(request)
        serializer = PostSerializer(data=data)
        if serializer.is_valid():
            serializer.save(author=request.user)
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
Exemplo n.º 27
0
 def get(self, request):
     try:
         data = Post.objects.all()
         s_data = PostSerializer(data, many=True).data
         return Response(data={
             'status': True,
             "result": s_data
         },
                         status=status.HTTP_200_OK)
     except Exception as e:
         return Response(data={
             'status': False,
             "message": str(e)
         },
                         status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 28
0
    def get(self, request, blog_id, post_id):
        try:
            blog = Blog.objects.get(id=blog_id)
        except Blog.DoesNotExist:
            return create_response(error={"message": "Blog does not exist"},
                                   status=status.HTTP_404_NOT_FOUND)

        try:
            post = blog.blog_posts.get(id=post_id)
        except Post.DoesNotExist:
            return create_response(error={"message": "Post does not exist"},
                                   status=status.HTTP_404_NOT_FOUND)

        serializer = PostSerializer(post)
        return create_response(data=serializer.data, status=status.HTTP_200_OK)
Exemplo n.º 29
0
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = PostSerializer(queryset, many=True)
        response = {'posts': []}
        for data in serializer.data:
            to_append = {'title': '', 'summary': ''}
            to_append.update({
                'id': data['id'],
                'title': data['title'],
                'summary': data['content'][:50],
                'votes': data['votes']
            })
            response['posts'].append(to_append)

        return Response(response)
Exemplo n.º 30
0
 def post(self, request):
     try:
         data = request.data['post']
         data = Post.objects.filter(title__icontains=data)
         s_data = PostSerializer(data, many=True).data
         return Response(data={
             'status': True,
             "result": s_data
         },
                         status=status.HTTP_200_OK)
     except Exception as e:
         return Response(data={
             'status': False,
             "message": str(e)
         },
                         status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 31
0
    def get(self, request, format=None):  

        posts =Post.objects.all()     
        
        serializer = PostSerializer(posts,many=True)
        cache_data = r.hgetall("POSTS")
        if  cache_data :
            cache_data_last = r.hgetall("POSTS")      
            return Response(cache_data_last.values())
        else :
            if posts :
                for obj in json.loads(json.dumps(serializer.data)):
                    r.hset("POSTS",obj["id"],json.dumps(obj))     
                return Response(json.dumps(serializer.data))
            else :    
                return Response("")