def submitNew(request, linkError=None, groupName = None): if request.method == 'POST': form = NewArticleForm(request.POST) if form.is_valid(): url = form.cleaned_data['url'] title = form.cleaned_data['title'] comment = form.cleaned_data['comment'] pub_date = str(timezone.now()) group = None if groupName: group = Group.objects.get(name = groupName) articleEntry = Articles(article = url, pub_date = pub_date, title = title, comment = comment, user = request.user, group = group) articleEntry.save() request.session['message'] = title return HttpResponseRedirect("/") else: form = NewArticleForm() return shortcuts.render_to_response('newArticle.html', {"linkError" : linkError, 'groupName' : groupName, "menuItem" : 'submit', 'form' : form}, context_instance=RequestContext(request))
def get_form_kwargs(self): kwargs = super(SubmitNew, self).get_form_kwargs() kwargs['instance'] = Articles() if self.request.user.is_authenticated(): kwargs['instance'].subject = '0' kwargs['instance'].name = self.request.user return kwargs
def get_form_kwargs(self): kwargs = super(SubmitTopic, self).get_form_kwargs() kwargs['instance'] = Articles() if self.request.user.is_authenticated(): kwargs['instance'].subject = '1' kwargs['instance'].name = self.request.user return kwargs
def post(self): title = self.request.get('subject') post = self.request.get('content') slug = self.request.get('slug') cid = self.request.get('cid') error = dict() cid = int(cid) if title and post: if not slug or not valid_slug(slug): slug = slugify(str(title)) slug_in_db = Articles.all().filter('slug =', slug).get() if not slug_in_db or cid == slug_in_db.key().id(): edit = Articles.get_by_id(cid) edit.title = title edit.post = post edit.slug = slug edit.put() # Remove from memcache memcache.flush_all() self.redirect('/articles/' + slug) else: error['slug'] = 'Sorry, this slug is taken. Please enter a unique one' form = {'title': title, 'post': post, 'slug': slug, 'cid': cid, 'error': error, 'logged_in': True} self.render_form(form) else: if not title: error['subject'] = 'Please enter a title' if not post: error['post'] = 'Please enter some content' form = {'title': title, 'post': post, 'slug': slug, 'cid': cid, 'error': error, 'logged_in': True} self.render_form(form)
def post(self): title = self.request.get('subject') post = self.request.get('content') slug = self.request.get('slug') error = dict() if title and post: if not slug: slug = slugify(str(title)) slug_in_db = Articles.ll().filter('slug =', slug).get() if not slug_in_db: submission = Articles(title=title, post=post, slug=slug) submission.put() memcache.flush_all() else: error['slug'] = 'Sorry, this slug is taken. Please enter a unique one' self.render_post(title, post, slug, error) else: if not title: error['subject'] = 'Please enter a title' if not post: error['post'] = 'Please enter some content' self.render_post(title, post, slug, error)
def get_page_content(pageid): ia = Articles.select().group_by(Articles.iamap); content = Articles.select().where(Articles.pageid == pageid ).limit(1) t0 = time() value = content[0] value.webpage = Markup(value.webpage) t1 = time() print 'Query from Articles takes %f' %(t1-t0) return render_template('page.html', content = value , ia = ia)
def edit_article(id): print(f"ROUTE: edit_article") print(f"Form Data: {request.form}") errors = Articles.validate(request.form) if errors: for error in errors: flash(error) return redirect(url_for('show_post_form')) Articles.update(id, request.form) return redirect(url_for("show_dashboard"))
def Release(): if request.method == 'GET': return render_template('release.html') else: title = request.form.get('title') content = request.form.get('content') article = Articles(title=title,content=content) article.author = g.user db.session.add(article) db.session.commit() return redirect(url_for('Index')) pass
def post_article(): print(f"ROUTE: post_article") print(f"Form Data: {request.form}") errors = Articles.validate(request.form) if errors: for error in errors: flash(error) return redirect(url_for('show_post_form')) article_id = Articles.add_to_db(request.form, session['user_id']) return redirect(url_for("show_dashboard"))
def index(): from models import Articles, Comments from forms import ArticlesForm, CommentsForm if request.method == 'POST': print(request.form) us_form = ArticlesForm(request.form) if us_form.validate(): post_art = Articles(**us_form.data) db.session.add(post_art) db.session.commit() return 'Article was created' else: us_form = CommentsForm(request.form) if us_form.validate(): post_com = Comments(**us_form.data) db.session.add(post_com) db.session.commit() return 'Commit was created' else: raise Exception if request.method == 'GET': vie_posts = Articles.query.all() return render_template('home.txt', posts=vie_posts)
def handle_articles(): #POST method if request.method == "POST": body = request.get_json() #Conditions for request! if body is None: raise APIException( "You need to specify the request body as a json object", status_code=400) if "title" not in body: raise APIException('You need to specify the title', status_code=400) if "description" not in body: raise APIException('You need to specify the description', status_code=400) article = Articles(title=body['title'], description=body["description"]) db.session.add(article) db.session.commit() return 'ok', 200 #GET Method if request.method == 'GET': all_articles = Articles.query.all() all_articles = list(map(lambda x: x.serialize(), all_articles)) return jsonify(all_articles), 200
def copyFromArticles(self, request): '''Copies articles and authors from legacy Articles Kind into new Article and Author kinds''' user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') for article in Articles().all(): if '@' not in article.author: author_email = article.author + '@gmail.com' else: author_email = article.author a_key = ndb.Key(Author, author_email) author = a_key.get() # create new Author if not there if not author: author = Author( key=a_key, authorID=str(Author.allocate_ids(size=1)[0]), displayName=author_email.split('@')[0], mainEmail=author_email, ) author.put() self.copyArticlesKind(article, author) return BooleanMessage(data=True)
def web_get_article(aid): article = Articles.get_by_id(aid) if article is None or article.draft: raise notfound article.reads = counters.incr(aid) article.content = texts.md2html(texts.get(article.content_id)) category = Categories.get_by_id(article.category_id) return dict(article=article, category=category, comments=comments.get_comments(aid))
def api_delete_article(aid): a = Articles.get_by_id(aid) if a is None: raise notfound() a.delete() uploaders.delete_attachment(a.cover_id) comments.delete_comments(aid) return dict(result=True)
def test(request): title = u'何以解忧,唯有前行!' subtitle = u'何以解忧,唯有杜康' content = u'我其实很久以前就读了东野圭吾的《解忧杂货店》,感觉这是一本最不像东野圭吾的小说,没有他一贯的引人注目的悬疑和推理,看似十分凌乱。初读的时候,很容易被众多的人物和错乱的时空搞得莫名奇妙。但是,当你真正读懂读通,理清了小说的时间顺序和人物关系,你就会发现它仍旧是东野圭吾的风格,故事缜密又奇妙。' author = Author.objects.filter(name='xiaoxiao').first() categorys = Categorys.objects.get(pk=3) tag = Tags.objects.get(pk=3) article = Articles(title=title, subtitle=subtitle, content=content, author=author, categorys=categorys) # article = Articles.objects.all().first() for i in range(50): article.save() article.tags.add(tag) return HttpResponse('success')
def homepage(): categories = _get_categories() cat_dict = dict(((c._id, c.name) for c in categories)) fn_get_category_name = lambda cid: cat_dict.get(cid, u'ERROR') articles = Articles.select('where publish_time<? order by publish_time desc limit ?', time.time(), 10) reads = counters.counts((a._id for a in articles)) for a, r in zip(articles, reads): a.reads = r return dict(articles=articles, fn_get_category_name=fn_get_category_name)
def test_db(): from models import Articles try: t_book = Articles(name='aaaa', author='aaaaa', published=2001) db.session.add(t_book) db.session.commit() except Exception as e: return (str(e))
def api_delete_category(cid): cat = Categories.get_by_id(cid) if cat is None: raise APIValueError('_id', 'category not found.') if len(Articles.select('where category_id=?', cat._id)) > 0: raise APIValueError('_id', 'cannot delete non-empty categories.') cat.delete() _clear_categories_cache() return dict(result=True)
def addArticleView(): if request.method == 'POST': title = request.values.get("title") content = request.values.get("content") article = Articles(article_title=title, article_content=content) db.session.add(article) db.session.commit() flash('Add article succeed!') return redirect(url_for('adminArticlesView')) return render_template('adminAddArticle.html')
def api_create_article_comment(aid): u = ctx.user if u is None: raise APIPermissionError() i = ctx.request.input(content='') content = assert_not_empty(i.content, 'content') a = Articles.get_by_id(aid) if a is None: raise notfound() return comments.create_comment('article', aid, content)
def get_articles(count=10, update=False): ''' Adding to and Retrieving from memcache ''' key = 'top_' + str(count) value = memcache.get(key) if value is None or update: logging.info('Ran a query to retrieve the top posts') posts = Articles.query().order(-Articles.created).fetch(count) value = (list(posts), datetime.datetime.now()) memcache.set(key, value) return value
def api_update_article(aid): article = Articles.get_by_id(aid) if article is None: raise notfound() i = ctx.request.input() update = False if 'name' in i: article.name = assert_not_empty(i.name, 'name') update = True if 'summary' in i: article.summary = assert_not_empty(i.summary, 'summary') update = True if 'category_id' in i: article.category_id = _check_category_id(i.category_id) update = True if 'tags' in i: article.tags = texts.format_tags(i.tags) update = True # update draft first: if 'draft' in i: if i.draft.lower()=='true': if not article.draft: # change False to True: article.draft = True if article.publish_time < TIME_FEATURE: article.publish_time = article.publish_time + TIME_FEATURE update = True else: if article.draft: # change True to False: article.draft = False # update publish time: if 'publish_time' in i and i.publish_time.strip(): article.publish_time = time2timestamp(i.publish_time) else: article.publish_time = time.time() update = True if 'content' in i: content = assert_not_empty(i.content, 'content') article.content = content update = True old_cover_id = '' if 'cover' in i: f = i.cover if f: # update cover: old_cover_id = article.cover_id atta = uploaders.upload_cover(article.name, f.file.read()) article.cover_id = atta._id update = True if hasattr(article, 'content'): article.content_id = texts.set(article._id, article.content) if update: article.update() if old_cover_id: uploaders.delete_attachment(old_cover_id) return dict(_id=article._id)
def api_update_article(aid): article = Articles.get_by_id(aid) if article is None: raise notfound() i = ctx.request.input() update = False if 'name' in i: article.name = assert_not_empty(i.name, 'name') update = True if 'summary' in i: article.summary = assert_not_empty(i.summary, 'summary') update = True if 'category_id' in i: article.category_id = _check_category_id(i.category_id) update = True if 'tags' in i: article.tags = texts.format_tags(i.tags) update = True # update draft first: if 'draft' in i: if i.draft.lower() == 'true': if not article.draft: # change False to True: article.draft = True if article.publish_time < TIME_FEATURE: article.publish_time = article.publish_time + TIME_FEATURE update = True else: if article.draft: # change True to False: article.draft = False # update publish time: if 'publish_time' in i and i.publish_time.strip(): article.publish_time = time2timestamp(i.publish_time) else: article.publish_time = time.time() update = True if 'content' in i: content = assert_not_empty(i.content, 'content') article.content = content update = True old_cover_id = '' if 'cover' in i: f = i.cover if f: # update cover: old_cover_id = article.cover_id atta = uploaders.upload_cover(article.name, f.file.read()) article.cover_id = atta._id update = True if hasattr(article, 'content'): article.content_id = texts.set(article._id, article.content) if update: article.update() if old_cover_id: uploaders.delete_attachment(old_cover_id) return dict(_id=article._id)
def form(): if request.form: new_article = Articles(name=request.form['name'], title=request.form['title'], sub_title=request.form['article_subtitle'], body=request.form['description'], url=request.form['url']) db.session.add(new_article) db.session.commit() return redirect(url_for('index')) return render_template('form.html')
def homepage(): categories = _get_categories() cat_dict = dict(((c._id, c.name) for c in categories)) fn_get_category_name = lambda cid: cat_dict.get(cid, u'ERROR') articles = Articles.select( 'where publish_time<? order by publish_time desc limit ?', time.time(), 10) reads = counters.counts((a._id for a in articles)) for a, r in zip(articles, reads): a.reads = r return dict(articles=articles, fn_get_category_name=fn_get_category_name)
def add_article(): form = ArticleForm(request.form) if request.method == 'POST' and form.validate(): title = form.title.data content = form.content.data author = session['username'] new_article = Articles(title=title, content=content, author=author) db.session.add(new_article) db.session.commit() flash('Article created', 'success') return redirect(url_for('blog.dashboard')) return render_template('add_article.html', form=form)
def fetch_articles_from_specific_dates(self, query: str, date_from: str, date_to: str, page_size: int = 100) -> Articles: """Method to fetch articles from specific dates: dates should be in format in 2019-08-04""" if self.mode == 'NEWSPAPER': params = "q={0}&pageSize={1}&apiKey={2}&from={3}&to={4}".format( query, page_size, self.api_key, date_from, date_to) elif self.mode == 'GNEWS': params = "q={0}&max={1}&token={2}&mindate={3}&maxdate={4}".format( query, page_size, self.api_key, date_from, date_to) url = self.baseUrl + params results = requests.get(url).json() try: articles = results["articles"] except KeyError: return Articles([]) return Articles(self.create_article_objects(articles))
def fetch_all_articles(self, query: str, page_size: int = 10) -> Articles: """Method to fetch all articles of a specific query. Note to get the full body use the get_body method""" if self.mode == 'NEWSPAPER': url_parameters = "q={0}&pageSize={1}&apiKey={2}".format( query, page_size, self.api_key) elif self.mode == 'GNEWS': url_parameters = "q={0}&max={1}&token={2}".format( query, page_size, self.api_key) url = self.baseUrl + url_parameters results = requests.get(url).json() all_articles = results["articles"] return Articles(self.create_article_objects(all_articles))
def show_dashboard(): print(f"ROUTE: show_dashboard") if 'user_id' not in session: print(f"User id not found") return redirect('/') current_user = Users.query.get(session['user_id']) posts = Articles.get_latest_articles() posts.reverse() # qod = get_quote_of_the_day() return render_template("dashboard.html", user=current_user, posts=posts)
def _get_rss(): def _rss_datetime(ts): dt = datetime.fromtimestamp(ts, UTC_0) return dt.strftime('%a, %d %b %Y %H:%M:%S GMT') def _safe_str(s): if isinstance(s, str): return s if isinstance(s, unicode): return s.encode('utf-8') return str(s) limit = 20 name = u'廖雪峰的官方网站' description = u'' copyright = 'copyright 2013' domain = ctx.request.host articles = articles = Articles.select('where publish_time<? order by publish_time desc limit ?', time.time(), 50) for a in articles: a.content = texts.md2html(texts.get(a.content_id)) rss_time = articles and articles[0].publish_time or time.time() L = [ '<?xml version="1.0"?>\n<rss version="2.0"><channel><title><![CDATA[', name, ']]></title><link>http://', domain, '/</link><description><![CDATA[', description, ']]></description><lastBuildDate>', _rss_datetime(rss_time), '</lastBuildDate><generator>BrighterPage</generator><ttl>3600</ttl>' ] for a in articles: url = 'http://%s/article/%s' % (domain, a._id) L.append('<item><title><![CDATA[') L.append(a.name) L.append(']]></title><link>') L.append(url) L.append('</link><guid>') L.append(url) L.append('</guid><author><![CDATA[') L.append(a.user_name) L.append(']]></author><pubDate>') L.append(_rss_datetime(a.publish_time)) L.append('</pubDate><description><![CDATA[') L.append(texts.md2html(texts.get(a.content_id))) L.append(']]></description></item>') L.append(r'</channel></rss>') return ''.join(map(_safe_str, L))
def get_article(slug, update=False): ''' Caching single article objects. Used by Article, JsonArticle, and Delete ''' key = slug value = memcache.get(key) if value is None or update: logging.info('Ran a query to retrive an article') post = Articles.query().filter('slug =', key).get() if post: value = (post, datetime.datetime.now()) memcache.set(key, value) else: return (None, None) return value
def process_articles_source(article_list): source_articles = [] for art in article_list: source = art.get("source") author = art.get('author') title = art.get('title') description = art.get('description') url = art.get('url') urlToImage = art.get('urlToImage') publishedAt = art.get('publishedAt') article_object = Articles(source,author,title,description,url,urlToImage,publishedAt) source_articles.append(article_object) return source_articles
def front_add_article(request): if request.method == 'GET': categorys = Categorys.objects.all() tags = Tags.objects.all() context = {'categorys': categorys, 'tags': tags} if hasattr(request, 'front_user'): context['front_user'] = request.front_user return render(request, 'front_add_article.html', context) else: form = AddArticleForm(request.POST) if form.is_valid(): title = form.cleaned_data.get('title') subtitle = form.cleaned_data.get('subtitle') data = request.POST tags = request.POST.getlist('tags[]') context = {} for k, v in data.iteritems(): context[k] = v category_name = context['category'] #获取分类 categoryModel = Categorys.objects.filter( name=category_name).first() current_user = request.front_user article_content = context['textarea_content'] articleModel = Articles(title=title, subtitle=subtitle, categorys=categoryModel, author=current_user, content=article_content) articleModel.save() for tag in tags: tagModel = Tags.objects.filter(pk=tag).first() articleModel.tags.add(tagModel) data = {'code': 200, 'info': u'恭喜您!文章发布成功!'} return JsonResponse(data) else: return render(request, 'front_add_article.html', {'error': '表单验证出错!'})
def _get_rss(): def _rss_datetime(ts): dt = datetime.fromtimestamp(ts, UTC_0) return dt.strftime('%a, %d %b %Y %H:%M:%S GMT') def _safe_str(s): if isinstance(s, str): return s if isinstance(s, unicode): return s.encode('utf-8') return str(s) limit = 20 name = u'廖雪峰的官方网站' description = u'' copyright = 'copyright 2013' domain = ctx.request.host articles = articles = Articles.select( 'where publish_time<? order by publish_time desc limit ?', time.time(), 50) for a in articles: a.content = texts.md2html(texts.get(a.content_id)) rss_time = articles and articles[0].publish_time or time.time() L = [ '<?xml version="1.0"?>\n<rss version="2.0"><channel><title><![CDATA[', name, ']]></title><link>http://', domain, '/</link><description><![CDATA[', description, ']]></description><lastBuildDate>', _rss_datetime(rss_time), '</lastBuildDate><generator>BrighterPage</generator><ttl>3600</ttl>' ] for a in articles: url = 'http://%s/article/%s' % (domain, a._id) L.append('<item><title><![CDATA[') L.append(a.name) L.append(']]></title><link>') L.append(url) L.append('</link><guid>') L.append(url) L.append('</guid><author><![CDATA[') L.append(a.user_name) L.append(']]></author><pubDate>') L.append(_rss_datetime(a.publish_time)) L.append('</pubDate><description><![CDATA[') L.append(texts.md2html(texts.get(a.content_id))) L.append(']]></description></item>') L.append(r'</channel></rss>') return ''.join(map(_safe_str, L))
def publish_article(): if session.get('username'): if request.method == 'GET': return render_template('publish.html') else: article_type = request.values.get('article_type') title = request.form.get('title').strip() content = request.form.get('content').strip() if title and content: article = Articles(type=article_type, title=title, content=content) author = Users.query.filter( Users.username == session['username']).first() article.author = author db.session.add(article) db.session.commit() return redirect( url_for('article.article_info', article_id=article.id)) else: flash(u'标题或内容不能为空', 'error') return render_template('publish.html') else: return redirect(url_for('auth.login'))
def add_book(): name=request.args.get('name') author=request.args.get('author') published=request.args.get('published') try: book=Articles( name=name, author=author, published=published ) db.session.add(book) db.session.commit() return "Book added. book id={}".format(book.id) except Exception as e: return(str(e))
def process_new_articles(articles_list): articles_outcome = [] for one_article in articles_list: source = one_article.get("source") author = one_article.get("author") description = one_article.get("description") title = one_article.get("title") url = one_article.get("url") urlToImage = one_article.get("urlToImage") publishedAt = one_article.get("publishedAt") new_article = Articles(source, author, title, description, url, urlToImage, publishedAt) articles_outcome.append(new_article) return articles_outcome
def edit_article(): article = Articles.get_by_id(ctx.request['_id']) if article is None: raise notfound() return dict( \ form_title = u'Edit Article', \ form_action = '/api/articles/%s/update' % article._id, \ _id = article._id, \ name = article.name, \ category_id = article.category_id, \ draft = article.draft, \ publish_time = article.publish_time, \ tags = article.tags, \ summary = article.summary, \ cover_id = article.cover_id, \ content = texts.get(article.content_id), \ categories = _get_categories())
def add_book_form(): if request.method == 'POST': name=request.form.get('name') author=request.form.get('author') published=request.form.get('published') try: book=Articles( name=name, author=author, published=published ) db.session.add(book) db.session.commit() return "Book added. book id={}".format(book.id) except Exception as e: return(str(e)) return render_template("getdata.html")
def create_article(): if request.method == 'POST': title = request.form['title'] intro = request.form['intro'] text = request.form['text'] article = Articles(title=title, intro=intro, text=text) try: db.session.add(article) db.session.commit() return redirect('/posts') except: return 'При добавлении страницы произошла ошибка' else: return render_template('create-article.html')
def articles_list(): form = ArticlesForm() all_articles = Articles.query.all() all_authors = Author.query.all() if request.method == "POST": if form.validate() is not False: new_article = Articles(request.form.get('author'), form.title.data, form.slug.data, form.lead.data, form.body.data, datetime.datetime.now()) db.session.add(new_article) db.session.commit() form = ArticlesForm() # Re-render the form return render_template('articles.html', form=form, all_articles=all_articles, all_authors=all_authors)
def get_ia_content(iamap): ia = Articles.select().group_by(Articles.iamap); content = Articles.select().where(Articles.iamap == iamap ) return render_template('maps.html', content = content, ia = ia)