Beispiel #1
0
def publish(request):
  if not request.user.is_authenticated():
    return HttpResponseRedirect('/news/login')  
#  if request.user.is_superuser == 0:
#    return HttpResponse('You are not super user, can not publish an article.')
 
  from urllib import unquote
  news_id = News.objects.all().count()
  if request.method == 'POST':
    form = PublishForm(request.POST)
    if form.is_valid():
      p_subject = form.cleaned_data['p_subject']
      p_content = form.cleaned_data['p_content']
      p_author = form.cleaned_data['p_author']
#      p_subject = p_subject.decode('utf-8')
#      p_content = unquote(unicode(p_content).encode('utf-8'))
#      p_author = p_author.decode('utf-8')
      
      n = News(subject=p_subject, content=p_content, author=p_author)
      n.save()
      p_id=n.id
       
      return HttpResponseRedirect('/news/' + str(p_id))
  else:
    form = PublishForm()
  return render(request, 'news/publish.html', { 
      'form': form,
      'back': news_id,
  })
Beispiel #2
0
 def test_slug_unique(self):
     """Comprueba que el slug sea único."""
     news = News(name="Noticia 1",
                 abstract="Resumen de la noticia 1",
                 description="Contenido de la noticia 1")
     with self.assertRaises(IntegrityError):
         news.save()
Beispiel #3
0
def publish(request):
  if util.is_param_empty('text', request.GET) or \
    util.is_param_empty('title', request.GET) or \
    util.is_param_empty('about', request.GET) or \
    util.is_param_empty('fb_id', request.GET) or \
    util.is_param_empty('msg_id', request.GET):
      return HttpResponse('ERR')

  # Find who is the news about
  about_id = _find_facebook_user(request.GET['fb_id'])
  anonymous = True if 'anonymous' in request.GET else False

  # Create the news
  news = News()
  news.user = request.user
  if about_id:
    news.about_id_id = about_id
  else:
    news.about_name = request.GET['about'].strip().title()
  news.title = request.GET['title'].strip().title()
  news.text = request.GET['text'].strip()
  news.anonymous = anonymous
  news.source = 1
  news.save();

  # Update the fb_news counter
  FbNews.objects.filter(id=request.GET['msg_id']).update(counter_used=F('counter_used') + 1, last_used=datetime.datetime.now())

  return HttpResponse(news.id)
Beispiel #4
0
def newsReleaseViews(request):
    """
    mxl
    """
    if request.method == 'POST':
        files = request.FILES.getlist("news_document")
        newsform = NewsForm(request.POST)
        if newsform.is_valid():
            new_news = News(news_title = newsform.cleaned_data["news_title"],
                             news_content = newsform.cleaned_data["news_content"],
                             news_date = newsform.cleaned_data["news_date"],
                             news_category = NewsCategory.objects.get(id = newsform.cleaned_data["news_category"])
                            )
            new_news.save()
        if files:
            for f in files:
                doc = DocumentFile(news_document = f,
                                    news = new_news)
                doc.save()
        # return redirect("/news/newslist/%s" % new_news.id)
        return redirect("/management/newsManagement")
    else:
        newsform = NewsForm()
        context = {
            'newsform' : newsform
        }
        return render(request, "management/news_release.html", context)
Beispiel #5
0
def Release_News(request):
    '''
    Release_News
    '''
    unsubjected = False
    subject_list = ProjectSingle.objects.all().order_by('school').exclude(
        school__schoolName=u'测试用学校')
    for project in subject_list:
        if project.project_grade.grade == GRADE_UN:
            unsubjected = False
            break

    if unsubjected:
        release = False
    else:
        html = refresh_member_table(subject_list)
        release = True
        title = datetime.datetime.today().year
        data = News(news_title=title.__str__() + '年创新项目级别汇总',
                    news_content=html,
                    news_category=NewsCategory.objects.get(
                        category=NEWS_CATEGORY_ANNOUNCEMENT))
        data.save()
    loginfo(p=release, label="release")
    return simplejson.dumps({'release': release})
Beispiel #6
0
 def post(self, request):
     today_news = News.objects.filter(updated_at__gte=date.today()).all()
     form = NewsForm(self.request.POST)
     if form.is_valid():
         _new = News(title=self.request.POST["title"], body=self.request.POST["body"])
         _new.save()
         form = NewsForm1()
     return render(self.request, 'news/index.html', context={'news': today_news, 'form': form})
