def get_last_news_mobile(cat_id=None): settings = Settings.get_settings() if settings.template_debug: html = "<div><code>Last news are not find</code></div>" else: html = '' if cat_id: news = News.get_category_news(cat_id)[:settings.last_news_mobile_count] else: news = News.get_last_news()[:settings.last_news_mobile_count] if news: html = '' photo_news_ids = NewsPhotoMarker.all() video_news_ids = NewsVideoMarker.all() NewsVideoMarker.all() tpl = loader.get_template('site/news/_lastNewsTpl.html') for n in news: context = { 'id': n.get('id'), 'title': n.get('title'), 'comments': n.get('comments'), 'slug': n.get('cat_slug'), 'status': n.get('status'), 'created_at': n.get('created_at'), 'pr': n.get('pr'), 'photo_news_ids': photo_news_ids, 'video_news_ids': video_news_ids } html += tpl.render(context) return html
def admin_edit(request, uid): news = News.get_by_id(uid) if not news: return redirect(url_for('news/admin')) form = NewsForm(initial={ 'title':news.title, 'is_display':news.is_display, 'short_text':news.short_text, 'text':news.text }) if request.method == 'POST': if form.validate(request.form): news.title = form['title'] news.is_display = form['is_display'] news.short_text = form['short_text'] news.text = form['text'] news.put() return redirect(url_for('news/admin')) else: return render_to_response( 'news/admin/edit.html', { 'form': form.as_widget(), 'news': news }) return render_to_response( 'news/admin/edit.html', { 'form': form.as_widget(), 'news': news })
def parse(self): logger.info("start parsing: %s", self.name) downloaded_news = self.download() queries = [] for data in downloaded_news['items']: news_data = self.formatNews(data) try: query = News( id=news_data['id'], datetime=datetime.fromtimestamp(news_data['datetime'], pytz.utc), title=news_data['title'], content=news_data['content'], source_title=news_data['source_title'], source_url=news_data['source_url'], referrer=news_data['referrer'], ) except Exception as e: logger.error("%s: %s", e, str(data)) queries.append(query) logger.info("done parsing: %s, %s queries were parsed", self.name, len(queries)) return queries
def get_interview_news(): news = News.get_category_news(14) html = '' if news: settings = Settings.get_settings() news = news[:settings.category_news_count] tpl = loader.get_template('site/news/_interviewTpl.html') html = '<section id="interview_block">' html += '<header class="clearfix"><p>інтерв\'ю <a class="right" href="/category/interview">більше<i ' \ 'class="icon_all"></i></a></p></header>' html += '<div class="carousel row" style="margin:0;">' for n in news: context = { 'id': n.get('id'), 'title': n.get('title'), 'comments': n.get('comments'), 'slug': n.get('cat_slug'), 'created_at': n.get('created_at'), 'image': n.get('image'), } html += tpl.render(context) html += '</div></section>' return html
def get_last_videos_aside(): news = News.get_video_news() html = '' if news: settings = Settings.get_settings() news = news[:settings.category_news_count] tpl = loader.get_template('site/news/_lastNewsVideosTpl.html') html = '<section id="last_videos_aside">' html += '<header class="clearfix"><p>останні відео <a class="right" href="/videos">більше<i ' \ 'class="icon_all"></i></a></p></header>' html += '<div class="carousel_aside row" style="margin:0;">' for n in news: context = { 'id': n.get('id'), 'title': n.get('title'), 'comments': n.get('comments'), 'slug': n.get('cat_slug'), 'created_at': n.get('created_at'), 'image': n.get('image_400'), } html += tpl.render(context) html += '</div></section>' return html
def category_news(cat_id): news = News.get_category_news(cat_id) html = '' if news: settings = Settings.get_settings() news = news[:settings.category_news_count] photo_news_ids = NewsPhotoMarker.all() video_news_ids = NewsVideoMarker.all() tpl = loader.get_template('site/news/_categoryNewsTpl.html') for idx, n in enumerate(news): context = { 'id': n.get('id'), 'title': n.get('title'), 'comments': n.get('comments'), 'slug': n.get('cat_slug'), 'cat_title': n.get('cat_title'), 'color': n.get('color'), 'status': n.get('status'), 'created_at': n.get('created_at'), 'image': n.get('image_400'), 'image_small': n.get('image_200'), 'pr': n.get('pr'), 'idx': idx, 'photo_news_ids': photo_news_ids, 'video_news_ids': video_news_ids } html += tpl.render(context) return html
def news_add(request): if request.method == 'POST': # ketika submit data form = AddNewsForm(request.POST, request.FILES) # isi value pada form sesuai yg di POST if form.is_valid(): # cek validasi # Data ada di array form.cleaned_data user = User.objects.get(pk=request.user.id) news = News() news.title = form.cleaned_data['title'] news.description = form.cleaned_data['description'] news.member = user if request.FILES: f = request.FILES['image'] path = get_file_path(request,f.name) fd = open('%s/%s' % (settings.MEDIA_ROOT, str(path)), 'wb') for chunk in f.chunks(): fd.write(chunk) fd.close() else : path = '' news.image = path news.save() #insert data ke table news messages.success(request, "Add News Success.") return HttpResponseRedirect('/news/') # Redirect after POST #return render_to_response('wisata/form_wisata.html',{'tulisan':tulisan}, context_instance=RequestContext(request, processors=[custom_proc])) else: form = AddNewsForm() # value form kosongan breadcrumb = 'Add News' datanya = {'form':form, 'breadcrumb': breadcrumb} return render_to_response('news/form_news.html',datanya, context_instance=RequestContext(request, processors=[custom_proc]))
def show(request, uid): news = News.get_by_id(uid) if not news: return redirect(url_for('news')) images = NewsImage.query(NewsImage.news_ref == news.key) return render_to_response('news/show.html', { 'news': news, 'images': images })
def admin_images(request, uid): news = News.get_by_id(uid) if not news: return render_to_response('empty.html') images = NewsImage.query(NewsImage.news_ref == news.key) url = blobstore.create_upload_url(url_for('news/admin/images/add', uid=news.key.id())) return render_to_response('news/admin/images.html',{ 'images': images, 'news': news, 'url': url })
def generate_random_news(category, new=randint(1, 6), old=randint(1, 6)): ns = [] author_user = UserFactory() for i in range(new): n = News(title="news", body="news body", date=datetime.now() - timedelta(days=randint(0, 6)), author_id=author_user.pk) n.category = category n.save() ns.append(n) for i in range(old): n = News(title="old news", body="news body", date=datetime.now() - timedelta(days=randint(8, 20)), author_id=author_user.pk) n.category = category n.save() ns.append(n) return (new, old, ns)
def get_top_news(cat_id=None): news = News.get_top_news(cat_id) if cat_id and not news: news = News.get_top_news() html = '' if news: photo_news_ids = NewsPhotoMarker.all() video_news_ids = NewsVideoMarker.all() tpl = loader.get_template('site/news/_topNewsTpl.html') context = { 'id': news.get('id'), 'title': news.get('title'), 'comments': news.get('comments'), 'slug': news.get('cat_slug'), 'created_at': news.get('created_at'), 'image': news.get('image'), 'photo_news_ids': photo_news_ids, 'video_news_ids': video_news_ids } html = tpl.render(context) return html
def admin_add_image(request, uid): if request.method == 'POST': news = News.get_by_id(uid) if not news: return render_json_response({'api':{'success':False}}) upload_files = get_uploads(request, 'file') if len(upload_files): blob_info = upload_files[0] if blob_info.size: image = NewsImage.create(blob_info.key()) news = News.get_by_id(uid) images = NewsImage.query(NewsImage.news_ref == news.key) if not images.count: image.is_master = True image.news_ref = news.key image.cached_url = image.get_cached_url() image.put() else: blob_info.delete() return admin_images(request, uid) return render_to_response('empty.html')
def exist_a_news(step): for news_hashes in step.hashes: author = User.objects.get(username__exact=news_hashes.get('author')) date, hour = news_hashes.get('date_and_time').split() day, month, year = date.split('/') hours, minutes = hour.split(':') date_time = datetime(int(year), int(month), int(day), int(hours), int(minutes)) News(title=news_hashes.get('title'), summary=news_hashes.get('summary'), body=news_hashes.get('body'), image=news_hashes.get('image'), author=author, date_and_time=date_time).save() file_name = news_hashes.get('image').split('/')[-1] shutil.copy2(os.path.join(settings.PROJECT_ROOT_PATH, 'apps', 'news', 'features', 'resources', file_name), os.path.join(settings.MEDIA_ROOT, 'test', 'images', 'news'))
def news_all(request): news = News.all().order('-add_time') paginator = Paginator(news, 25) try: page = int(request.args.get('page',1)) except ValueError: page = 1 try: news = paginator.page(page) except (EmptyPage, InvalidPage): news = paginator.page(paginator.num_pages()) return render_to_response('news/admin/news_all.html', {'news':news})
def news_edit(request, key): news = News.get(key) images_form = NewsImageForm(action='/news/admin/news/add_image/%s/' % key) if news is None: return redirect('/news/admin/news/all') form = NewsForm(instance=news) if request.method == 'POST' and form.validate(request.form): form.save() return redirect('/news/admin/news/all/') return render_to_response('news/admin/news_add.html', {'form':form.as_widget(), 'images_form':images_form.as_widget(), 'news':news})
def test_get_successive_news(self): ns = [] for i in range(12): n = News(title="news", body="news body", author_id=1, date=datetime.now() - timedelta(days=12 - i)) n.save() ns.append(n) self.assertEqual(0, len(News.objects.get_successive_news('-', 0, 0))) self.assertEqual( 0, len(News.objects.get_successive_news('-', randint(0, 11), 0))) self.assertEqual(12, len(News.objects.get_successive_news('-', 0, 20))) nss = News.objects.get_successive_news('-', 3, 6) for i in range(0, 6): self.assertEqual(nss[i].id, ns[8 - i].id) for n in ns: n.delete()
def add_news_image(request, news_key): news = News.get(news_key) if not news: news = News() news.put() form = NewsForm(instance=news) images_form = NewsImageForm(action='/news/admin/news/add_image/%s/' % news.key()) if request.method == 'POST': if images_form.validate(request.form, request.files): img = images_form['image_file'] content_type = 'image/jpeg' if not images_form['title']: title = '' else: title = images_form['title'] title = title.replace('"', '"') thumb_img = ThumbImage() thumb_img.add_new_thumb(blob_img=img, thumb_size=(100, 100), content_type=content_type, title=title) if not images_form['width'] or not images_form['height']: width = height = 300 else: width = images_form['width'] height = images_form['height'] thumb_img.add_new_thumb(blob_img=img, thumb_size=(width, height), content_type=content_type, title=title) thumb_img.put() news_image = NewsImage() news_image.title = title news_image.news = news news_image.image = thumb_img news_image.size = '%sx%s' % (width, height) news_image.put() return redirect('/news/admin/news/edit/%s/' % news.key()) return render_to_response('news/admin/news_add.html', {'form':form.as_widget(), 'images_form':images_form.as_widget()})
def index(request): newss = News.all().order('-add_time') actions = Action.all().order('-add_time') return render_to_response('news/index.html', {'newss': newss, 'actions':actions})
def admin_list(request): news = News.query().order(-News.add_time) return render_to_response('news/admin/list.html', {'news':news})
def admin_add(request): news = News() news.put() form = NewsForm(action=url_for('news/admin/edit', uid=news.key.id())) return render_to_response('news/admin/edit.html', {'form': form.as_widget(), 'news': news})
def create(self, validate_data): news =News(**validate_data) news.author=self.request.user news.save() return news
def test_creating_news(self): n1 = News(title="news test", body="news body") self.assertEqual(str(n1), "news test")
def test_convert_its_RST_body_to_HTML(self): h = News(body="*NSI* site rulz!") h.body_as_html() |should| contain('<em>NSI</em> site rulz!')
def post(self): user = g.user if not user: return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录") # POST 提交,执行发布新闻操作 # 1. 获取要提交的数据 title = request.form.get("title") source = "个人发布" digest = request.form.get("digest") content = request.form.get("content") index_image = request.files.get("index_image") category_id = request.form.get("category_id") # 1.1 判断数据是否有值 if not all([title, source, digest, content, index_image, category_id]): return jsonify(errno=RET.PARAMERR, errmsg="参数有误") try: category_id = int(category_id) except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.PARAMERR, errmsg="参数有误") key = "https://beishufudeyu.github.io/images/%E5%88%86%E5%B8%83%E5%BC%8F%E7%89%88%E6%9C%AC%E6%8E%A7%E5%88%B6.png" if index_image is not None: # 2. 将标题图片上传到七牛 try: index_image_data = index_image.read() key = storage(index_image_data) except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误") # 3. 初始化新闻模型,并设置相关数据 news = News() news.title = title news.digest = digest news.source = source news.content = content if index_image: news.index_image_url = constants.QINIU_DOMIN_PREFIX + key else: news.index_image_url = key news.category_id = category_id news.user_id = g.user.id # 1代表待审核状态 news.status = 1 # 4. 保存到数据库 try: db.session.add(news) db.session.commit() except Exception as e: db.session.rollback() current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg="保存数据失败") # 5. 返回结果 return jsonify(errno=RET.OK, errmsg="发布成功,等待审核")
def news_delete(request, key): news = News.get(key) if news: news.delete() return redirect('/news/admin/news/all/')
def news_add(request): news = News(title=u'Название новости', text=u'Текст новости') news.put() return redirect('/news/admin/news/edit/%s/' % news.key())
def show_news(request, id): news = News.get_by_id(id) if news is None: return redirect('/news/') return render_to_response('news/show_news.html', {'news':news})
def admin_delete(request, uid): news = News.get_by_id(uid) if news: news.key.delete() return redirect(url_for('news/admin'))
def index(request): news = News.query(News.is_display == True).order(-News.add_time) return render_to_response('news/index.html', { 'news': news })