def update_blog(request): """ Expects:{"username":"******","name":"Default","content":"This is some HTML"}\n 1.Updates article for user\n 2.Ensures unique blog name , (can be replaced by an custom ID field to allow duplicate blogs)\n 3.Checks if the blogs username is registered 4.Checks if the owner of the article in request is actually the owner TODO : Verify user login via session / Use PUT instead of POST / Use Partial update """ if request.method == 'POST': queryset = Blog.objects.all() serializer = BlogSerilizer(data=request.data) updated_blog = request.data['name'] userset = User.objects.all() for user in userset: if user.username == request.data['username']: for blogs in queryset: if updated_blog == blogs.name: if blogs.username == request.data['username']: if serializer.is_valid(): blog_id = blogs.id blog_obj = Blog(id=blog_id, name=updated_blog, content=request.data['content'], username=request.data['username']) blog_obj.save(force_update=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_412_PRECONDITION_FAILED)
def post(self): """ Post method to create new posts :rtype: object """ blog = {} _title = self.request.get("title") _blog = self.request.get("blog") _title_error = "Please enter title" _post_error = "Please enter post" if self.user: if _title and _blog: user = self.user newPost = Blog(user=user.key, title=_title, blog=_blog) newPost_key = newPost.put() newPostID = newPost_key.id() self.redirect('/blog/%s' % str(newPostID)) elif _title == "" or _blog == "": if _title == "": blog["title"] = "" blog["blog"] = _blog self.render('newpost.html', title_error=_title_error, blog=blog) if _blog == "": blog["title"] = _title blog["blog"] = "" self.render('newpost.html', post_error=_post_error, blog=blog) else: self.redirect('/login')
def _get_blogs_by_page(): total = Blog.count_all() page = Page(total, _get_page_index()) blogs = Blog.find_by(' order by create_at desc limit ?,?', page.offset, page.limit) return blogs,page
def api_create_blog(request, *, name, summary, content, hide, categorys_tag): check_admin(request) if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty.') if not summary or not summary.strip(): raise APIValueError('summary', 'summary cannot be empty.') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty.') if not hide: hide = False if not categorys_tag: raise APIValueError('categorys_tag', 'categorys_tag cannot be empty.') categorys_bit = yield from categorys_tag2bit(categorys_tag) blog = Blog( user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, name=name.strip(), summary=summary.strip(), content=content.strip(), hide=hide, categorys_bit=categorys_bit ) yield from blog.save() return blog
def post(self): """ Post method to like and unlike blogs """ if self.user: if self.request.get("like_blog"): _blog_id = self.request.get("like_blog") user = self.user user_id = user.key.id() _user = User.by_id(int(user_id)) _blog = Blog.get_by_id(int(_blog_id)) like = Like(user=user.key, blog=_blog.key) like.like = 1 like_key = like.put() blog = _blog.key.get() blog.likes.append(like_key) blog.put() self.redirect('/') if self.request.get("dislike"): _blog_id = self.request.get("dislike") user = self.user user_id = user.key.id() _user = User.by_id(int(user_id)) _blog = Blog.get_by_id(int(_blog_id)) like = Like.query(Like.user == user.key, Like.blog == _blog.key).get() like_key = like.key blog = _blog.key.get() blog.likes.remove(like_key) blog.put() like_key.delete() self.redirect('/') else: self.redirect('/login')
def Post(self): title = self.Request.get("title") content = self.Request.get("content") blog = Blog(title=title, content=content) blog.put() return webapp2.redirect("/blog")
def index(request): context = base_context() rpp = record_per_page() cur_page = 1 try: cur_page = int(request.REQUEST["jumpPage"].strip()) except: cur_page = 1 blogs_count = Blog.all().count() max_page = blogs_count / rpp temp2 = blogs_count % rpp if temp2 != 0: max_page = max_page + 1 if cur_page > max_page or cur_page <= 0: cur_page = max_page blogs = Blog.all().order("-date").fetch(0) else: blogs = Blog.all().order("-date").fetch(rpp, rpp * (cur_page - 1)) context.cur_page = cur_page context.max_page = max_page context.action_mode = "/" context.range1 = range(1, max_page + 1) context.up_page = cur_page - 1 context.down_page = cur_page + 1 context.blogs = blogs template = loader.get_template("blogs/index.html") return HttpResponse(template.render(context))
def api_create_blog(request, *, name, summary, content): # 校验当前用户权限: check_admin(request) # 校验传递值中参数‘name’是否为空或空串,为空则抛出异常: if not name or not name.strip(): # 参数‘name’为空则抛出异常: raise APIValueError("name", "name cannot be empty.") # 校验传递值中参数‘summary’是否为空或空串,为空则抛出异常: if not summary or not summary.strip(): raise APIValueError("summary", "summary cannot be empty.") # 校验传递值中参数‘content’是否为空或空串,为空则抛出异常: if not content or not content.strip(): raise APIValueError("content", "content cannot be empty.") # 创建Blog实例: blog = Blog( user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, name=name.strip(), summary=summary.strip(), content=content.strip(), ) # 将Blog信息存储到数据库: yield from blog.save() return blog
def blog_add(): user_now = current_user() blog = Blog(request.form) blog.user = user_now blog.save() log('发布成功') return redirect(url_for('timeline_view', username=user_now.username))
def test_get_select_posts_bytag(self): blog = Blog('tests/data/feed.xml') selected = blog.select_posts_bytag(u'鏡館') for p in selected: self.assertTrue(u'鏡館' in p.tags)
def blog_add(request): if request.method == 'POST': form = BlogForm(request.POST) tag = TagForm(request.POST) if form.is_valid() and tag.is_valid(): cd = form.cleaned_data cdtag = tag.cleaned_data tagname = cdtag['tag_name'] for taglist in tagname.split(): Tag.objects.get_or_create(tag_name=taglist.strip()) title = cd['caption'] author = Author.objects.get(id=1) content = cd['content'] blog = Blog(caption=title, author=author, content=content) blog.save() for taglist in tagname.split(): blog.tags.add(Tag.objects.get(tag_name=taglist.strip())) blog.save() id = Blog.objects.order_by('-publish_time')[0].id return HttpResponseRedirect('blog/%s' % id) else: form = BlogForm() tag = TagForm(initial={'tag_name': 'notags'}) return render_to_response('blog_add.html', {'form': form, 'tag': tag}, context_instance=RequestContext(request))
def post(self): update = self.request.get('update', False) cate_name = self.request.get('cate_name') tags_list = self.request.get_all('tags_name', []) title = self.request.get('title') blog = self.request.get('blog') if not blog: self.response.write('blog content empty!') cate = Category.query(Category.title==cate_name).get() if not cate: cate = Category(title=cate_name) cate.put() print tags_list tags = Tag.query(Tag.title.IN(tags_list)).fetch() tags_old = [tag.title for tag in tags] tags_new = [] for tag in tags_list: if tag not in tags_old: tag = Tag(title=tag) tag.put() tags_new.append(tag) print tags print tags_new tags += tags_new print tags print '===' print dir(tags[0]) tags = [tag.key for tag in tags] blog = Blog(title=title, text=blog, category=cate.key, tags=tags) blog.put() self.response.write('blog publish success') self.response.set_status(200)
def api_blogs(*, page='1'): page_index = get_page_index(page) num = yield from Blog.findNumber('count(id)') p = Page(num, page_index) if num == 0: return dict(page=p, blogs=()) blogs = yield from Blog.findAll(orderBy='created_at desc', limit=(p.offset, p.limit)) return dict(page=p, blogs=blogs)
def index(*, page="1"): page_index = get_page_index(page) num = yield from Blog.findNumber("count(id)") p = Page(num, page_index, page_size=5) blogs = yield from Blog.findAll(orderBy="created_at desc", limit=(p.offset, p.limit)) for blog in blogs: blog.html_summary = markdown2.markdown(blog.summary) return {"__template__": "blogs.html", "page_index": get_page_index(page), "blogs": blogs}
def api_index(*, page="1"): page_index = get_page_index(page) num = yield from Blog.findNumber("count(id)") p = Page(num, page_index, page_size=5) if num == 0: return dict(page=p, blogs=()) blogs = yield from Blog.findAll(orderBy="created_at desc", limit=(p.offset, p.limit)) return dict(page=p, blogs=blogs)
def api_delete_blog(blog_id): check_admin() blog = Blog.get(blog_id) blog = Blog.get(blog_id) if blog is None: raise APIResourceNotFoundError("Blog") blog.delete() return dict(id=blog_id)
def test_single_existence(self): """Test that the blog is created only once """ self.blog = Blog(title = "test",tag_line = "new blog",entries_per_page=10,recents = 5, recent_comments = 5) self.blog.save() blog = Blog(title = "test",tag_line = "new blog",entries_per_page=10,recents = 5, recent_comments = 5) #should raise Exception when another blog is created self.assertRaises(Exception,blog.save()) self.blog.delete()
def index(*, page="1"): page_index = get_page_index(page) num = yield from Blog.findNumber("count(id)") page = Page(num, page_index) if num == 0: blogs = [] else: blogs = yield from Blog.findAll(orderBy="created_at desc", limit=(page.offset, page.limit)) return {"__template__": "blogs.html", "page": page, "blogs": blogs}
def add(request): if request.user.is_authenticated(): category= get_object_or_404(Category, category=request.POST.get('category')) blog = Blog(title=request.POST.get('title'), body=request.POST.get('body'), author=request.user, category=category) blog.save() return HttpResponseRedirect(reverse('Blog:main')) else: return HttpResponse("You are not logged in.")
def myapi_blogs(request,*, page='1'): where_user='******'+'\''+request.__user__.name+'\'' page_index = get_page_index(page) num = yield from Blog.findNumber('count(id)',where=where_user) p = Page(num, page_index) if num == 0: return dict(page=p, blogs=()) blogs = yield from Blog.findAll(where=where_user,orderBy='created_at desc', limit=(p.offset, p.limit)) return dict(page=p, blogs=blogs)
def add_entry(): if not session.get('logged_in'): abort(401) blog = Blog() blog.title = cgi.escape(request.form['title']) blog.text = cgi.escape(request.form['text']) blog.put() flash('New entry was successfully posted') return redirect(url_for('show_entries'))
def get_blogs(*, p_index=1): int_index = get_page_index(p_index) num = yield from Blog.findNumber('count(id)') p = Page(num, int_index, page_size=5) if num == 0: return dict(page=p, blogs=()) blogs = yield from Blog.findAll(orderBy='created_at desc', limit=(p.offset, p.limit)) return dict(page=p, blogs=blogs)
def new_blog(request): if request.method != 'POST': c = {} c.update(csrf(request)) return render(request, "new_blog_form.html",c) else: blog = Blog(baslik=request.POST['baslik'],icerik=request.POST['icerik'],olusturulma_tarihi=datetime.today()) blog.save() return redirect('/blog/list_blogs')
def myapi_create_blog(request, *, name, summary, content,id): if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty.') if not summary or not summary.strip(): raise APIValueError('summary', 'summary cannot be empty.') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty.') blog = Blog(user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, name=name.strip(), summary=summary.strip(), content=content.strip(),id=id) yield from blog.save() return blog
def api_private_blogs(*, page='1'): page_index = get_page_index(page) num = yield from Blog.findNumber('count(id)') p = Page(num, page_index, page_size=20) if num == 0: return dict(page=p, blogs=()) blogs = yield from Blog.findAll(orderBy='created_at desc', limit=(p.offset, p.limit)) for blog in blogs: blog.content = '' return dict(page=p, blogs=blogs)
def api_blogs(*, page='1'): page_index = get_page_index(page) num = yield from Blog.findNumber('count(id)') # num为博客总数 p =Page(num, page_index) # 创建page对象 if num ==0: return dict(page=p, blogs=()) # 博客书不为0就从数据库中抓取博客 # limit强制select返回指定的记录数 blogs = yield from Blog.findAll(orderBy='created_at desc', limit=(p.offset, p.limit)) return dict(page=p, blogs=blogs) # 返回dict,以供response的中间件处理
def api_blogs(*, page='1'): page_index = get_page_index(page) num = yield from Blog.findNumber('count(id)') # num为博客总数 p = Page(num, page_index) # 创建page对象 if num == 0: return dict(page=p, blogs=()) # 若博客数为0,返回字典,将被app.py的response中间件再处理 # 博客总数不为0,则从数据库中抓取博客 # limit强制select语句返回指定的记录数,前一个参数为偏移量,后一个参数为记录的最大数目 blogs = yield from Blog.findAll(orderBy="created_at desc", limit=(p.offset, p.limit)) return dict(page=p, blogs=blogs) # 返回字典,以供response中间件处理
def api_blogs(*, page="1"): # 获取页面索引,默认为1: page_index = get_page_index(page) # 查询数据库中Blog表中文章总数: num = yield from Blog.findNumber("count(id)") p = Page(num, page_index) if num == 0: return dict(page=p, blogs=()) # 查询数据库中Blog表中对应分页的文章结果;(limit为mysql的分页查询条件) blogs = yield from Blog.findAll(orderBy="created_at desc", limit=(p.offset, p.limit)) return dict(page=p, blogs=blogs)
def get_blog(blog_id): blog = yield from Blog.find(blog_id) comments = yield from Blog.findAll('blog_id = ?', [blog_id], orderBy = 'created_at desc') for c in comments: c.html_content = text2html(c.content) blog.html_content = markdown2.markdown(blog.content) return { '__template__': 'blogs.html', 'blog': blog, 'comments': comments }
def api_blogs(*, page = '1'): # 获取博客信息,调用位置:manage_blogs.html 40行 ''' 请参考29行的api_get_users函数的注释 ''' page_index = get_page_index(page) blog_count = yield from Blog.findNumber('count(id)') p = Page(blog_count, page_index) if blog_count == 0: return dict(page = p, blogs = []) blogs = yield from Blog.findAll(orderBy = 'created_at desc', limit = (p.offset, p.limit)) return dict(page = p, blogs = blogs)
def api_create_comment(id, request, *, content): user = request.__user__ if user is None: raise APIPermissionError('Please signin first.') if not content or not content.strip(): raise APIValueError('content') blog = yield from Blog.find(id) if blog is None: raise APIResourceNotFoundError('Blog') comment = Comment(blog_id=blog.id, user_id=user.id, user_name=user.name, user_image=user.image, content=content.strip()) yield from comment.save() return comment
def get_blog(id, request): #get_blog({'id':'151fadksjfalfjlka'}) #print('id', id, 'kw', kw) #kw没有,应该是app看它注册的就只给了id吧... #001514861142476bd95fab85f7542178dba245d02470c57000 blog = yield from Blog.find(id) comments = yield from Comment.findAll('blog_id=?', [id], orderBy='created_at desc') for c in comments: c.html_content = text2html(c.content) blog.html_content = markdown2.markdown(blog.content) if request.__user__: #从request中判断有无登陆信息,有的话添加 user = request.__user__ return { '__template__': 'blog.html', 'blog': blog, 'comments': comments, '__user__': user #附加上__user__属性代其利用 }
async def api_create_blog(request, *, name, summary, content): check_admin(request) if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty.') if not summary or not summary.strip(): raise APIValueError('summary', 'summary cannot be empty.') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty.') blog = Blog(user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, name=name.strip(), summary=summary.strip(), content=content.strip()) await blog.save() return blog
def add_blog(): if current_user: if request.form['inputTitle'] and request.form['inputDescription']: blog_desc = re.sub('<[^>]*>', '', request.form['inputDescription']) blog_obj = Blog(title=request.form['inputTitle'], description=blog_desc, user_id=current_user.id) db.session.add(blog_obj) if blog_obj: db.session.commit() flash('You have successfully created your blog', 'success') return redirect(url_for('blog_mod.blog_home')) else: return render_template('error.html', error='No data found') else: flash('Please enter blog details', 'error')
async def test(): await orm.create_pool(loop, user='******', password='******', db='awesome') #u = User(name='Test', email='*****@*****.**', passwd='1234567890', image='about:blank') u = Blog(user_id='test_id', user_name='test_user_name', user_image='test_img', name='test_name', summary='test_summary', content='test_content') await u.save()
def api_update_blog(id, request, *, name, class_id, summary, content): check_admin(request) blog = yield from Blog.find(id) if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty.') if not class_id or not class_id.strip(): raise APIValueError('class_id', 'class_id cannot be empty.') if not summary or not summary.strip(): raise APIValueError('summary', 'summary cannot be empty.') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty.') blog.name = name.strip() blog.class_id = class_id.strip() blog.summary = summary.strip() blog.content = content.strip() yield from blog.update() return blog
def api_create_comment(request, *, blog_id, content): user = request.__user__ if user is None: raise APIPermissionError('Please signin first.') if not content or not content.strip(): raise APIValueError('content') blog = yield from Blog.find(blog_id) print("blog--------->" + blog.id) if blog is None: raise APIResourceNotFoundError('Blog') if blog is not None and blog.commentState == '0': raise APIValueError('prohibiting', '该文章已禁止评论.') comment = Comment(blog_id=blog_id, user_id=user.id, content=content.strip()) yield from comment.save() return comment
def api_modify_blog(request, *, id, name, summary, content): logging.info('修改的博客的ID为:%s' % id) if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty.') if not summary or not summary.strip(): raise APIValueError('summary', 'summary cannot be empty.') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty.') blog = yield from Blog.find(id) blog.name = name blog.summary = summary blog.content = content yield from blog.update() return blog
def newpost(): if request.method == 'POST': blog_title = request.form['title'] blog_body = request.form['blog-entry'] if blog_body.strip() == "" or blog_title.strip() == "": flash('Please enter content into both text areas') return redirect('/newpost') new_entry = Blog(blog_title, blog_body, logged_in_user()) db.session.add(new_entry) db.session.commit() post_id = new_entry.id return redirect('/blog/{0}'.format(post_id)) return render_template('newpost.html')
def api_create_comment(id): ##通过Cookie查询登录用户 user = cookie2user() if user is None: raise APIPermissionError('Please signin first.') content = request.json['content'] if not content or not content.strip(): raise APIValueError('content') blog = Blog.get(id=id) if blog is None: raise APIResourceNotFoundError('Blog') comment = Comment(blog_id=blog.id, user_id=user.id, user_name=user.name, user_image=user.image, content=content.strip()) return comment.to_dict()
def show_posts(): posts = Blog().get_posts() result = [] if not posts: abort(400) for post in posts: temp = {} temp['id'] = post["_id"] temp['title'] = post["title"] temp['body'] = post["body"] comments = Comment().get_comment(post["_id"]) if comments is not None: tree = arrangecomments(comments) temp['comments'] = tree result.append(temp) # result = [{col: getattr(d, col) for col in cols} for d in post] return jsonify({"Post":result})
def api_get_blog(*, id): blog = yield from Blog.find(id) tags = [] if blog.tags: for tag_id in blog.tags.split(","): tag = yield from Tags.find(tag_id) if tag: tags.append({"key": tag.id, "value": tag.name}) blog.tags = tags blog.alltags = [{ "key": tag.id, "value": tag.name } for tag in (yield from Tags.find_all())] return blog
async def blogTest(loop): await orm.create_pool(loop, host='192.168.125.116', user='******', password='******', db='awesome') b = Blog(user_id='0015290387322034e831203fda641f9a44caeea44d4902a000', user_name='Test03', name='blog1', content='content1!!!', summary='about:blank', user_image='about:blank') await b.remove() blogs = await Blog.findAll() for b in blogs: print(b) await b.remove()
async def api_create_blogs(request, *, name, summary, content): check_admin(request) if not name or not name.strip(): raise APIValueErrpr('name', 'name is not be empty') if not summary or not summary.strip(): raise APIValueErrpr('summary', 'summary is not be empty') if not content or not content.strip(): raise APIValueErrpr('content', 'content is not be empty') user = request.__user__ blog = Blog(user_id=user.id, user_image=user.image, user_name=user.name, summary=summary.strip(), content=content.strip(), name=name.strip()) await blog.save() return blog
def api_update_blog(id, request, *, name, summary, picture, content): check_admin(request) blog = yield from Blog.find(id) if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty.') if not summary or not summary.strip(): raise APIValueError('summary', 'summary cannot be empty.') if not picture or not picture.strip(): raise APIValueError('picture', '[update_blog] picture cannot be empty.') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty.') blog.name = name.strip() blog.summary = summary.strip() blog.picture = picture.strip(), blog.content = content.strip() yield from blog.update() return blog
async def api_create_blog(request, *, name, summary, content): # 只有管理员可以写博客 check_admin(request) # name,summary,content 不能为空 if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty') if not summary or not summary.strip(): raise APIValueError('summary', 'summary cannot be empty') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty') # 根据传入的信息,构建一条博客数据 blog = Blog(user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, name=name.strip(), summary=summary.strip(), content=content.strip()) # 保存 await blog.save() return blog
def api_create_blog_comment(blog_id): user = ctx.request.user if user is None: raise APIPermissionError('Need signin.') blog = Blog.get(blog_id) if blog is None: raise APIResourceNotFoundError('Blog') content = ctx.request.input(content='').content.strip() if not content: raise APIValueError('content') c = Comment(blog_id=blog_id, user_id=user.id, user_name=user.name, user_image=user.image, content=content) c.insert() return dict(comment=c)
def get_blog(id, request): blog = yield from Blog.find(id) # 如果不是管理员访问,则访问计数加1 try: check_admin(request) except APIPermissionError as e: blog.viewed_count += 1 yield from blog.update() comments = yield from Comment.findAll('blog_id=?', [id], orderBy='created_at desc') for c in comments: c.content = text2html(c.content) blog.content = markdown2.markdown(blog.content,extras=["fenced-code-blocks", "tables", "wiki-tables", "cuddled-lists"]) return { '__template__': 'blog.html', 'blog': blog, 'comments': comments }
def signin(): if request.method == 'GET': return render_template('signin.html') else: email = request.form['email'] password = request.form['password'] u = User.find_where('where email=?', email) print password, u[0].password if not u or password != u[0].password: raise Exception("signin failed!!") global user user = u[0] blogs = Blog.find_all() resp = make_response(render_template('blogs.html')) #resp=make_response('<h1>hello world! </h1>') resp.set_cookie(user.name, make_cookie(user)) return resp
async def api_create_blogs(request, *, title, summary, content, blogId): if blogId: blog = await Blog.find(blogId) blog.name = title blog.summary = summary blog.content = content await blog.update() else: blog = Blog(user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, name=title.strip(), summary=summary.strip(), content=content.strip(), created_at=time.time()) await blog.save() return blog
async def api_edit_blog(request, *, id,name, summary, content,category_id): check_admin(request) oldblog = await Blog.find(id) if not oldblog: raise APIValueError('id', 'id cannot be effect.') if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty.') if not summary or not summary.strip(): raise APIValueError('summary', 'summary cannot be empty.') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty.') if not category_id or not category_id.strip(): raise APIValueError('category_id', 'category_id cannot be empty.') blog = Blog(id=id,user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, name=name.strip(), summary=summary.strip(), content=content.strip(), category_id=category_id.strip(),created_at=oldblog.created_at) await blog.update() return blog
def api_create_blog_comment(blog_id): ''' 创建评论 ''' blog = Blog.get(blog_id) if blog is None: raise APIResourceNotFoundError('Blog') content = ctx.request.input(content='').content.strip() if not content: raise APIValueError('content') c = Comment(blog_id=blog_id, user_id=1, user_name='匿名', user_image='', content=content) c.insert() return dict(comment=c)
async def api_update_blog(id, request, *, name, summary, content): check_admin(request) blog = Blog.find(id) if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty.') if not summary or not summary.strip(): raise APIValueError('summary', 'summary cannot be empty.') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty.') blog.name = name.strip() blog.summary = summary.strip() blog.content = content.strip() await blog.update() return blog
def newpost(): blogs = Blog.query.order_by(Blog.pubdate.desc()).all() placeholder = random.choice([ "What's on your mind?", "How're you doing today?", "This message is randomly generated! Neat!", "I'm running out of random messages to display...", ]) if request.method == 'POST': blog_title = request.form['blog_title'] blog_body = request.form['blog_body'] title_error = body_error = '' if not blog_title: title_error = "Your blog needs a title." if not blog_body: body_error = "Please add some content to your blog post." if not title_error and not body_error: new_blog = Blog(blog_title, blog_body) db.session.add(new_blog) db.session.commit() blog_id = new_blog.id return redirect('/blog?id={0}'.format(blog_id)) else: return render_template( 'newpost.html', title='New Blog Post', blog_body=blog_body, blog_title=blog_title, title_error=title_error, body_error=body_error, placeholder=placeholder, blogs=blogs, ) return render_template( 'newpost.html', title='New Blog Post', placeholder=placeholder, blogs=blogs, )
def new_post(): if request.method == 'POST': title = request.form['title'] body = request.form['body'] owner = User.query.filter_by(username=session['username']).first() if title != "" and body != "": new_post = Blog(title, body, owner) db.session.add(new_post) db.session.commit() id = str(new_post.id) return redirect('/blog?id='+id) else: flash("Please make sure neither field is empty!", 'error') return render_template('newpost.html', title=title, body=body) return render_template('newpost.html')
async def api_create_blog(request, *, name, summary, content, private=1): check_admin(request) if not name or not name.strip(): raise APIValueError('name', 'name can not be empty') if not summary or not summary.strip(): raise APIValueError('summary', 'summary can not be empty') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty ') user = await User.findAll('email=?', [request.__user__.email]) blog = Blog(user_id=request.__user__.id, user_name=request.__user__.name, private=private, user_image=request.__user__.image, name=name.strip(), summary=summary.strip(), content=content.strip()) await blog.save() return blog
def create_users(word_list, n=6): i = 0 while i < n: current_user = User(rand_name(), 'abc') # rs1 = rand_str(11) # # rs2 = rand_str(11) rs1 = rand_sentence(word_list) rs2 = rand_sentence(word_list, 8) # print(rs1) # print() # print(rs2) current_blog = Blog(rs1, rs2, current_user) db.session.add(current_user) db.session.add(current_blog) i += 1
def newpost(): if request.method == "POST": title = request.form["title"] body = request.form["body"] owner = User.query.filter_by(username=session["username"]).first() if title and body: post = Blog(title, body, owner.id) db.session.add(post) db.session.commit() post_id = str(post.id) return redirect("/blog?id={0}".format(post_id)) else: flash("Please enter a title and content for your new blog post.", "error") return render_template("newpost.html", title=title, body=body) return render_template("newpost.html")
def new_post(): if request.method == "POST": title = request.form['title'] body = request.form['body'] owner = User.query.filter_by(name=session['name']).first() if title == '': flash("Must have a blog title", 'error') if body == '': flash("Must have content in blog", "error") elif title != '' and body != '': new_blog = Blog(title, body, owner) db.session.add(new_blog) db.session.commit() blog_id = str(new_blog.id) return redirect("/blog?id=" + blog_id) return render_template('/new_post.html')
def api_update_blog(id, request, *, name, summary, content, project_status): check_admin(request) blog = yield from Blog.find(id) if not name or not name.strip(): raise APIValueError('name', 'name cannot be empty.') if not summary or not summary.strip(): raise APIValueError('summary', 'summary cannot be empty.') if not content or not content.strip(): raise APIValueError('content', 'content cannot be empty.') if not project_status or not project_status.strip(): raise APIValueError('project_status', 'project_status cannot be empty.') blog.name = name.strip() blog.summary = summary.strip() blog.content = content.strip() blog.project_status = project_status.strip() yield from blog.update() return blog