Beispiel #7
0
    def get(self, request, news_id):
        title = '详情页'
        news = News.objects.select_related('tag', 'author'). \
            only('title', 'update_time', 'author__username', 'tag__name', 'clicks', 'content'). \
            filter(is_delete=False, id=news_id).first()
        if not news:
            return render(request, '404.html')
        hot_news = News.objects.only(
            'title', 'image_url', 'update_time',
            'clicks').filter(is_delete=False).order_by('-clicks')[0:10]
        News.increase_click(news)
        comments = Comments.objects.filter(is_delete=False,
                                           news_id=news_id).order_by('-id')

        comment_list = []
        for comment in comments:
            thumbs = ThumbsUpClicks.objects.filter(author_id=request.user.id,
                                                   comments_id=comment.id,
                                                   is_delete=False).first()
            if thumbs:
                is_thumbs = True if not thumbs.is_delete else False
            else:
                is_thumbs = False

            if not comment.parent_id:
                comment_list.append({
                    'news_id':
                    comment.news_id,
                    'content_id':
                    comment.id,
                    'content':
                    comment.content,
                    'author':
                    comment.author,
                    'update_time':
                    comment.update_time,
                    'is_thumbs':
                    is_thumbs,
                    'clicks':
                    comment.clicks if comment.clicks != 0 else "赞",
                    'child_list': []
                })
        for one_comment in comments:
            if one_comment.parent:
                for parent_comment in comment_list:
                    if one_comment.parent_id == parent_comment['content_id']:
                        parent_comment['child_list'].append(one_comment)
        num_news = News.objects.filter(is_delete=False).count()

        return render(request,
                      'news/news_detail.html',
                      context={
                          'news': news,
                          'title': title,
                          'hot_news': hot_news,
                          'comment_list': comment_list,
                          'num_news': num_news
                      })
Beispiel #8
0
def save_thumbnail_news(sender, instance: News, **kwargs):
    if not instance.disable_signals:
        thumbnail_file = ThumbnailCreator.get_thumbnail(instance.icon.name)
        thumbnail_file.save(
            './media/news_thumbnails/thumbnail_{}.png'.format(instance.id),
            "PNG")
        instance.thumbnail = 'news_thumbnails/thumbnail_{}.png'.format(
            instance.id)
        instance.save_without_signals()
Beispiel #9
0
def post_news(text):
    news = News(text=text)
    try:
        news.save()
        for t in TeamProfile.objects.all():
            t.nb_unread_news += 1
            t.save()
    except Exception:
        logger.exception("Error adding news: ")
Beispiel #10
0
def readd_all_commits(request):
    if request.user.is_superuser:
        try:
            all_commits = go_news_commit()
            News.objects.filter(news_type=2).delete()
            for news_date, news_text in go_news_commit().items():
                news_item = News(
                            title = news_text,
                            created_date = datetime.strptime(news_date, '%Y-%m-%d %H:%M:%S'),
                            news_type = 2,
                            parsed_date = timezone.now(),
                            )
                news_item.save()

            data = {
                'news_commit': go_news_commit(),
            }
            
            log = Logs(
                    log_user = request.user, 
                    log_type = 7, 
                    log_status = LOGSTATUSYES,
                    )
            log.save()
            state = {
                'state_type':'success',
                'state_message':'<strong>Отлично!</strong> Все прошло как надо! Добавлено коммитов: %s' % (len(all_commits)),
                    }
            data = {
                'news_commit': all_commits,
                'state':state,
                }
            return render(request,
                            'admin/readd_all_commits.html',
                            data,)
        except Exception as inst:
            import sys
            log = Logs(
                    log_user = request.user, 
                    log_type = 7, 
                    log_status = LOGSTATUSNO,
                    )
            log.save()
            state = {
                'state_type':'danger',
                'state_message':inst,
                    }
            data  = {
                'state':state,
                    }
            return render(request,
                            'admin/readd_all_news_wed.html',
                            data,)

    else:
        return HttpResponseRedirect('/')
Beispiel #11
0
def add_post(request):
    if 'email' in request.session:
        if request.POST:
            news = News(title=request.POST['title'], publicator=request.session['name'], text=request.POST['message'])
            news.save()
        else:
            return render_to_response('news/add_post.html', {'user': request.session,
                                                             'login': True,
                                                             'edit': False})
    return HttpResponseRedirect('/')
Beispiel #12
0
def news_factory():
    fake = Faker(locale=['en'])
    title = fake.name()
    preview_content = fake.name()
    content = f'{title}\n{preview_content}'
    news = News(title=title,
                preview_content=preview_content,
                content=content)
    news.save()
    return news
Beispiel #13
0
    def test_edit_news(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости ++'
        news.text = 'Текст первой новости!!!'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        self.client.login(username='******', password='******')

        response = self.client.post('/admin/news/news/' + str(news.id) + '/', {
            'title': 'Моя вторая новость',
            'announcement': 'Анонс второй новости',
            'text': 'Текст второй новости',
            'pub_date_0': '2014-10-15',
            'pub_date_1': '16:07:00',
            'category': str(category.id)
        },
                                    follow=True)

        self.assertContains(response, 'успешно изменен', status_code=200)

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)
        only_news = all_news[0]
        self.assertEquals(only_news.title, 'Моя вторая новость')
        self.assertEquals(only_news.announcement, 'Анонс второй новости')
        self.assertEquals(only_news.text, 'Текст второй новости')
