def get(self): default_size = 10 summary_length = 200 cate_id = self.get_query_argument('cate', None) size = self.get_query_argument('size', default_size) categories = Category.list(self.current_user.id) user_id = self.current_user.id if cate_id: drafts = Post.drafts_by_category(user_id, int(cate_id), 0, int(size)) count = Post.count_drafts_by_category(user_id, cate_id) else: drafts = Post.drafts(user_id, 0, int(size)) count = Post.count_drafts(user_id) for draft in drafts: draft['author'] = self.current_user _html = markdown.markdown(draft.content) soup = BeautifulSoup(_html, 'html.parser') img = soup.find('img') if img: img['class'] = 'inner-img-limit' _text = soup.get_text() if _text and len(_text) > summary_length: _text = _text[0:summary_length] + '...' draft['cover'] = img draft['summary'] = _text self.render('drafts.html', cate_id=cate_id, categories=categories, drafts=drafts)
def get(self, nick=None): posts = None if not nick: self.redirect('/posts') return select_user = '******' user = db.get(select_user, nick) if user: default_size = 10 summary_length = 200 need_pagination = False size = self.get_query_argument('size', default_size) count = Post.count_posts(user.id) posts = Post.list(user.id, 0, default_size) if posts: need_pagination = count > len(posts) for post in posts: _html = markdown.markdown(post.content) soup = BeautifulSoup(_html, 'html.parser') img = soup.find('img') if img: img['class'] = 'inner-img-limit' _text = soup.get_text() if _text and len(_text) > summary_length: _text = _text[0:summary_length] + '...' post['cover'] = img post['summary'] = _text post['author'] = user self.render('main.html', user=user, posts=posts, page_size=size, need_pagination=int(need_pagination))
def post(self): title = self.request.get('title').strip() content = self.request.get('content').strip() template_vars = {} template_vars['errors'] = {} template_vars['values'] = {} if not title: template_vars['errors']['title'] = 'Title is Required' if not content: template_vars['errors']['content'] = 'Content is Required' if len(template_vars['errors']) == 0: print 'no errors should create' # make post post = Post( title=title, content=content ) # save post inserted = post.put() # TODO - see if need to handle case where insert fails self.redirect('/post/%s' % inserted.id()) self.render('post_add', template_vars)
def postChallenge(): data = request.form.to_dict() ops = [] qtype = data['type'] data['testcases'] = json.loads(data['testcases']) lang = langs[data['lang']] user = get_jwt_identity() if any(bad in data['code'] for bad in lang.invalid): ret = '' for i in lang.invalid: ret += i return Response(json.dumps({'success': False, 'err': 'Unsupported functions used.\nCannot use These Functions : '+ret}), mimetype="application/json", status=200) else: for i, tc in enumerate(data['testcases']): op = compile_and_run_code(lang, data['code'], tc) if not op['success']: if op['timeout']: return Response(json.dumps({'success': False, 'err': 'Time out occured for Case #'+str(i+1)}), mimetype="application/json", status=200) else: return Response(json.dumps({'success': False, 'err': 'Error in TestCase #'+str(i+1)+op['err']}), mimetype="application/json", status=200) else: ops.append(op['output']) # return Response(json.dumps({'Success': 'True', 'op': ops}), mimetype="application/json", status=200) temp = Post(originalPostBy=user, title=data['title'], qtype=qtype, description=data['description'], code=data['code'], testcases=data['testcases'], outputs=ops) temp.save() User.objects(username=get_jwt_identity()).update_one(push__posts=temp.ID) return Response(json.dumps({'success': True, 'link': '/dashboard'}), mimetype="application/json", status=201)
def get(self): default_size = 10 summary_length = 200 need_pagination = False cate_id = self.get_query_argument('cate', None) size = self.get_query_argument('size', default_size) categories = Category.list(self.current_user.id) user_id = self.current_user.id if cate_id: posts = Post.list_by_category(user_id, int(cate_id), 0, int(size)) count = Post.count_posts_by_category(user_id, cate_id) else: count = Post.count_posts(user_id) posts = Post.list(user_id, 0, int(size)) if posts: need_pagination = count > len(posts) for post in posts: _html = markdown.markdown(post.content) soup = BeautifulSoup(_html, 'html.parser') img = soup.find('img') last_modified = post.last_modified if img: img['class'] = 'inner-img-limit' _text = soup.get_text() if _text and len(_text) > summary_length: _text = _text[0:summary_length] + '...' post['cover'] = img post['summary'] = _text post['author'] = self.current_user self.render('posts.html', cate_id=cate_id, categories=categories, posts=posts, page_size=size, need_pagination=int(need_pagination))
def create(): if request.method == "GET": return render_template("create.html") else: title = str(request.form.get("title")) body = request.form.get("body") category = request.form.get("category") published_at = str(datetime.utcnow()) user_id = "samjunior101" new_post = Post(title=title, body=body, user_id="samjunior101", category=category) data = { u'title': title, u'body': body, u'published_at': published_at, u'user_id': user_id, u'category': category } Post.save(data=data) return redirect(url_for('index'))
def post(self): subject = self.request.get("subject") content = self.request.get("content") if subject and content: post = Post(subject = subject, content = content) post.put() self.top_posts(update=True) self.redirect("/blog/"+str(post.key().id())) else: error = "we need both a subject and content!" self.render_new_post(subject,content,error)
def post(self): subject = self.request.get('subject') content = self.request.get('content') if subject and content: p = Post(parent=Utils().blog_key(), author=self.user, subject=subject, content=content) p.put() return self.redirect('/blog/%s' % str(p.key().id())) else: error = "subject and content are both needed!" self.render("newpost.html", subject=subject, content=content, error=error)
def seed_db(): # Seed database with example data from models.Post import Post from models.User import User from main import bcrypt from faker import Faker import random faker = Faker() users = [] for i in range(5): user = User() user.email = f"test{i}@test.com" user.name = faker.name() user.password = bcrypt.generate_password_hash("123456").decode("utf-8") user.created_at = datetime.now() db.session.add(user) users.append(user) db.session.commit() for i in range(20): post = Post() post.caption = faker.catch_phrase() post.created_at = datetime.now() post.updated_at = datetime.now() post.total_likes = 0 post.total_comments = 0 post.user_id = random.choice(users).id db.session.add(post) db.session.commit() print("Tables seeded")
def edit_post_submission(post_id): """updates the specified post to use the newly submitted data""" post_dict = process_post_form(request.form) if post_dict: title = post_dict['title'] content = post_dict['content'] tags = post_dict['tags'] Post.update_by_id(post_id, title, content, tags) return redirect(f'/posts/{post_id}') else: flash('Your Post Must Have a Title and Content!') return redirect(f'/posts/{post_id}/edit')
def new_post(self): tittle = input("Enter post Tittle: ") content = input("Enter post Content: ") date = input("Enter post date, or leave blank for today (in format DDMMYYYY ): ") if date == "": date = datetime.datetime.utcnow() # put localmachineDate in Date with DateFormat else: date=datetime.datetime.strptime(date, "%d%m%Y") #parse str to DateFormat post = Post(blog_id=self.id, tittle=tittle, content=content, author=self.author, date=date) post.save_to_mongo()
def edit_post(id): today_date = date.today() if request.method == "POST": title = request.form['title'] content = request.form['content'] category_id = request.form['category'] add_post = Post().update_post([title, content, category_id], current_user.id) return redirect(url_for('dashboard')) post = Post().view_single_post(id) category = Category().view_all_category() return render_template('edit_post.html', post=post, category=category)
def post(self, post_id): ''' Adds or removes likes depending on if a like exists for the post by the current user and the current user did not write the post ''' current_user = self.authenticate_user() post = Post.get_by_id(long(post_id)) like = Like.query(Like.user == current_user.key, Like.post == post.key).get() if post.user == current_user.key: self.redirect(self.request.referer) elif like: remove_user_like(current_user, like) remove_post_like(post, like) like.key.delete() else: like = Like(user=current_user.key, post=post.key) like.put() post.likes.append(like.key) post.put() current_user.likes.append(like.key) current_user.put() self.redirect(self.request.referer)
def submit(id): data = request.form.to_dict() ops = [] lang = langs[data['lang']] user = get_jwt_identity() try: post = Post.objects(ID=id)[0].to_mongo() if any(bad in data['code'] for bad in lang.invalid): ret = '' for i in lang.invalid: ret += i return Response(json.dumps({'success': False, 'err': 'Unsupported functions used.\nCannot use These Functions : '+ret}), mimetype="application/json", status=200) else: for i, tc in enumerate(post['testcases']): op = compile_and_run_code(lang, data['code'], tc) if not op['success']: if op['timeout']: return Response(json.dumps({'success': False, 'err': 'Time out occured for Case #'+str(i+1)}), mimetype="application/json", status=200) else: return Response(json.dumps({'success': False, 'err': 'Error in TestCase #'+str(i+1)+op['err']}), mimetype="application/json", status=200) else: ops.append(op['output']) for i, op in enumerate(ops): if op == post['outputs'][i]: continue else: return Response(json.dumps({'success': False, 'err': 'Error in TestCase #'+str(i+1)+'\nExpected : '+post['outputs'][i]+'\nGot : '+op}), mimetype="application/json", status=200) User.objects(username=get_jwt_identity() ).update_one(push__posts=post['_id']) return Response(json.dumps({'success': True, 'link': '/dashboard'}), mimetype="application/json", status=201) except: return Response(json.dumps({'Success': False, 'redirect': '/'}), mimetype="application/json", status=200)
def get(self, post_id): post = Post.getById(post_id) if not post: self.error(404) self.write( "<h1>404 Not Found</h1>The resource could not be found.") return comments = Comment.getByPostID(post_id) comments_count = Comment.countByPostID(post_id) likes_num = Like.countByPostID(post_id) # Get post status (liked or not) by a specific user like_btn_txt = "Like" if self.user: if Like.getByPostAndAuthor(post_id, self.user.name): like_btn_txt = "Unlike" self.render("post.html", post=post, comments_count=comments_count, comments=comments, likes_num=likes_num, like_text=like_btn_txt)
def post_links(): session = Session() data = json.loads(request.data) for link in data['links']: post = Post.get_or_create(session, link['reddit_id']) subreddit = Subreddit.get_or_create(session, link['sub_name']) user = User.get_or_create(session, link['authorname']) post.subreddit_id = subreddit.id post.author_id = user.id post.domain = link['domain'] post.title = link['title'] post.url = link['url'] post.score = link['score'] post.downs = link['downs'] post.ups = link['ups'] post.is_self = link['is_self'] post.over_18 = link['over_18'] post.thumbnail = link['thumbnail'] post.created = float(link['created']) post.scraped_time = Util.now() session.add(post) session.commit() session.close() return jsonify({'received':True})
def post(self): if self.user: subject = self.request.get("subject") content = self.request.get("content") if subject and content: new_post = Post(subject=subject, content=content, author=self.user.name) new_post.put() self.redirect("/post/%s" % str(new_post.key.id())) else: error = "Both fields are required" self.render_page("newpost.html", subject, content, error=error) else: self.redirect("/login")
def post(self, post_id): # get the key for this blog post post = Post.getById(post_id) if not post: self.response.out.write("Not a valid post!") if not self.user: return self.redirect('/login') if post.author != self.user.name: self.render("post.html", post=post, title=post.subject, error="You're not allowed to edit this article!") return subject = self.request.get('subject') content = self.request.get('content') if subject and content: # update the blog post and redirect to the post page post.subject = subject post.content = content post.put() time.sleep(0.1) self.redirect('/post/%s' % str(post.key.id())) else: post_error = "Please enter a subject and the blog content" self.render("editpost.html", subject=subject, content=content, post_error=post_error)
def get(self, post_id): """ Renders the post.html template with the requested post """ current_user = self.authenticate_user() if not post_id: self.render("post.html", error="No post id provided") else: post = Post.get_by_id(long(post_id)) if not post: self.render("post404.html") else: user = User.get_by_id(post.user.id()) comments = Comment.query().filter(Comment.post == post.key).fetch() likes = Like.query(Like.post == post.key).fetch() like = Like.query( Like.user == current_user.key, Like.post == post.key).get() self.render( "post.html", post=post, current_user=current_user, user=user, like_count = len(likes), like=like, comments=comments)
def category_posts(id): posts = Post().view_by_category(id) # return json.dumps(post) category = Category().view_single_category(id) return render_template('category_posts.html', posts=posts, category=category)
def post(self, post_id): """ Attempt to create a new blog post """ current_user = self.authenticate_user() if not current_user: self.redirect("/login") else: content = self.request.get("content") title = self.request.get("subject") post = Post.get_by_id(long(post_id)) if not post: self.render("/post404.html") elif current_user.key != post.user: self.redirect("/post/" + str(post.key.id())) elif not content or not title: self.render_front(post_id, error="We need both a title and content") else: post.title = title post.content = content post.put() self.redirect("/post/" + str(post.key.id()))
def my_posts(): items = [] posts = Post.objects(originalPostBy=get_jwt_identity()) for post in posts: item = post.to_mongo() items.append(item) return render_template('myposts.html', posts=items, logged_in=True)
def mypost(id): user = User.objects(username=get_jwt_identity())[0].to_mongo() if id not in user['posts']: return redirect('/dashboard') post = Post.objects(ID=id)[0].to_mongo() return render_template('viewpost.html', logged_in=True, post=post)
def new_post(self): title = raw_input("Enter post title: ") content = raw_input("Enter post content: ") date = raw_input( "Enter post date, or leave blank for today (in format DDMMYYYY): ") if date == "": date = datetime.datetime.utcnow() else: date = datetime.datetime.strptime(date, "%d%m%Y") post = Post(blog_id=self.id, title=title, content=content, author=self.author, date=date) post.save_to_mongo()
def index(): if current_user.is_authenticated(): date_string = make_datestring(today()) try: post = Post.objects.get( date_string=date_string, owner=current_user.id ) except Post.DoesNotExist: post = Post(date_string=date_string, owner=current_user.id) post.save() return render_template( 'index.html', post=post, past_status=past_status(), user=current_user ) return render_template('unauth_index.html')
def post(self, id, update=False): post_id = int(id) res = self.client.get(id) if res is None or update: post = Post.get_by_id(post_id) last_update = datetime.utcnow() res = (post,last_update) self.client.set(id, res) return res
def globalwall(): user = User.objects(username=get_jwt_identity())[0].to_mongo() items = Post.objects(qtype='Global') items = [item.to_mongo() for item in items] items = [item for item in items if item['_id'] not in user['posts']] items.reverse() return render_template('globalwall.html', posts=items[:MAX_POSTS_GLOBAL_WALL], logged_in=True)
def post_create(): post_name = request.form.get("post_name") post_description = request.form.get("post_description") profile = Profiles.query.filter_by(user_id=current_user.id).first() new_post = Post() new_post.post_name = post_name new_post.post_description = post_description new_post.profile_id = current_user.id # new_post.profile_id = profile.profileid #profile.post.append(new_post) db.session.add(new_post) db.session.commit() # return jsonify(post_schema.dump(new_post)) return redirect(url_for('post.post_index'))
def solve(id): user = User.objects(username=get_jwt_identity())[0].to_mongo() if id in user['posts']: return redirect('/dashboard') try: post = Post.objects(ID=id)[0].to_mongo() return render_template('solve.html', langs=langs, logged_in=True, post=post) except: return redirect('/dashboard')
def viewed_posts(): items = [] user = User.objects(username=get_jwt_identity())[0].to_mongo() posts_id = user['posts'] for postid in posts_id: post = Post.objects(ID=postid)[0].to_mongo() if post['originalPostBy'] != user['username']: items.append(post) return render_template('viewedposts.html', posts=items, logged_in=True)
def edit(post_id): if request.method == "GET": post = dictify(Post.get_one(post_id=post_id)) return render_template("edit.html", post=post) else: title = str(request.form.get("title")) body = request.form.get("body") category = request.form.get("category") user_id = "samjunior101" data = { u'title': title, u'body': body, u'user_id': user_id, u'category': category } Post.save(data=data, post_id=post_id) return redirect(url_for("index"))
def solution(id): user = User.objects(username=get_jwt_identity())[0].to_mongo() try: post = Post.objects(ID=id)[0].to_mongo() if id not in user['posts']: User.objects(username=get_jwt_identity()).update_one( push__posts=post['_id']) return render_template('solution.html', logged_in=True, post=post) except: return redirect('/')
def update(session, user, praw_post, score): post = Post.get_or_create(session, praw_post.id) post.update_from_praw(praw_post) post.author_id = user.id Util.update_subreddit(Subreddit, post, session, praw_post.subreddit.display_name) vote = Vote.get_or_create(session, user, post, score) vote.vote = score session.add(vote) session.add(post)
def seed_db(): from models.Profiles import Profiles from faker import Faker from models.Users import Users from main import bcrypt from models.Post import Post import random faker = Faker() profiles = [] true_or_false = [True, False] posts = [] for i in range(10): user = Users() user.email = f"test{i}@test.com" user.password = bcrypt.generate_password_hash("123456").decode("utf-8") db.session.add(user) #accounts.append(user) db.session.commit() for i in range(10): profile = Profiles() profile.username = faker.name() profile.fname = faker.first_name() profile.lname = faker.last_name() profile.account_active = faker.boolean() profile.user_id = i + 1 db.session.add(profile) profiles.append(profile) db.session.commit() for i in range(30): new_post = Post() new_post.post_name = faker.name() new_post.post_description = faker.catch_phrase() new_post.profile_id = random.choice(profiles).profileid posts.append(new_post) db.session.add(new_post) db.session.commit() print("Tables seeded")
def get_post_vars(post_id): post = Post.get_by_id(post_id) errors = {} template_vars = { 'id': post_id, 'title': post.title, 'content': post.content, 'errors': errors } return template_vars
def get(self, post_id=None): user_id = self.current_user.id post = None if post_id: _post = Post.get_post(post_id) if _post and _post.user_id == user_id: post = _post get_categories = 'select id, name from tb_category where visible = 1 and user_id = %s' categories = db.query(get_categories, user_id) referer = self.request.headers.get('Referer') or '/' self.render('edit.html', categories=categories, post=post, referer=referer)
def past_status(): post_map = dict() posts = Post.objects(owner=current_user.id).order_by('-date').limit(29) for post in posts: post_map[post.date_string] = ( post.completed, post.length, post.url_string() ) return [ post_map.get( make_datestring(today() - timedelta(days=i)), (False, 0, None) ) for i in reversed(range(1, 29)) ]
def get(self): res = {'data': None} need_pagination = False summary_length = 260 offset = self.get_query_argument('offset', 0) size = self.get_query_argument('size', 10) user_id = self.current_user.id count = Post.count_posts(user_id) posts = Post.list(user_id, int(offset), int(size)) if posts: need_pagination = count > (int(offset) + int(size)) for post in posts: _html = markdown.markdown(post.content) soup = BeautifulSoup(_html, 'html.parser') _text = soup.get_text() if _text and len(_text) > summary_length: _text = _text[0:summary_length] + '...' post['summary'] = _text post['author'] = self.current_user data = {'posts': posts, 'need_pagination': need_pagination} self.send_result(True, data, None)
def get(self, id): post = Post.get_post(id) if post: if not ord(post.public): if not self.current_user: self.write_error(403, '您没有该文章的阅读权限') return elif self.current_user.id != post.user_id: self.write_error(403, '您没有该文章的阅读权限') return query_author = 'select id, nick from tb_user where id = %s' author = db.get(query_author, post.user_id) post['author'] = author post = json.dumps(post, cls=modules.utils.JSONEncoder) self.send_result(True, post, None) return self.write_error(404)
def main(notify): session = Session() gen = r.get_subreddit("all").get_top(limit=3000) start = session.query(Post).count() notify("Getting posts, initial count: %d" % start) count = 0 for post in gen: count += 1 p = Post.get_or_create(session, post.id) p.update_from_praw(post) author_name = Util.patch_author(post.author) Util.update_user(User, p, session, author_name) Util.update_subreddit(Subreddit, p, session, post.subreddit.display_name) session.add(p) session.commit() diff = session.query(Post).count() - start notify("Added %d posts" % diff)
def get(self, id): read_mode = self.get_query_argument('mode', None) post = Post.get_post(id) if post: if not ord(post.public): if not self.current_user: raise tornado.web.HTTPError(403) return elif self.current_user.id != post.user_id: raise tornado.web.HTTPError(403) return query_author = 'select id, nick from tb_user where id = %s' author = db.get(query_author, post.user_id) post['author'] = author else: raise tornado.web.HTTPError(404) template_name = 'post.html' if self.is_mobile: template_name = 'read_focus.html' elif read_mode and read_mode == 'focus_read': template_name = 'read_focus.html' self.render(template_name, post=post)
def create_post(): session = Session() post = Post.create('woops', sync=True, session=session) session.close() return post.slug
def get_past(): if not current_user.is_authenticated(): return redirect(url_for("index")) posts = Post.objects(owner=current_user.id, length__gt=0).order_by('-date') return render_template('past.html', posts=posts)
def delete(self, post_id): if Post.pretend_delete(post_id): self.send_result(True, error_code=None) return self.send_result()