def top(self, request): """获取界面顶部的新闻: 轮播图, 推荐新闻, 图片新闻""" ''' 返回的数据格式如下: { 'slide_news': [{第1条新闻}, {第2条新闻}, ...], 'top_news': [{第1条新闻}, {第2条新闻}, ...], 'image_news': [{第1条新闻}, {第2条新闻}, ...] } ''' # 轮播图新闻 news_slide = News.objects.filter(is_slide=True).exclude(img_url='') # 推荐新闻 news_top = News.objects.order_by('-create_time')[0:10] # 图片新闻 news_image = News.objects.exclude(img_url='').order_by('-click')[0:4] serializer_slide = NewsSerializer(news_slide, many=True) serializer_top = NewsSerializer(news_top, many=True) serializer_imgs = NewsSerializer(news_image, many=True) context = { 'slide_news': serializer_slide.data, 'top_news': serializer_top.data, 'image_news': serializer_imgs.data, } return Response(context)
def category(self, request): """获取类别新闻""" ''' 返回的数据格式如下: [ { # 第1个大类别 'id': 3, 'title': '互联网媒体', 'category_set': [{'id':x1, 'title': '子类别1'}, {'id':x2, 'title': '子类别2'}], 'news': [], 'top8': [], }, { # 第2个大类别 'id': 4, 'title': '科技财经', 'category_set': [{'id':x1, 'title': '子类别1'}, {'id':x2, 'title': '子类别2'}] 'news': [{新闻1},{新闻2}...], 'top8': [{新闻1},{新闻2}...] }, ... ] ''' list_data = [] # 获取一级大类别 categories = NewsCategory.objects.filter(parent_id=0) # 遍历每一个大类别 for category in categories: dict_category = NewsCategorySerializer(category).data # 设置类别新闻 child_category_ids = [category.id] # 设置二级子类别 child_category_set = category.newscategory_set.all() for category in child_category_set: child_category_ids.append(category.id) news_set = News.objects.filter(category_id__in=child_category_ids)\ .order_by('-create_time').exclude(img_url='')[0:4] news_list = NewsSerializer(news_set, many=True).data dict_category['news'] = news_list # 设置最热门的8条新闻 top8 = News.objects.filter( category_id__in=child_category_ids).order_by('-click')[0:8] news_list = NewsSerializer(top8, many=True).data dict_category['top8'] = news_list # 把一个大类别添加到列表中 list_data.append(dict_category) return Response(list_data)
def post(self, request: Request, format=None) -> 'Response': """ Handle POST HTTP Request :param request: Request object :param format: Whether use or not format suffixes :return: Response with JSON News data if News was successfully created, otherwise Response with 400 status code """ serializer = NewsSerializer(data=request.data) if serializer.is_valid(): serializer.save(author=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def list(self, request, pk=None): queryset = News.objects.all() if self.request.user.is_authenticated: interests = self.request.user.interests.all() id_list = [] for interest in interests: id_list.append(interest.id) queryset = News.objects.filter(category__in=id_list) serializer = NewsSerializer(queryset, many=True) return Response(serializer.data) else: queryset = News.objects.all() serializer = NewsSerializer(queryset, many=True) return Response(serializer.data)
def get(self, request): slide_news = News.objects.filter(is_slide=1).exclude(img_url='') top_news = News.objects.order_by('-create_time')[:10] img_news = News.objects.order_by('-click').exclude(img_url='')[:4] slide_news = NewsSerializer(slide_news, many=True).data top_news = NewsSerializer(top_news, many=True).data img_news = NewsSerializer(img_news, many=True).data data = { 'slide_news': slide_news, 'top_news': top_news, 'img_news': img_news, } return Response(data)
def news_list(request): """ List all code news, or create a new news. """ if request.method == 'GET': news = News.objects.all() serializer = NewsSerializer(news, many=True,context={'request': request}) return JSONResponse(serializer.data) elif request.method == 'POST': data = JSONParser().parse(request) serializer = NewsSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400)
def test_get(self): url = reverse("news-list") response = self.client.get(url) data = NewsSerializer([self.news_1, self.news_2], many=True).data self.assertEqual(status.HTTP_200_OK, response.status_code) self.assertEqual(data, response.data)
def get_news(request): """ List all news """ if request.method == 'GET': news = News.objects.all() serializer = NewsSerializer(news, many=True) return JsonResponse(serializer.data, safe=False)
def get(self, request): start = int(request.GET.get('start', 0)) count = int(request.GET.get('count', 10)) all_news = News.objects.all() all_news = all_news[start:start + count] serializer = NewsSerializer(all_news, many=True) return Response(serializer.data)
def get_news(request, id): """ A function that gets news from a category id """ get_object_or_404(Category, id=id) queryset = News.objects.filter(category=id, deleted__isnull=True) serializer = NewsSerializer(queryset, many=True) return JsonResponse(serializer.data, safe=False)
def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) news = NewsSerializer(queryset, many=True, context={'request': request}) kaz = [d['kaz'] for d in news.data] rus = [d['rus'] for d in news.data] return Response({'kaz': kaz, 'rus': rus})
def sync(request): data = request.data user = request.user new = News.objects.all().filter(is_show=True).order_by("-id")[:3] return JsonResponse(data={ 'news': NewsSerializer(new, many=True).data, })
def put(self, request: Request, news_id, format=None) -> 'Response': """ Handle PUT HTTP Request :param request: Request object :param news_id: ID of News to update :param format: Whether use or not format suffixes :return: Response with JSON News data if News was successfully updated, otherwise Response with 400 status code """ news = News.get_by_id(news_id) if not news: return Response(status=status.HTTP_404_NOT_FOUND) serializer = NewsSerializer(news, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request: Request, news_id: int = None, format=None) -> Response: """ Handle GET HTTP Request :param request: Request object :param news_id: ID of News to get :param format: Whether use or not format suffixes :return: Response with JSON News data if request was handled successfully, otherwise Response with 404 status code """ if news_id: news = News.get_by_id(news_id) if not news: return Response(status=status.HTTP_404_NOT_FOUND) serializer = NewsSerializer(news) return Response(serializer.data) all_news = News.objects.all() response = NewsSerializer(all_news, many=True) return Response(response.data)
def news_upload(request): """ Add a new news. """ if request.method == 'PUT': data = JSONParser().parse(request) data["content"] = "\n".join([k[5:] for k in data["content"] if not k.startswith("img:")]) data["coverimg"] = "" for k in data["content"]: if k.startswith("img:"): data["coverimg"] = k break serializer = NewsSerializer(data=data) if serializer.is_valid(): try: serializer.save() return JsonResponse(serializer.data) except IntegrityError: pass return JsonResponse(serializer.errors, status=400)
def setUp(self): self.news_attributes = { 'title': "Don't just roll the dice – Software pricing guide (2012) [pdf] ", 'url': "https://neildavidson.com/downloads/dont-just-roll-the-dice-2.0.0.pdf", 'created': datetime.datetime.now().isoformat() } self.news = Post.objects.create(**self.news_attributes) self.serializer = NewsSerializer(instance=self.news)
def get_news_detail(request, news_id): """ Get one news with id """ try: news = News.objects.get(id=news_id) except News.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = NewsSerializer(news) return JsonResponse(serializer.data, safe=False)
def get(self, request, *args, **kwargs): """ Fetch data from NewsPuller service :param request: :param args: :param kwargs: :return: """ data = puller.fetch() serializer = NewsSerializer(data, many=True) return Response(serializer.data)
def news_detail(request, href): """ Retrieve a news. """ print(href) try: news = News.objects.get(href=href[:-1]) except News.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = NewsSerializer(news) return JsonResponse(serializer.data)
def get(self, reqeust): bcats = NewsCategory.objects.filter(parent=0) # bcats_data=CatSerializer(bcats,many=True).data b_cats_list = [] for bcat in bcats: scats = bcat.newscategory_set.all() bcat = CatSerializer(bcat).data ids = [] for scat in scats: ids.append(scat.id) news = News.objects.filter(category_id__in=ids).exclude( img_url='').order_by('-create_time')[:4] news = NewsSerializer(news, many=True).data bcat['news'] = news top8 = News.objects.filter( category_id__in=ids).order_by('-create_time')[:8] top8 = NewsSerializer(top8, many=True).data bcat['top8'] = top8 b_cats_list.append(bcat) return Response(b_cats_list)
def news_detail(request, pk): """ Retrieve, update or delete a code news. """ try: news = News.objects.get(pk=pk) except News.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = NewsSerializer(news) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = NewsSerializer(news, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': news.delete()
def retrieve(self, request, pk=None): queryset = self.get_queryset() news = get_object_or_404(queryset, pk=pk) serializer = NewsSerializer(news, context={'request': request}) return Response(serializer.data)
# <editor-fold desc="Seializer storing"> from news.serializers import NewsSerializer data = {"title": "this is title 1", "sentiment": "pn"} serializer = NewsSerializer(data=data) serializer.is_valid() serializer.save() serializer.validated_data data = { "title": "Pep Guardiola has played down suggestions that Lionel Messi could join him at Manchester City and believes " "the forward will end his playing days at Barcelona", "sentiment": "pn", "entities4thisnews": [{ "entity": "Pep Guardiola", }, { "entity": "Lionel Messi", }, { "entity": "Manchester City", }, { "entity": "Barcelona", }] } # </editor-fold> # <editor-fold desc="request data-News"> import requests import json
def retrieve(self, request, *args, **kwargs): queryset = News.objects.all() user = get_object_or_404(queryset, pk=kwargs.get('pk')) serializer = NewsSerializer(user) return Response(serializer.data)
def setUp(self): self.news = News.objects.create( title="some news", preview="test.png", text="something new" ) self.serialized_news = NewsSerializer(self.news)
class ListSaveNewsSerializer(serializers.ModelSerializer): news = NewsSerializer() class Meta: model = SaveNews fields = '__all__'