Beispiel #14
0
def create_news(request):
    """
    view untuk pembuatan berita
    """
    if not request.user.has_perm('news.add_news'):
        messages.error(request, _("Unvalidated user can not create news"))
        return HttpResponseRedirect(reverse('validate'))
    if request.POST:
        form = CreateNewsForm(request.POST)
        if form.is_valid():
            news = News()
            news.user = request.user
            news.title = form.cleaned_data['title']
            news.content = form.cleaned_data['content']
            news.category = form.cleaned_data['category']
            news.enable_comment = form.cleaned_data['enable_comment']
            news.location = form.cleaned_data['location']
            news.save()
            news.images.add(*request.POST.getlist('images'))
            p = Point(news=news, user=request.user)
            p.save()
            messages.info(request, _('A news %s created') % news.title)
            return HttpResponseRedirect(reverse('user_news'))
    else:
        form = CreateNewsForm()
    return render_to_response('news/create_news.html',
            {'form': form},
            context_instance=RequestContext(request))
Beispiel #15
0
    def test_delete_new(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости ++'
        news.text = 'Текст первой новости!!!'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)

        self.client.login(username='******', password='******')

        response = self.client.post('/admin/news/news/' + str(news.id) +
                                    '/delete/', {'post': 'yes'},
                                    follow=True)
        self.assertContains(response, 'успешно удален', status_code=200)

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 0)
Beispiel #16
0
    def test_news_expiry_date_is_today(self):
        t1 = timezone.make_aware(timezone.datetime(2017, 11, 22))
        t2 = timezone.make_aware(timezone.datetime(2017, 11, 23))
        news_1 = News(publish_date=t1,
                      status=CONTENT_STATUS_PUBLISHED,
                      expiry_date=t2)

        self.assertIsNotNone(news_1)
        news_1.save()
        homepage_list = News.objects.published()
        self.assertTrue(len(homepage_list) == 0)
Beispiel #17
0
 def test_name_length_validation(self):
     """Comprueba la longitud del nombre."""
     news = News(
         name="Officia mollit esse eiusmod dolor mollit Lorem. Ut sint"\
             "deserunta eiusmod dolor mollit",
         slug="test-slug",
         abstract="Officia mollit",
         description="Nulla consectetur"
     )
     with self.assertRaisesRegex(ValidationError, "(name).*(64)"):
         news.full_clean()
Beispiel #18
0
def add_news(request, course_id):
    if request.method == 'POST':
        text = request.POST['add-news']

        course = get_object_or_404(Course, pk=course_id)
        news = News(user=request.user, course=course, text=text)
        news.save()

        return redirect('training:cabinet', course_id=course_id)
    else:
        return redirect('training:cabinet', course_id=course_id)
Beispiel #19
0
def news_release():
    #进行页面渲染
    if request.method == "GET":
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=Code.DBERR, errmsg="获取分类失败")

        category_list = []
        for category in categories:
            category_list.append(category.to_dict())

        return render_template("news/user_news_release.html",
                               categories=category_list)

    # 数据提交
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")

    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=Code.PARAMERR, errmsg="参数不全")

    try:
        #读取图片为二进制数据,上传
        image_name = image_storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=Code.THIRDERR, errmsg="七牛云异常")

    if not image_name:
        return jsonify(errno=Code.NODATA, errmsg="图片上传失败")

    news = News()
    news.title = title
    news.source = g.user.nick_name
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.category_id = category_id
    news.user_id = g.user.id
    news.status = 1  #表示审核中

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=Code.DBERR, errmsg="新闻发布失败")
    # print("发布成功")
    return jsonify(errno=Code.OK, errmsg="发布成功")
Beispiel #20
0
def addnews(csvfile):
    csvdata = csv.reader(open(csvfile), dialect="excel")
    print csvdata.next()
    userinput =  raw_input("Is this ok? yes/no: ")
    if userinput == "yes":
        for line in csvdata:
            news = News(title=unicode(line[0]), body=unicode(line[1]), author=unicode(line[2]))
            news.save()
    else:
        ret = "Aborted by user"
        return ret
Beispiel #21
0
 def done(self, request, cleaned_data):
     
     # http://stackoverflow.com/questions/628132/django-form-preview-how-to-work-with-cleaned-data
     #  **cleaned_data 
     # news = News(**{'key':'value',})
     news = News(**cleaned_data)
     news.publish_date = datetime.now()
     news.save()
     
     # Redirect
     url = reverse('news-detail', kwargs={'slug': news.slug})
     return HttpResponseRedirect(url)
Beispiel #22
0
 def test_abstract_length_validation(self):
     """Comprueba la longitud del resumen."""
     news = News(
         name="Officia mollit esse eiusmod dolor mollit Lorem.",
         slug=slugify("Officia mollit esse eiusmod dolor mollit Lorem."),
         abstract="Lorem ipsum dolor sit amet, consectetuer adipiscing"\
             "elit. Aenean commodo ligula eget dolor. Aenean massa. Cum"\
             "sociis natoque penatibus et magnis dis parturient montes, na",
         description="Nulla consectetur"
     )
     with self.assertRaisesRegex(ValidationError, "(abstract).*(140)"):
         news.full_clean()
