def put(self, request, pk):
     article = self.get_object(pk)
     serializer = ArticleSerializer(article, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
 def post(self, request):
     serializer = ArticleSerializer(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)
예제 #3
0
    def put(self, request, pk):
        """Метод для обновления содержимого статьи"""
        article = get_object_or_404(Article, id=pk)
        serializer = ArticleSerializer(article, 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)
예제 #4
0
파일: views.py 프로젝트: xycfree/py_web
 def post(self, request, format=None):
     _data = request.POST
     log.debug('_data: {}'.format(_data))
     serializer = ArticleSerializer(data=request.data)
     log.debug('serializer data: {}'.format(serializer.data))
     if serializer.is_valid():
         serializer['author'] = request.user
         serializer['article_from'] = 0
         serializer['author_id'] = UserProfile.objects.get(
             username=request.user).__dict__.get('id')
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #5
0
    def post(self, request):
        """Создаём пост"""
        request_data = request.data.copy()
        change_data = {
            "owner": request.user.id,
            "slug": slugify(request.data["title"])
        }
        change_value_in_dict(change_data, request_data)
        serializer = ArticleSerializer(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)
예제 #6
0
파일: views.py 프로젝트: xycfree/py_web
def index(request):
    if request.method == 'GET':
        article = Article.objects.filter(status=0).order_by('-create_time')
        serializer = ArticleSerializer(article, many=True)
        log.debug('data: {}, type: {}'.format(serializer.data,
                                              type(serializer.data)))
        return Response(serializer.data, status=status.HTTP_200_OK)
예제 #7
0
 def get(self, request):
     """Методом гет отдаём весь список статей REST API"""
     articles = Article.objects.all()
     serializer = ArticleSerializer(articles,
                                    context={'request': request},
                                    many=True)
     return Response({"articles": serializer.data})
예제 #8
0
def article(request, article_id):
    """
    Display particular blog article, delete particular blog article, update blog article
    """
    try:
        selected_article = Article.objects.get(pk=article_id)
    except Article.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        if selected_article.approval_status:
            serializer = ArticleSerializer(selected_article)
            return Response(serializer.data)
        else:
            return Response(status=status.HTTP_404_NOT_FOUND)
    elif request.method == 'DELETE':
        if 'HTTP_ISADMIN' in request.META:
            if request.META['HTTP_ISADMIN'] == "True":
                selected_article.delete()
                return Response(json.dumps('Successfully deleted'))
            else:
                return Response(json.dumps('Invalid header value'))
        else:
            return Response(json.dumps('IsAdmin header missing'))
    elif request.method == 'PATCH':
        selected_article.approval_status = True
        selected_article.save()
        return Response(json.dumps('{Message: Approved successfully}'))
    else:
        return Response(status=status.HTTP_400_BAD_REQUEST)
예제 #9
0
def article_list(request):
    """
    List all articles.
    """
    if request.method == 'GET':
        articles = Article.objects.all()
        serializer = ArticleSerializer(articles, many=True)
        return JsonResponse(serializer.data, safe=False)
예제 #10
0
 def get(self, request, slug, format=None):
     """
     individual article
     """
     article = self.get_article(slug)
     serializer = ArticleSerializer(article)
     return render_to_response('article.html.haml',
                               {'article': serializer.object})
예제 #11
0
파일: views.py 프로젝트: xycfree/py_web
 def get(self, request, format=None):
     article = Article.objects.filter(status=0).order_by('-create_time')
     serializer = ArticleSerializer(article, many=True)
     log.debug('data: {}, type: {}'.format(serializer.data,
                                           type(serializer.data)))
     code, msg = ('C00000', 'success') if serializer.data else ('C00002',
                                                                '查询无数据')
     res = {'code': code, 'data': serializer.data, 'msg': msg}
     return Response(res, status=status.HTTP_200_OK)
예제 #12
0
    def test_api_most_recent_article(self):
        """
        Test fetching most recent article 
        """
        response = self.client.get('/api/v1/articles/recent/?format=json')

        # fetch the data from db
        expected = Article.objects.filter(machine_name='four_url')
        serialized = ArticleSerializer(expected, many=True)
        self.assertEqual(response.data, serialized.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
예제 #13
0
    def test_api_get_article(self):
        """
        Test fetching an article by machine_name
        """
        response = self.client.get('/api/v1/articles/get/two_url?format=json')

        # fetch the data from db
        expected = Article.objects.get(machine_name='two_url')
        serialized = ArticleSerializer(expected, many=False)
        test = serialized.data
        self.assertEqual(response.data, test)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
예제 #14
0
    def test_api_most_recent_article_range(self):
        """
        Test fetching most recent article using a range
        """
        response = self.client.get(
            '/api/v1/articles/recent/?start_index=1&end_index=3&format=json')

        # fetch the data from db
        expected = Article.objects.order_by('-pub_date')[1:3]
        serialized = ArticleSerializer(expected, many=True)
        self.assertEqual(response.data, serialized.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
예제 #15
0
def article_detail(request, pk):
    """
    Retrieve article.
    """
    try:
        article = Article.objects.get(pk=pk)
    except Article.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = ArticleSerializer(article)
        return JsonResponse(serializer.data)
예제 #16
0
    def test_api_get_all_articles(self):
        """
        This test ensures that all articles added in the setUp method
        exist when we make a GET request to the articles/ endpoint
        """
        # hit the API endpoint
        #response = self.client.get(
        #    reverse("articles-all", kwargs={"version": "v1"})
        #)
        response = self.client.get('/api/v1/articles/all/?format=json')

        # fetch the data from db
        expected = Article.objects.all()
        serialized = ArticleSerializer(expected, many=True)
        self.assertEqual(response.data, serialized.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
예제 #17
0
def article_list(request, format=None):
    """
    List all articles,or create a new article.
    :param request:
    :return:
    """
    if request.method == "GET":
        articles = Article.objects.all()
        # many=True 如果序列化的对象是一个数据集就需要这个参数
        # 如果查询的是一个单一的数据,比如article = Article.objects.get(pk=pk) 就不需要这个参数
        serializer = ArticleSerializer(articles, many=True)
        return Response(serializer.data)
    elif request.method == "POST":
        serializer = ArticleSerializer(data=request.data)
        if serializer.is_valid():
            # 注意:由于序列化器中author是read-only字段,用户是无法通过POST提交来修改的,
            # 我们在创建Article实例时需手动将author和request.user绑定,如下所示:
            serializer.save(author=request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
예제 #18
0
def article_detail(request, pk, format=None):
    """
    Retrieve(检索),update or delete an article instance.
    :param request:
    :param pk:
    :return:
    """
    try:
        article = Article.objects.get(pk=pk)
    except Article.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    if request.method == "GET":
        serializer = ArticleSerializer(article)
        return Response(serializer.data)
    elif request.method == "PUT":
        serializer = ArticleSerializer(article, data=request.data)
        # raise_exception=True自动抛出异常信息
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == "DELETE":
        article.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
예제 #19
0
 def get_articles(self, obj):
     return ArticleSerializer(Article.objects.filter(liked_by__in=[obj]),
                              many=True).data
예제 #20
0
파일: views.py 프로젝트: xycfree/py_web
 def get(self, request, format=None):
     article = Article.objects.filter(author=request.user)[:5]
     serializer = ArticleSerializer(article, many=True)
     return Response(serializer.data)
예제 #21
0
 def get(self, request, pk):
     """Метод для получения данных о статье"""
     article = get_object_or_404(Article, id=pk)
     serializer = ArticleSerializer(article)
     return Response({"article": serializer.data})
예제 #22
0
 def get(self, request, format=None):
     """Handle the get request."""
     serialized = ArticleSerializer(Article.objects.all(), many=True)
     return Response(serialized.data)
예제 #23
0
 def get(self, request, format=None):
     articles = Article.objects.all()
     serializers = ArticleSerializer(articles)
     return render_to_response('articles.html.haml',
                               {'articles': serializers.object})
예제 #24
0
파일: views.py 프로젝트: v4iv/BlogEngine
 def get(self, request, slug, format=None):
     about = self.get_object(slug)
     serializer = ArticleSerializer(about)
     return Response(serializer.data)
 def get(self, request, pk):
     article = self.get_object(pk)
     serializer= ArticleSerializer(article)
     return Response(serializer.data)
예제 #26
0
 def get(self, request, pk, format=None):
     articles = self.get_object(request, pk)
     serializer = ArticleSerializer(articles, many=True)
     return Response(serializer.data)
 def get(self, request):
     articles = Article.objects.filter(active=True)
     serializer = ArticleSerializer(articles, many=True)
     return Response(serializer.data)