class CommentModelTest(unittest.TestCase): """ """ def setUp(self): self.user_made = User(username='******', password='******', email='*****@*****.**') self.new_post = Posts(title='Python', blog='Python is awesome', category="flask", user=self.user_made) self.new_comment = Posts(comment='Great posts', post=self.new_post, user=self.user_made) def tearDown(self): Posts.query.delete() User.query.delete() Comment.query.delete() def test_check_instance_variables(self): self.assertEquals(self.new_comment.title, "Youre testing") self.assertEquals(self.new_comment.user, self.user_James) self.assertEquals(self.new_comment.post, self.new_post) def test_save_comment(self): self.new_comment.save_comment() self.assertTrue(len(Comment.query.all()) > 0)
def create_test_post(): for x in range(1, 200): content = '内容%s' % x author = Users.query.filter_by(id=13).first() post = Posts(content=content) post.user = author db.session.commit()
def index(): form = PostForm() if form.validate_on_submit(): post = Posts(body=form.body.data, timestamp=datetime.utcnow(), link=form.link.data, user_id=current_user.id) post.write(current_user) flash("Your post is now live!") return redirect(url_for("index")) page = request.args.get("page", 1, type=int) all_posts = current_user.followed_posts() posts_per_page = app.config["POSTS_PER_PAGE"] #The following statement helps implement pagination. posts = all_posts[(page - 1) * posts_per_page:page * posts_per_page] next_url = url_for("index", page=page+1)\ if (len(all_posts) > page*posts_per_page) else None prev_url = url_for("index", page=page-1)\ if (page-1 > 0) else None return render_template("index.html", title="Home", form=form, posts=posts, next_url=next_url, prev_url=prev_url)
def test_follow_posts(self): u1 = User(username = '******',email ='*****@*****.**') u2 = User(username = '******',email = '*****@*****.**') u3 = User(username = '******',email ='*****@*****.**') u4 = User(username = '******',email = '*****@*****.**') db.session.add_all([u1,u2,u3,u4]) now = datetime.utcnow() p1 = Posts(body = 'post from susan',author = u1,timestamp = now + timedelta(seconds = 1)) p2 = Posts(body = 'post from john',author = u2,timestamp = now + timedelta(seconds = 4)) p3 = Posts(body = 'post from mary',author = u3,timestamp = now + timedelta(seconds = 8)) p4 = Posts(body = 'post from david',author = u4,timestamp = now + timedelta(seconds = 10)) db.session.add_all([p1,p2,p3,p4]) db.session.commit() u1.follow(u2) u1.follow(u4) u2.follow(u3) u3.follow(u4) db.session.commit() f1 = u1.followed_posts().all() f2 = u2.followed_posts().all() f3 = u3.followed_posts().all() f4 = u4.followed_posts().all() self.assertEqual(f1,[p2,p4,p1]) self.assertEqual(f2,[p3,p2]) self.assertEqual(f3,[p4,p3]) self.assertEqual(f4,[p4])
def create_post(): if request.method == "POST": text = request.form['post'] post_name = request.form['post-name'] file = request.files['file'] print(request.files) user = sess.query(Users).filter_by(id=session['user-id']).first() if post_name and text and len(post_name) <= 20 and len(text) <= 600: if allowed_file(file.filename): data = sess.query(Users).order_by(Users.id).first() filename = str(data.id) + secure_filename(file.filename) print(filename) file.save(f'{UPLOAD_FOLDER}/{filename}') new_post = Posts(postname=post_name, post=text, username=user.username, user_id=user.id, image=filename) sess.add(new_post) sess.commit() else: new_post = Posts(postname=post_name, post=text, username=user.username, user_id=user.id, image=' ') sess.add(new_post) sess.commit() return redirect(url_for('user_profile', id=session['user-id'])) else: return redirect(url_for('create_post')) else: if 'user-id' in session: return render_template('create_post.html') return redirect(url_for('login'))
class PostsModelTest(unittest.TestCase): """ """ def setUp(self): self.user_James = User(username='******', password='******', email='*****@*****.**') self.new_post = Posts(title="You're testing", blog='This the test of the century', category="my-thoughts", user=self.user_James) def tearDown(self): Posts.query.delete() User.query.delete() def test_check_instance_variables(self): self.assertEquals(self.new_post.title, "Youre testing") self.assertEquals(self.new_post.blog, "This is the test of the century") self.assertEquals(self.new_post.category, "my-thoughts") self.assertEquals(self.new_post.user, self.user_James) def test_save_post(self): self.new_post.save_post() self.assertTrue(len(Posts.query.all()) > 0)
def setUp(self): self.user_James = User(username='******', password='******', email='*****@*****.**') self.new_post = Posts(title="You're testing", blog='This the test of the century', category="my-thoughts", user=self.user_James)
def create_test_posts(): for x in range(1, 255): title = '标题:%s' % x content = '内容: %s' % x posts = Posts(title=title, content=content) posts.uid = 1 db.session.add(posts) db.session.commit() print('插入成功')
def test_follow_posts(self): # Users u1 = User(pseudo="john", email="*****@*****.**") u2 = User(pseudo="marie", email="*****@*****.**") u3 = User(pseudo="david", email="*****@*****.**") u4 = User(pseudo="bob", email="*****@*****.**") db.session.add(u1) db.session.add(u2) db.session.add(u3) db.session.add(u4) # Posts now = datetime.utcnow() p1 = Posts(body="Post from John", author=u1, datestamp=now + timedelta(1)) p2 = Posts(body="Post from Marie", author=u2, datestamp=now + timedelta(2)) p3 = Posts(body="Post from David", author=u3, datestamp=now + timedelta(3)) p4 = Posts(body="Post from Bob", author=u4, datestamp=now + timedelta(4)) db.session.add(p1) db.session.add(p2) db.session.add(p3) db.session.add(p4) db.session.commit() # Followers u1.follow(u1).follow(u2).follow(u4) u2.follow(u2).follow(u3) u3.follow(u3).follow(u4) u4.follow(u4) assert (u1.is_following(u1)) assert (u1.is_following(u2)) assert (u1.is_following(u4)) db.session.commit() r1 = u1.followed_posts().all() r2 = u2.followed_posts().all() r3 = u3.followed_posts().all() r4 = u4.followed_posts().all() assert (len(r1) == 3) assert (len(r2) == 2) assert (len(r3) == 2) assert (len(r4) == 1) assert (r1 == [p4, p2, p1]) assert (r2 == [p3, p2]) assert (r3 == [p4, p3]) assert (r4 == [p4]) assert (True)
def setUp(self): self.user_made = User(username='******', password='******', email='*****@*****.**') self.new_post = Posts(title='Python', blog='Python is awesome', category="flask", user=self.user_made) self.new_comment = Posts(comment='Great posts', post=self.new_post, user=self.user_made)
def publish(): form = PostForm() if form.validate_on_submit(): if current_user.is_authenticated: # 如果登录 # 获取当前用户 u = current_user._get_current_object() p = Posts(content=form.content.data, user=u) db.session.add(p) flash('发表成功') # 到时候这个跳转要修改 return redirect(url_for('main.publish')) else: flash("请先登录") return redirect(url_for('users.login')) # 调取所有发表的博客 # posts = Posts.query.filter_by(rid=0).all() # www.baidu.com?page=1 # 接收用户 url传递过来的 page参数 page = request.args.get('page', 1, type=int) pagination = Posts.query.filter_by(rid=0).order_by( Posts.timestamp.desc()).paginate(page, per_page=5, error_out=False) posts = pagination.items return render_template('posts/publish.html', form=form, posts=posts, pagination=pagination)
def newpost(user_id): newpostform = NewPostForm() if request.method == "POST": if newpostform.validate_on_submit(): caption = newpostform.caption.data post_photo = newpostform.post_photo.data post_photoname = secure_filename(post_photo.filename) post_photo.save(os.path.join(app.config['UPLOAD_FOLDER'], post_photoname)) created_on = datetime.utcnow() post = Posts(user_id, post_photoname, caption, created_on) db.session.add(post) db.session.commit() newpostmessage = { "message": "Successfully created a new post" } return jsonify(newpostmessage=newpostmessage) else: return jsonify(errors={"errors":form_errors(newpostform)}) return jsonify(errors={"errors":form_errors(newpostform)})
def index(): form = PostsForm() if form.validate_on_submit(): # 判断用户是否是登录状态 if current_user.is_authenticated: user = current_user._get_current_object() posts = Posts(content=form.content.data, user=user) db.session.add(posts) return redirect(url_for('main.index')) else: flash('登录后才能发表') return redirect(url_for('user.login')) # 分页读取数据,然后展示 # 从请求的参数中获取当前页码,没有page参数默认为第一页 page = request.args.get('page', 1, type=int) # paginate参数介绍 # page:唯一的必须参数,表示当前的页码 # per_page:可选参数,表示每页显示的记录数,默认20条 # error_out:可选参数,页码超出范围时是否显示404错误,默认为True pagination = Posts.query.filter_by(rid=0).order_by( Posts.timestamp.desc()).paginate(page, per_page=5, error_out=False) # 获取当前页的记录 posts = pagination.items return render_template('main/index.html', form=form, posts=posts, pagination=pagination)
def index(): form = PostsForm() if form.validate_on_submit(): # 判断是否登录 if current_user.is_authenticated: # 获取原始的用户对象 u = current_user._get_current_object() # 创建对象 p = Posts(content=form.content.data, user=u) # 保存到数据库 db.session.add(p) flash('发表成功') return redirect(url_for('main.index')) else: flash('登录之后才可以发表') return redirect(url_for('user.login')) # 读取博客 # posts = Posts.query.filter(Posts.id == 0) # 分页查询 page = request.args.get('page', 1, int) # 将获取的页码参数转为int类型 pagination = Posts.query.filter(Posts.rid == 0).paginate(page, per_page=10, error_out=False) posts = pagination.items return render_template('main/index.html', form=form, pagination=pagination, posts=posts)
def index(): form = PostsForm() if form.validate_on_submit(): if current_user.is_authenticated: # 获取当前登录用户对象 user = current_user._get_current_object() # 创建对象 p = Posts(content=form.content.data, user=user) # 保存到数据库 db.session.add(p) flash('发表成功') return redirect(url_for('main.index')) else: flash('请登录后再发表') return redirect(url_for('user.login')) # 查询博客 # posts = Posts.query.filter(Posts.rid == 0).order_by(Posts.timestamp.desc()) # 分页查询 page = request.args.get('page', 1, int) pagination = Posts.query.filter(Posts.rid == 0).order_by( Posts.timestamp.desc()).paginate(page, per_page=3, error_out=False) posts = pagination.items return render_template('main/index.html', form=form, posts=posts, pagination=pagination)
def index(): form = PostsForm() if form.validate_on_submit(): if current_user.is_authenticated: u = current_user._get_current_object() p = Posts(content=form.content.data, user=u) db.session.add(p) flash("发表成功") return redirect(url_for('main.index')) else: flash("登录后才可发表") return redirect(url_for("user.login")) # 读取博客 # posts = Posts.query.filter(Posts.rid==0).order_by(Posts.timestamp.desc()).all() page = request.args.get("page", 1, type=int) pagination = Posts.query.filter(Posts.rid == 0).order_by( Posts.timestamp.desc()).paginate(page=page, per_page=5, error_out=False) # 当前页码的数据 posts = pagination.items return render_template('main/index.html', form=form, posts=posts, pagination=pagination)
def index(): form = PostsForm() if form.validate_on_submit(): # 判断是否登录 if current_user.is_authenticated: u = current_user._get_current_object() # 根据表单提交的数据常见对象 p = Posts(content=form.content.data, user=u) # 然后写入数据库 db.session.add(p) return redirect(url_for('main.index')) else: flash('登录后才能发表博客') return redirect(url_for('user.login')) # 从数据库中读取博客,并分配到模板中,然后在模板中渲染 # 安装发表时间,降序排列 # 只获取发表的帖子,过滤回复的帖子 #posts = Posts.query.filter_by(rid=0).order_by(Posts.timestamp.desc()).all() # 分页处理 # 获取当前页码,没有认为是第一页 page = request.args.get('page', 1, type=int) pagination = Posts.query.filter_by(rid=0).order_by( Posts.timestamp.desc()).paginate(page, per_page=1, error_out=False) posts = pagination.items return render_template('main/index.html', form=form, posts=posts, pagination=pagination)
def index(): form = PostForm() # 数据合法则保存 if form.validate_on_submit(): if not current_user.is_authenticated: flash('登录才能发言哦') return redirect(url_for('users.login')) else: user = current_user._get_current_object() post = Posts(content=form.content.data, user=user) db.session.add(post) return redirect(url_for('main.index')) # posts = Posts.query.filter_by(rid=0) # 指定渲染页数 分页代码 page = request.args.get('page', 1, type=int) pagination = Posts.query.filter_by(rid=0).order_by(db.desc( Posts.timestamp)).paginate(page, per_page=6) posts = pagination.items # 最热 最新 博文 Topposts = Posts.query.order_by(db.desc(Posts.views))[:5] Newposts = Posts.query.order_by(db.desc(Posts.timestamp))[:5] return render_template('common/index.html', form=form, posts=posts, Topposts=Topposts, Newposts=Newposts, pagination=pagination)
def index(): form = PostForm() if form.validate_on_submit(): if current_user.is_authenticated:#如果登录 #获取当前用户 u = current_user._get_current_object() p = Posts(content=form.content.data,user=u) db.session.add(p) return redirect(url_for('main.index')) else: flash("请先登录") return redirect(url_for('users.login')) #调取所有发表的博客 # posts = Posts.query.filter_by(rid=0).all() #www.baidu.com?page=1 #接收用户 url传递过来的 page参数 page = request.args.get('page',1,type=int) pagination = Posts.query.filter_by(rid=0).order_by(Posts.timestamp.desc()).paginate(page,per_page=5,error_out=False) posts = pagination.items return render_template('main/index.html',form=form,posts=posts,pagination=pagination) # @main.route('/token/',methods=['GET','POST']) # def token(): # s = Serializer(current_app.config['SECRET_KEY'],expires_in=3600) # return s.dumps({'id':666}) # # @main.route('/check/',methods=['GET','POST']) # def check(): # t = 'eyJhbGciOiJIUzUxMiIsImlhdCI6MTU0NzUzNzQ2OCwiZXhwIjoxNTQ3NTQxMDY4fQ.eyJpZCI6NjY2fQ.oVWgGFIS9ew0pZrzqk-5RetoUSBuPeimbMN4E7R1hveFhC3BAQlOSy-IH-0lBH7GnkaDvf2fasAMKmFCci4HiA' # s = Serializer(current_app.config['SECRET_KEY']) # data = s.loads(t) # return str(data['id'])
def create_post(): try: post = Posts(title=request.json['title'], description=request.json['description'], published=request.json['published'], publisher=request.json['publisher']) db.session.add(post) db.session.commit() if post.id is None: return { 'status_code': 408, 'status_msg': 'Request Timeout', 'description': "Something going wrong . Please try again." } return { 'id': post.id, 'status_code': 201, 'status_msg': 'created', "description": f"Post with id {post.id} successfully created." } except InternalError: db.session.rollback() return { 'status_code': 400, 'status_msg': 'Bad Request', "description": f"Something going wrong. Error: {InternalError}", }
def blog_view(post_id, slug): post = Posts.by_id(post_id) tags = Tag.query.join(FatJunction, FatJunction.tag_id==Tag.id) \ .filter(FatJunction.blog_id==post.id).all() return render_template('blog_view.html', post=post, tags=tags)
def index(): # 发表 form = PostsForm() if form.validate_on_submit(): # 用户想发表内容必须先登录 并且获取当前登录用户名 if current_user.is_authenticated: # 获取该用户对象 u = current_user._get_current_object() p = Posts(content=form.content.data, user=u) db.session.add(p) db.session.commit() return redirect(url_for('main.index')) else: flash('请先登录') return redirect(url_for('users.login')) # posts = Posts.query.filter_by(rid=0).all() # 获取发表的内容 # 获取用户查看第几页 page = request.args.get('page', 1, type=int) # pagination = Posts.query.filter_by(rid=0).order_by( Posts.timestamp.desc()).paginate(page, per_page=5, error_out=False) posts = pagination.items # 当前对象的所有数据 return render_template('main/index.html', form=form, posts=posts, pagination=pagination)
def userPosts(user_id): #Gets the current user to add/display posts to user = db.session.query(Users).get(user_id) form = PostsForm() if request.method == "POST" and form.validate_on_submit() == True: caption = form.caption.data photo = assignPath(form.photo.data) post = Posts(photo, caption, user_id) db.session.add(post) db.session.commit() #Flash message to indicate a post was added successfully success = "Successfully created a new post" return jsonify(message=success), 201 elif request.method == "GET": posts = [] for post in user.posts: p = { "id": post.id, "user_id": post.user_id, "photo": post.photo, "description": post.caption, "created_on": post.created_on } posts.append(p) return jsonify(posts=posts) #Flash message to indicate an error occurred failure = "Failed to create/display posts" return jsonify(error=failure)
def index(): #1 form = PostForm() if form.validate_on_submit(): language = guess_language(form.post.data) if language == 'UNKNOWN' or len(language) > 6: language = '' post = Posts(body=form.post.data, language=language, author=current_user) db.session.add(post) db.session.commit() flash('Your Post is Live !') return redirect(url_for('index')) page = request.args.get('page', 1, type=int) posts = current_user.followed_posts().paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('explore', page=posts.next_num) if posts.has_next else None prev_url = url_for('explore', page=posts.prev_num) if posts.has_prev else None return render_template('index.html', title='Machine Learning', user=user, form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
def index(): form = PostsForm() if form.validate_on_submit(): if not current_user.is_authenticated: flash('登录后才可发表') return redirect(url_for('user.login')) u = current_user._get_current_object() p = Posts(content=form.content.data, user=u) db.session.add(p) flash('发表成功') return redirect(url_for('main.index')) # 读取所有发表博客的数据(不分页) # posts= Posts.query.filter(Posts.rid==0).order_by(Posts.timestamp.desc()).all() # 分页查询发表博客的数据 # 获取当前页码 page = request.args.get('page', 1, int) pagination = Posts.query.filter(Posts.rid == 0).order_by( Posts.timestamp.desc()).paginate(page=page, per_page=10, error_out=False) posts = pagination.items return render_template('main/index.html', form=form, posts=posts, pagination=pagination)
def index(): form = PostsForm() if form.validate_on_submit(): # 判断是否登录 if current_user.is_authenticated: # 获取当前用户 u = current_user._get_current_object() # 创建博客对象 p = Posts(content=form.content.data, user=u) # 保存到数据库 db.session.add(p) return redirect(url_for('main.index')) else: flash('用户尚未登录。请登录后发表') return redirect(url_for('user.login')) # 分页读取数据 # 获取get参数里的页码,默认为当前页 page = request.args.get('page', 1, type=int) # 获取数据库中博客的数据,按时间排序(pagination是个对象) pagination = Posts.query.filter_by(rid=0).order_by(Posts.timestamp.desc()).paginate(page, per_page=5, error_out=False) # 读取每页数据 posts = pagination.items for post in posts: post.count = post.users.count() return render_template('main/index.html', form=form, pagination=pagination, posts=posts)
def userpost(user_id): form = PostForm() token = request.headers['Authorization'].split()[1] current_id = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])['id'] if request.method == 'POST' and form.validate_on_submit(): caption = form.caption.data photo = form.photo.data filename = photo.filename photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) post = Posts(user_id, filename, caption) db.session.add(post) db.session.commit() return jsonify({'message': 'Successfully created a post!'}), 201 allpost = [] posts = Posts.query.filter_by(user_id=user_id).order_by(desc( Posts.id)).all() user = Users.query.filter_by(id=user_id).first() follow = Follows.query.filter_by(user_id=current_id, follower_id=user_id).count() if (follow == 0): follow = "not following" else: follow = "following" followcount = Follows.query.filter_by(follower_id=user_id).count() postcount = Posts.query.filter_by(user_id=user_id).count() for post in posts: # getusername of post creator likes = Likes.query.filter_by(post_id=post.id).count() allpost.append({ 'id': post.id, 'user_id': post.user_id, 'photo': post.photo, 'caption': post.caption, 'no_likes': likes, 'created_on': post.created_on }) return jsonify({ 'postcount': postcount, 'followcount': followcount, 'follow': follow, 'user_id': user.id, 'username': user.username, 'firstname': user.firstname, 'lastname': user.lastname, 'location': user.location, 'joinedon': user.joined_on.strftime('%B %Y'), 'biography': user.biography, 'photo': user.display_photo, 'posts': allpost }), 200
def post_editing(request): if request.method == "POST": title = request.POST['title'] content = request.POST['content'] if not all([title, content]): return JsonResponse({"code": -1, "info": "请填写标题和内容"}) create_time = int(time.time()) username = request.session.get('username', '') post = Posts(title=title, content=content, create_time=create_time, username=username) post.save() return JsonResponse({"code": 0, "info": ""})
def index(request): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): Email = strip_tags(request.POST['Email']) Name = strip_tags(request.POST['Name']) Url = strip_tags(request.POST['Url']) Comment = strip_tags(request.POST['Comment']) newComment = Posts(name=Name, email=Email, url=Url, comment=Comment) newComment.save() else: form = CommentForm() posts = Posts.objects.all().order_by("-date") c = {'form': form, 'Posts' : posts} c.update(csrf(request)) return render_to_response('start.html', c)
class PitchModelTest(unittest.TestCase): def setUp(self): self.new_post = Posts(title="title", post="content") db.session.add(self.new_blog) db.session.commit() def tearDown(self): Posts.query.delete() db.session.commit() def test_save_blogs(self): self.new_post.save_post() self.assertTrue(len(Blog.query.all()) > 0) def test_check_instance_variables(self): self.assertEquals(self.new_blog.title, 'title') self.assertEquals(self.new_blog.post, 'content')
def create_post(): form = CreatePostForm() if form.validate_on_submit(): post_body = form.post.data post = Posts(body=post_body, user_id=current_user.id) db.session.add(post) db.session.commit() return redirect(url_for('user', username=current_user.username)) return render_template("create_post.html", form=form)
def index(request): if request.method == 'POST': form = CommentForm(request.POST, request.FILES) print form if form.is_valid(): Email = strip_tags(request.POST['Email']) Name = strip_tags(request.POST['Name']) Url = strip_tags(request.POST['Url']) Comment = strip_tags(request.POST['Comment']) Image = form.cleaned_data['Image'] print Image if Image.content_type.split("/")[0] == 'image': newComment = Posts(name=Name, email=Email, url=Url, comment=Comment, image=Image, imageType=Image.content_type) newComment.save() else: form = CommentForm() posts = Posts.objects.all().order_by("-date") c = {'form': form, 'Posts' : posts} c.update(csrf(request)) return render_to_response('start.html', c)