Beispiel #23
0
    def done(self, request, cleaned_data):

        # http://stackoverflow.com/questions/628132/django-form-preview-how-to-work-with-cleaned-data
        #  **cleaned_data
        # news = News(**{'key':'value',})
        news = News(**cleaned_data)
        news.publish_date = datetime.now()
        news.save()

        # Redirect
        url = reverse('news-detail', kwargs={'slug': news.slug})
        return HttpResponseRedirect(url)
Beispiel #24
0
def addnews(csvfile):
    csvdata = csv.reader(open(csvfile), dialect="excel")
    print csvdata.next()
    userinput = raw_input("Is this ok? yes/no: ")
    if userinput == "yes":
        for line in csvdata:
            news = News(title=unicode(line[0]),
                        body=unicode(line[1]),
                        author=unicode(line[2]))
            news.save()
    else:
        ret = "Aborted by user"
        return ret
Beispiel #25
0
def news_index(request):
    if request.method == "GET":
        today_news = News.objects.filter(updated_at__gte=date.today()).all()
        form = NewsForm()
        return render(request, 'news/index.html', context={'news': today_news, 'form': form})
    elif request.method == "POST":
        today_news = News.objects.filter(updated_at__gte=date.today()).all()
        form = NewsForm(request.POST)
        if form.is_valid():
            _new = News(title=request.POST["title"], body=request.POST["body"])
            _new.save()
            form = NewsForm()
        return render(request, 'news/index.html', context={'news': today_news, 'form': form})
Beispiel #26
0
    def test_category_page(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)
        only_news = all_news[0]
        self.assertEquals(only_news, news)

        category_url = news.category.get_absolute_url()
        response = self.client.get(category_url)
        self.assertContains(response, news.category.name, status_code=200)

        #проверяем атрибуты
        self.assertEquals(only_news.title, 'Моя первая новость')
        self.assertEquals(only_news.announcement, 'Анонс первой новости')
        self.assertEquals(only_news.pub_date.day, news.pub_date.day)
        self.assertEquals(only_news.pub_date.year, news.pub_date.year)
Beispiel #27
0
 def post(self, request):
     today_news = News.objects.filter(updated_at__gte=date.today()).all()
     form = NewsForm(self.request.POST)
     if form.is_valid():
         _new = News(title=self.request.POST["title"],
                     body=self.request.POST["body"])
         _new.save()
         form = NewsForm1()
     return render(self.request,
                   'news/index.html',
                   context={
                       'news': today_news,
                       'form': form
                   })
Beispiel #28
0
def news_index(request):
    if request.method == "POST":
        form = NewsForm(request.POST)
        if form.is_valid():
            _new = News(**form.cleaned_data)
            _new.save()
            return HttpResponseRedirect('/news/')

    else:
        form = NewsForm()

    today_news = News.objects.filter(updated_at__gte=date.today()).all()
    return render(request, 'news/index.html',
                  context={'news': today_news, 'form': form})
Beispiel #29
0
    def test_delete_new(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости ++'
        news.text = 'Текст первой новости!!!'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)

        self.client.login(username='******', password='******')

        response = self.client.post('/admin/news/news/' + str(news.id) + '/delete/', {
            'post':'yes'
            },
            follow=True
            )
        self.assertContains(response, 'успешно удален', status_code=200)

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 0)
Beispiel #30
0
def index(request):
    datas = newscraw()
    newsAdded = False
    for data in datas:
        title, content, link, fulltext = data["title"], data["content"], data[
            "link"], data["fulltext"]
        if len(News.objects.filter(title=title)) == 0:
            newNews = News(title=title,
                           content=content,
                           link=link,
                           fulltext=fulltext)
            newNews.save()
            newsAdded = True
    return render(request, 'index.html', {"added": newsAdded})
Beispiel #31
0
def new_post(blog_id, username, password, post, publish):
    user = authenticate(username, password)
    item = News()
    item.title = post['title']
    item.description = post['description']
    if post.get('dateCreated'):
        item.dateCreated  = datetime.strptime(str(post['dateCreated']),'%Y%m%dT%H:%M:%S')
    else:
        item.dateCreated = datetime.now().date()
    item.author = user
    item.publish = publish
    item.categories = Categories.objects.get(name=u'Новости сайта')
    item.save()
    return item.pk
Beispiel #32
0
def add(request):
	news = News()
	context = {}

	if request.method == 'POST':
		news.title = request.POST.get('title','')
		news.text = request.POST.get('text','')
		news.user = request.user

		try:
			if request.POST.get('preview', 'no-preview') != 'no-preview':
				news.check()
				context['preview'] = True

			else:
				news.save()
				success_msg(request, "Message created successfully.")
				return redirect('news-news')

		except news.Error as error:
			error_msg(request, "Could not create the message because of some errors.")
			context['error'] = error
	
	context['news'] = news

	return render(request,'news/add.html', context)
Beispiel #33
0
def save_news(title, url, published):
    news_exist = News.query.filter(News.url == url).count()
    print(news_exist)
    if not news_exist:
        new_news = News(title=title, url=url, published=published)
        db.session.add(new_news)
        db.session.commit()
Beispiel #34
0
def pick_top_headlines():
    newsapi = NewsApiClient(api_key=settings.NEWS_API_KEY)
    for category in categories:
        top = newsapi.get_top_headlines(country='ua', category=category)
        logger.info(f'receive top headlines in {category}')
        category_obj = Category.objects.get(slug=category)
        if top['status'] == 'ok':
            articles = top['articles']
            news = []
            for article in articles:
                one_news = News(
                    category=category_obj,
                    author=article['author'] or '',
                    title=article['title'] or '',
                    description=article['description'] or '',
                    url=article['url'] or '',
                    url_to_image=article['urlToImage'] or '',
                    published_at=make_aware(
                        datetime.datetime.strptime(article['publishedAt'],
                                                   '%Y-%m-%dT%H:%M:%SZ')),
                    content=article['content'] or '',
                )
                news.append(one_news)
            News.objects.bulk_create(news, ignore_conflicts=True)
            logger.info(f'save received news in {category} to db')
Beispiel #35
0
def news_add(request):
    if request.method == 'POST':
        '''
        每创建一条记录时,
        字段都要填写完整,
        这里由于用户模块还没完善,
        所以写死了user_id=1,
        并把此实例传给表单保存
        '''
        user = Users.objects.get(user_id=1)
        news = News(user=user)
        # 这里有上传文件的功能,所以可用request.FILES代替request.POST
        form = NewsAddModelForm(request.POST or None,
                                request.FILES or None,
                                instance=news)
        if form.is_valid():
            form.save()
            print('success')
            messages.add_message(request, messages.SUCCESS, '文章发布成功,等待管理员审核!')
            return redirect('/')
        else:
            messages.add_message(request, messages.WARNING, '检查您输入的信息是否正确!')
    else:
        form = NewsAddModelForm()
        messages.add_message(request, messages.WARNING,
                             '如果要发布信息,那么每一个字段都要填写...')
    template = get_template('news_add.html')
    request_context = RequestContext(request)
    request_context.push(locals())
    html = template.render(request_context)

    return HttpResponse(html)
Beispiel #36
0
    class Meta:  # 元数据信息
        # 指定那个数据库模型来创建表单
        model = News()  # 与数据库模型关联

        # fields = ['title', 'author', 'digest', 'content', 'image_url', 'tag']
        fields = ['title', 'digest', 'content', 'image_url', 'tag']

        error_messages = {
            'title': {
                'max_length': "文章标题长度不能超过150",
                'min_length': "文章标题长度大于1",
                # 传入字符串为空和,传入为空格是有区别的
                'required': '文章标题不能为空',
            },
            'digest': {
                'max_length': "文章摘要长度不能超过200",
                'min_length': "文章标题长度大于1",
                'required': '文章摘要不能为空',
            },
            'content': {
                'required': '文章内容不能为空',
            },
            # 'author': {
            #     'required': '作者不能为空',
            # },
        }
Beispiel #37
0
class Connection(graphene.Connection):

    total_count = graphene.Int()
    pages = graphene.Int()
    per_page = graphene.Int()
    current_page = graphene.Int()

    try:
        total = News.get_news_items().count()
    except:
        total = 0

    class Meta:
        abstract = True

    def resolve_total_count(self, __):
        return self.total

    def resolve_pages(self, __):
        return int(ceil(self.total / float(s.NEWS_PERPAGE)))

    @staticmethod
    def resolve_per_page(_, __):
        return s.NEWS_PERPAGE

    @staticmethod
    def resolve_current_page(_, info):
        return info.variable_values.get('page', 1)
Beispiel #38
0
    def search(self, subject) -> list:
        """pesquisa notícias de acordo com o assunto especificado

        Arguments:
            subject {string} -- assunto pesquisado

        Returns:
            list -- lista de notícias encontradas
        """
        url = self.get_url_search(subject)
        page = requests.get(url)
        soup = BeautifulSoup(page.text, 'html.parser')

        container_list = soup.find_all(class_=self.container_class)
        news_list = []

        for news in container_list:
            figure_url = self.get_figure_url(news)
            title = self.get_title(news)
            published_at = news.find(class_=self.published_class).contents[0]

            founded = News(figure_url, title, published_at, subject, self.name)

            news_list.append(founded)

        return news_list
Beispiel #39
0
def insert_into_db():
    url = 'https://news.ycombinator.com'
    #connection to web page
    htmlfile = urllib2.Request(url, headers={'User-Agent' : "Browser"})
    htmlopen = urllib2.urlopen(htmlfile)
    # read html
    htmltext = htmlopen.read()
    # web scrapper
    soup = BeautifulSoup(htmltext)
    link = soup.findAll(attrs={'class': 'title'})
    #insert news titles into database
    for title in link:
        if len(title.attrs) == 1 and title.text != 'More':
            news_object = News()
            news_object.name = title.text
            news_object.save()
Beispiel #40
0
 def process_item(self, item, spider):
     # print item['owner'], item['title'], item['time_way']
     if self.NAME not in getattr(spider, 'pipelines', []):
         return item
     news = News()
     news.content = item['content']
     # news.editor = item['editor']
     news.pub_time = item['pub_time']
     news.source = item['source']
     news.title = item['title']
     news.abstract = item['abstract']
     news.save()
     return item
Beispiel #41
0
def index(request):
    login_flag = False
    kola_name = ''
    errors = []
    flag = ''
    news_list = []
    if "login_flag" in request.session:
        login_flag = True
        kola_name = request.session['name']
    news = News.objects.order_by("-dt")
    if request.method == "POST":

        # 使用geetest验证码验证 +++++++++++++++++++++++++++++++++++++
        challenge = request.POST.get('geetest_challenge')
        validate = request.POST.get('geetest_validate')
        seccode = request.POST.get('geetest_seccode')
        gt = geetest.geetest('geetest_KEY')
        if not gt.geetest_validate(challenge, validate, seccode):
            errors.append(u'验证未通过,请先通过验证')
        # ———————————————————————————————————————————————————————————

        if len(request.POST.get('news', '')) < 70:
            errors.append(u'提交内容长度必须大于70字.')
        if len(request.POST.get('news', '')) > 1000:
            errors.append(u"提交内容长度过长,不超过1000个字.")
        if not errors:
            new_news = News(
                title=request.POST.get('news', ''),
                source=u"匿名新闻",
            )
            new_news.save()
            request.session["news_flag"] = True
            flag = u"匿名新闻提交成功。"
            return HttpResponseRedirect('/news/')

    paginator = Paginator(news, 40)  # Show 25 contacts per page
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)
    return render(request, 'news_index.html', locals())
Beispiel #42
0
def index(request):
    login_flag = False
    kola_name = ''
    errors = []
    flag = ''
    news_list = []
    if "login_flag" in request.session:
        login_flag = True
        kola_name = request.session['name']
    news = News.objects.order_by("-dt")
    if request.method == "POST":
        
        # 使用geetest验证码验证 +++++++++++++++++++++++++++++++++++++
        challenge = request.POST.get('geetest_challenge')
        validate = request.POST.get('geetest_validate')
        seccode = request.POST.get('geetest_seccode')
        gt = geetest.geetest('geetest_KEY')      
        if not gt.geetest_validate(challenge, validate, seccode):
            errors.append(u'验证未通过,请先通过验证')  
        # ———————————————————————————————————————————————————————————
        
        if len(request.POST.get('news',''))<70:
            errors.append(u'提交内容长度必须大于70字.')
        if len(request.POST.get('news',''))>1000:
            errors.append(u"提交内容长度过长,不超过1000个字.")
        if not errors:
            new_news =News(
                title=request.POST.get('news',''),
                source=u"匿名新闻",
                )
            new_news.save()
            request.session["news_flag"] = True
            flag = u"匿名新闻提交成功。"
            return HttpResponseRedirect('/news/')

    paginator = Paginator(news, 40) # Show 25 contacts per page
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)    
    return render(request,'news_index.html',locals())
 def resolve_news_items(_, __, **kwargs):
     pagination = Pagination(
         page=kwargs.get('page'),
         per_page=s.NEWS_PERPAGE,
     )
     offset = pagination.offset
     per_page = pagination.per_page
     return [i for i in News.get_news_items()[offset:offset + per_page]]
Beispiel #44
0
def cron(request):
	stars= Star.objects.all()
  #  resString = "1) ";
	for star in stars:
		f = { 'q' : star.name, 'hl' : "ru", 'output' : 'rss'}
		params = urllib.urlencode(f)
		d = feedparser.parse('https://news.google.com/news?'+params)
		for field in d['entries']:
			news = News()
			news.header = field.title
			news.text =  field.title
			news.url = field.title_detail.base
			news.star = star
			news.save()
		#	print field.title
	return HttpResponse("ok")
  #  stars= Star.objects.all()
  #  resString = "1) ";
  #  for star in stars:
  #      res = json.loads(getPage(star.name))
#	for item in res['responseData']['results']:
#		news = News()
#		news.header =BeautifulSoup(item['title']).text
#		news.text = BeautifulSoup(item['content']).text
#		news.url = BeautifulSoup(item['url']).text
#		news.star = star
#		news.save()
	return HttpResponse("OK")
Beispiel #45
0
    def test_category_page(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)
        only_news = all_news[0]
        self.assertEquals(only_news, news)

        category_url = news.category.get_absolute_url()
        response = self.client.get(category_url)
        self.assertContains(response, news.category.name, status_code=200)

        #проверяем атрибуты
        self.assertEquals(only_news.title, 'Моя первая новость')
        self.assertEquals(only_news.announcement, 'Анонс первой новости')
        self.assertEquals(only_news.pub_date.day, news.pub_date.day)
        self.assertEquals(only_news.pub_date.year, news.pub_date.year)
Beispiel #46
0
 def test_insert_to_db(self):
     l = [
         {
             'url': 'http://url1.ru/',
             'title': 'news1'
         },
         {
             'url': 'http://url2.ru/',
             'title': 'news2'
         },
         {
             'url': 'http://url3.ru/',
             'title': 'news3'
         },
     ]
     News.insert_to_db(l)
     count = News.objects.filter(title__contains='news').count()
     self.assertEqual(count, 3)
Beispiel #47
0
def news_index(request):
    if request.method == "POST":
        form = NewsForm(request.POST)
        if form.is_valid():
            _new = News(**form.cleaned_data)
            _new.save()
            return HttpResponseRedirect('/news/')

    else:
        form = NewsForm()

    today_news = News.objects.filter(updated_at__gte=date.today()).all()
    return render(request,
                  'news/index.html',
                  context={
                      'news': today_news,
                      'form': form
                  })
Beispiel #48
0
def index():
    json_obj = requests.get('https://newsapi.org/v2/top-headlines?country=in&apiKey=992d09763cc4473d8612788b6ddc1326').json()

    articles = json_obj['articles']
    print(type(articles))
    News.objects.all().delete()
    for i, article in enumerate(articles):

        source= article['source']['name']
        title= article['title']
        description = article['description']
        url = article['url']
        urlToImage= article['urlToImage'] 
        newsinfo = News(source = source,title=title,description =description,url=url)
        data = {"source":source,"title":title,"description":description,"url":url,"urlToImage":urlToImage}
        newsinfo.save()
    print("done")
    return 
Beispiel #49
0
 def get(self, request):
     news_count = News.objects.count()
     tournaments_count = Tournament.objects.count()
     return render(
         request, 'bowling_app/home.html', {
             'news': News.ordered_by_creation(3),
             'tournaments': Tournament.ordered_by_creation(3),
             'news_count': news_count,
             'tournaments_count': tournaments_count
         })
Beispiel #50
0
	def post(self, request, format=None):
		"""
		更新news
		"""
		r = requests.get('http://mazii.net/api/news/1/10')
		if r.status_code != 200:
			return Response("news connect fail", status=status.HTTP_200_OK)

		for item in r.json()['results']:
			news_id = item['id']

			try:
				news = News.objects.get(news_id=news_id)
				print "id exiets continue"
				continue
			except ObjectDoesNotExist:
				r = requests.get('http://mazii.net/api/news/' + news_id)

				if r.status_code != 200:
					return Response("news connect fail", status=status.HTTP_200_OK)

				result = r.json()['result']
				rev = result['_rev']
				title = result['title']
				link = result['link']
				pubdate = result['pubDate']
				description = result['description']
				content = result['content']['textbody']
				pubdate = datetime.datetime.strptime(pubdate, "%Y-%m-%d %H:%M:%S")
				news = News(news_id=news_id, rev=rev, title=title, link=link, pubdate=pubdate, description=description, content=content)
				news.save()

				if result['content']['audio']:
					print "pres audio..."
					pres_audio_from_website(news, result['content']['audio'], "audio")

				if result['content']['image']:
					print "pres photo..."
					pres_photo_from_website(news, result['content']['image'], "image")

		return Response("ok", status=status.HTTP_200_OK)
Beispiel #51
0
def news_new(request):

    email = get_email(request)
    if request.method == "POST":
        name = request.session["name"]
        import time

        tmp = time.localtime()
        raw_time = time.time()
        dt = "-".join(["%d" % i for i in tmp[:3]])
        time = ":".join(["%d" % i for i in tmp[3:6]])
        title = request.POST["title"]
        content = request.POST["content"]
        news = News(
            name=name, title=title, content=content, dt=dt, time=time, raw_time=raw_time, email=email, display=True
        )
        news.save()

        return HttpResponseRedirect("news")

    return render(request, "news/news_new.html", {"csrf_token": request.COOKIES["csrftoken"], "email": email})
Beispiel #52
0
def active(request):
    """Renders default/program template:
       - The list of all active (published and not yet expired) news,
    """

    news = News.get_frontpage_news()
    events = Event.get_frontpage_events()
    daytime_events = Event.get_frontpage_daytime_events()

    sticky_news = News.get_sticky_news()

    #get latest albums from gallery
    latest = Album.objects.filter(category='LIVE',
        date_of_event__range=(datetime.today() - timedelta(14), datetime.today())).order_by('-date_of_event')[:3]

    return render_to_response('news.html', {
        'news': news,
        'events': events,
        'daytime_events': daytime_events,
        'latest': latest,
        'sticky_news': sticky_news
        }, context_instance=RequestContext(request))
Beispiel #53
0
 def setUp(self):
     city = City.objects.get(name='Curitiba')
     news = News()
     news.title = 'Test news'
     news.content = 'Test content'
     news.city = city
     news.save()
     self.news = news
Beispiel #54
0
def test(request):

    # tag2 = Tag(name="3d")
    # tag2.save()
    #
    # news = News(my_id = 1, content="lorem ipsum lorem,lorem, ipsum lorem ipsum lorem,lorem, ipsum lore ipsum lorem,lorem, ipsum",
    #             abstract="lorem ipsum test and done", title="lorem", views=102)
    # news.tags.append(tag1)
    # news.save()
    # news.tags.append(tag2)
    # news.save()


    context = {
        'user': request.user,
        'news': News.objects().first(),
        'tags': Tag.objects.all()
    }
    return render(request, 'main.html', context)
Beispiel #55
0
    def test_create_news(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        #создаем новость и заполняем поля
        news = News()

        #устанавливаем атрибуты
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости ++'
        news.text = 'Текст первой новости!!!'
        news.pub_date = timezone.now()
        news.category = category

        #сохраняем в бд
        news.save()

        #проверяем что новость доавбилась в базу
        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)
        only_news = all_news[0]
        self.assertEquals(only_news, news)

        #проверяем атрибуты
        self.assertEquals(only_news.title, 'Моя первая новость')
        self.assertEquals(only_news.announcement, 'Анонс первой новости ++')
        self.assertEquals(only_news.text, 'Текст первой новости!!!')
        self.assertEquals(only_news.pub_date.day, news.pub_date.day)
        self.assertEquals(only_news.pub_date.month, news.pub_date.month)
        self.assertEquals(only_news.pub_date.year, news.pub_date.year)
        self.assertEquals(only_news.pub_date.hour, news.pub_date.hour)
        self.assertEquals(only_news.pub_date.minute, news.pub_date.minute)
        self.assertEquals(only_news.pub_date.second, news.pub_date.second)
        self.assertEquals(only_news.category.name, 'Экономика')
        self.assertEquals(only_news.category.description, 'Новости экономики')
Beispiel #56
0
    def test_edit_news(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.announcement = 'Анонс первой новости ++'
        news.text = 'Текст первой новости!!!'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        self.client.login(username='******', password='******')
        
        response = self.client.post('/admin/news/news/' + str(news.id) + '/', {
            'title': 'Моя вторая новость',
            'announcement': 'Анонс второй новости',
            'text': 'Текст второй новости',
            'pub_date_0': '2014-10-15',
            'pub_date_1': '16:07:00',
            'category': str(category.id)
            },
            follow=True
            )

        self.assertContains(response, 'успешно изменен', status_code=200)

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)
        only_news = all_news[0]
        self.assertEquals(only_news.title, 'Моя вторая новость')
        self.assertEquals(only_news.announcement, 'Анонс второй новости')
        self.assertEquals(only_news.text, 'Текст второй новости')
Beispiel #57
0
def save(request):
    if isLoggedIn(request):
        req = request.POST
        id = req.get('id')
        title = req.get('title')
        content = req.get('content')
        mag = req.get('mag')
        signature = request.COOKIES.get('signature')
        if not int(id) == 0:
            news = News.objects.filter(id=id).first()
        else:
            news = News()
        if title and content and mag:
            news.title = title
            news.content = content
            news.mag = mag
            news.author = signature
            news.save()
            id = news.id
            news = News.objects.filter(id=id)
            return HttpResponse(serialize('json', news))
    return HttpResponse('0')
Beispiel #58
0
    def test_news_page(self):
        category = Category()
        category.name = 'Экономика'
        category.description = 'Новости экономики'
        category.slug = 'economy'
        category.save()

        news = News()
        news.title = 'Моя первая новость'
        news.text = 'Текст первой новости'
        news.pub_date = timezone.now()
        news.category = category
        news.save()

        all_news = News.objects.all()
        self.assertEquals(len(all_news), 1)

        response = self.client.get('/news/' + str(news.id) + '/')
        self.assertContains(response, news.title, status_code=200)
        self.assertContains(response, news.text)
        self.assertContains(response, news.pub_date.year)
        # выдает на англ и сравнивает с русским - не отрабатывает self.assertContains(response, news.pub_date.strftime('%b'))
        self.assertContains(response, news.pub_date.day)
        self.assertContains(response, news.category.name)
    def handle(self, *args, **options):
        path = args[0]

        if path.startswith('http'):
            content = json.load(urllib2.urlopen(path))
        else:
            content = json.load(open(path))

        for entry in content:
            try:
                news = News.objects.get(id=int(entry['id']))
            except News.DoesNotExist:
                news = News(id=int(entry['id']))

            if not 'html' in entry or entry['pub'] == '0':
                continue

            news.title = entry['name']
            news.caption = entry['announce']
            news.is_visible = entry['pub'] == '10'
            news.date_published = datetime.datetime.strptime(entry['time'], '%d.%m.%Y').date()
            news.content = entry['html']
            news.save()

            for url_hash in re.findall('src="/pic/(.*?)/"', news.content):
                url = 'http://tomat-podarky.ru/pic/%s/' % url_hash

                fp = ContentFile(requests.get(url).content)
                today = datetime.date.today()
                target_name = 'uploads/%(year)d/%(month)d/%(name)s%(ext)s' % {
                    'year': today.year,
                    'month': today.month,
                    'name': uuid.uuid4().hex,
                    'ext': '.jpg',
                }
                filepath = os.path.join(settings.MEDIA_ROOT, target_name)
                out = open(filepath, 'w')
                out.write(fp.read())
                out.close()

                news.content = news.content.replace('/pic/%s/' % url_hash, '/media/%s' % target_name)
            news.save()
Beispiel #60
0
def index(request):
	return  render_to_response("core/index.html", {'news': News.last(), 'feed': IndexedArticle.objects.order_by('-pubdate')[:10]}, context_instance=RequestContext(request))