def post(self): if not self.user: self.redirect('/login') return postbutton = self.request.get("postbutton") if postbutton == "submit": subject = self.request.get('subject') content = self.request.get('content') if subject and content: p = Post(parent=blog_key(), subject=subject, content=content, postuser=self.user) p.put() self.redirect('/blog/%s' % str(p.key().id())) return else: error = "You must enter the subject and the content for the post." self.render("newpost.html", subject=subject, content=content, error=error) if postbutton == "cancel": self.redirect('/')
def get_posts() -> Any: args = parse_args(Config.ARGS, request.args) valid, message = validate_args(Config.ARGS, args) if not valid: return make_response(jsonify({"error": message}), 400) if args["update"] == "sync": logger.info("sync update requested") Post.fetch_all(Config) logger.info("sync update done") if args["update"] == "async": logger.info("async update requested") redis_conn = Redis(host=Config.REDIS_HOST, port=Config.REDIS_PORT, db=Config.REDIS_DB) q = Queue(connection=redis_conn) # no args implies the default queue job = q.enqueue(Post.fetch_all, Config) logger.info(f"job for async update issued, job id: {job.id}") return make_response( jsonify({"message": f"update requested, job id: {job.id}"}), 200) query = Post.query_posts( sort=args["sort"], order=args["order"], limit=args["limit"], offset=args["offset"], ) return make_response(jsonify([p.to_dict() for p in query]), 200)
def remove_post(id): if not g.db.doc_exist(id): abort(404) Post.get(id).delete() flash('Post was successfully removed') return redirect(url_for('show_posts'))
def createPost(): nTitle = request.forms.get('title') nBody = request.forms.get('body') nDateTime = datetime.datetime.now() author = User.get(User.firstname == 'alibi') post = Post(title=nTitle, body=nBody, published_date=nDateTime, user=author) post.save() return template('blog', posts=Post.select())
def post(self): subject = self.request.get("subject") content = self.request.get("content") if subject and content: post_db = Post(subject = subject, content = content) post_db.put() post_url = str(post_db.key().id()) self.redirect("/unit6/blog/%s" % post_url) else: self.render(subject = subject, content = content, error = "Please make sure both fields are submitted correctly")
def addPost(): url = 'editpost.html' user = getUserByEmail(login_session['email']) if user: # POST method add category if request.method == 'POST': # check if title and content exists title = request.form.get('title', None) content = request.form.get('post_content', None) picture = request.form['picture'] description = request.form['description'] if title and content: post = Post( title=title, user_id=user.id, picture=picture, description=description, post_content=content, date_added=datetime.datetime.now(), ) session.add(post) session.commit() keywords = request.form['keywords'].split(',') try: for k in keywords: if k: k = Keyword(post_id=post.id, word=k) session.add(k) session.commit() except Exception as e: print e flash(create_alert('Error in saving keywords', 'danger')) return redirect(url_for('showPost', post_id=post.id)) else: # title or content is empty if request.form['origin'] == 'html': # html edit status url = 'editpost_html.html' flash( create_alert('Title and Content must not be empty', 'danger')) return render_template(url, user_logged=user, post=None) # GET method shows add page if request.args.get('mode'): url = 'editpost_html.html' post = Post(title='', description='', post_content='', picture='') return render_template(url, post=post, edit=False, user_logged=user) else: return redirect(url_for('login'))
def create(): ''' Creates a new article ''' if request.method == 'POST': if request.form['title'] != '' and request.form['body'] != '' and request.form['picture'] != '.gitignore': # create the new article here :) if request.form['topic'] == '_newTopic': art = Post(topic = request.form['newTopic'],title=request.form['title'],picture='/static/' + request.form['picture'],body=request.form['body']) else: art = Post(topic = request.form['topic'],title=request.form['title'],picture='/static/' + request.form['picture'],body=request.form['body']) db.session.add(art) db.session.commit() flash('successfully created new article',category='info') else: flash('error, missing required portion, or using invalid Image',category='error') return render_template('addArticle.html')
def get(self, uid): user = User.by_id(int(uid)) # posts = db.GqlQuery("SELECT * FROM User WHERE postuser = :1 ORDER BY desc", user) posts = Post.all().filter('postuser ='******'-created') # This will display the posts created by the user or a black page if # there are no posts self.render('front.html', posts=posts)
def fetch_x_days(sub, sub_id, last=None): param = {"before": f"t3_{base36.dumps(last)}"} if last is not None else {} i = 0 for s in reddit.subreddit(sub).new(limit=1000, params=param): author = getattr(s, "author", {}) try: p = Post(title=s.title, user_id=int(getattr(author, "id", "-1"), 36), username=getattr(author, "name", ""), link=s.url, num_comments=s.num_comments, score=s.score, r_id=int(s.id, 36), date=date.fromtimestamp( s.created_utc).strftime("%Y-%m-%d"), updated=int(time() * 1000), sub_id=sub_id) except Exception as e: print(f"oopsie\n{e}") continue session.add(p) if i % 100 == 0: session.commit()
def postmessage(): if redirect_is_not_logged(session) != True: return redirect_is_not_logged(session) new_post = {} if 'username' in session: if request.method == 'POST': message = request.form.get('message', None) title = request.form.get('title', None) redirection = request.form.get('redirection', None) if title: post = Post(title=title, message=message, user_id=session['id'], created=datetime.datetime.now()) db.session.add(post) db.session.commit() if redirection is not None: user = db.session.execute( 'SELECT user.* FROM user WHERE user.username = :username', { 'username': redirection }).first() print(redirection) if user is not None: return redirect(url_for('profile', username=user.username)) # new_post['title'] = title # new_post['message'] = message # return render_template('index.html', page_name="Home", new_post=new_post , session=session) return redirect(url_for('index'))
def get(self, post_id): post_lookup = Post.get_by_id(int(post_id)) if post_lookup: self.render(post_lookup=post_lookup) else: self.write("Sorry, Page could not be found. Please try again.")
def get(self, post_id): post_lookup = Post.get_by_id(int(post_id)) if post_lookup: queried = last_queried(post_id) self.render(post_lookup=post_lookup, last_queried = queried) else: self.write("Sorry, Post could not be found. Please try again.")
def get(self): posts = Post.all().order('-created') if self.user: self.render('front.html', posts=posts, heading_text="") else: self.redirect('/login') return
def like_post(id): if not g.db.doc_exist(id): abort(404) post = Post.get(id) uid = session.get('uid') if uid not in post.likes: post.likes.add(uid) else: post.likes.remove(uid) post.save() return 'OK', 200, {'Content-Type': 'text/plain'}
def about(): form = Publish() if form.validate_on_submit(): post = Post(title=form.title.data, content=form.content.data, author=current_user) db.session.add(post) db.session.commit() flash('Post has been created!', 'success') return redirect(url_for('home')) return render_template('about.html', form=form, legend='New Post')
def get_posts(update=False): q = Post.query().order(-Post.created) q = q.fetch(10, use_cache=False, use_memcache=False) mc_key = 'BLOGS' posts, age = age_get(mc_key) if update or posts is None: posts = list(q) age_set(mc_key, posts) return posts, age
def show_posts(): form = PostForm(request.form) posts = list(Post.view('posts/by_date'))[::-1] errors = [] if request.method == 'POST' and form.validate(): new_post = make_post_from_request(request) g.db.save_doc(new_post) flash('New post was successfully created') return redirect(url_for('show_posts')) errors.extend(format_form_errors(form.errors.items())) return render_template \ ('main.html', form = form, posts = posts, submit = 'Share', errors = errors)
def query(self, id): try: item = db.session.query(Item).get(id) post = db.session.query(Post).get(item.post_id) if post is None: post = Post(**config.POST_TEMPLATE) return { "name": item.name, "post": post, "display": item.display } except: db.session.rollback() return None
def star_post(id): if not g.db.doc_exist(id): abort(404) post = Post.get(id) uid = session.get('uid') user = User.get(uid) if uid not in post.stars: post.stars.add(uid) user.starred.add(post._id) else: post.stars.remove(uid) user.starred.remove(post._id) post.save() user.save() return 'OK', 200, {'Content-Type': 'text/plain'}
def get(self): posts, age = utils.get_posts() if self.request.url.endswith('.json'): self.response.headers['Content-Type'] = ('application/json; ' 'charset=UTF-8') allPosts = [{'content': p.content, 'created': p.created.strftime('%c'), 'subject': p.subject} for p in Post.query().order(-Post.created)] self.response.write(json.dumps(allPosts)) else: self.render('/templates/blogfront.html', posts=posts, age=utils.age_str(age))
def add(self, title, description, usage, complexity, code, note): try: post = Post(title=title, description=description, usage=usage, complexity=complexity, code=code, note=note, author=current_user.name) db.session.add(post) db.session.commit() return True except: db.session.rollback() return False
def newPosts(): if 'username' not in login_session: return redirect('/login') if 'username' in login_session: if request.method == 'POST': newpost = Post(name=request.form['name'], user_id=login_session['user_id'], post_type=request.form['post_type'], description=request.form['description'], image=request.form['image'], ratings=request.form['ratings']) session.add(newpost) flash("New Post Created Successfully") session.commit() return redirect(url_for('showPosts')) else: return render_template('newPost.html')
def apply(self, id, title, description, usage, complexity, code, note): try: post = Post(title=title, description=description, usage=usage, complexity=complexity, code=code, note=note, author=current_user.name) db.session.add(post) db.session.flush() item = db.session.query(Item).get(id) item.post_id = post.id db.session.commit() return True except: db.session.rollback() return False
def addNewPosts(subredditName, session): subreddit = reddit.subreddit(subredditName) newPosts = [] existingPosts = [pId for pId, in session.query(Post.postId)] for submission in subreddit.new(limit=100): if submission.id not in existingPosts: post = Post(postId=submission.id, title=submission.title, subreddit=submission.subreddit.display_name, created=int(submission.created_utc), author=submission.author.name) newPosts.append(post) session.add_all(newPosts) session.commit() logging.info(f"{subredditName}: added {len(newPosts)} new posts")
def new_post(self): post = Post() txt = input() self.__posts = self.__data.get_posts() # checks if posts.txt is empty (ternary doesn't work) if self.__posts == []: temp = str() else: temp = self.__posts[-1] post.set_crt(self.__cur_user.get_id()) # to avoid 'index out of range' error (ternary doesn't work) if isinstance(temp, str): id = 0 else: id = temp.get_id() post.set_id(id + 1) post.set_txt(txt) self.__data.push_post(post)
def addpost(): if request.method == 'GET': return render_template('addpost.html') else: post_title = request.form.get('title') post_continent = request.form.get('continent') post_country = request.form.get('country') post_city = request.form.get('city') if post_city != "": post_country += "," post_text = request.form.get('textish') post_pic_url = request.form.get('pic_url') thepost = Post(title=post_title, continent=post_continent, country=post_country, city=post_city, text=post_text, img_url=post_pic_url) session.add(thepost) session.commit() return redirect(url_for('feed'))
def get(self, post_id): post_key = 'POST_' + post_id post, age = utils.age_get(post_key) if not post: post = Post.get_by_id(long(post_id)) if not post: self.response.write('This page doesn\'t exist!') utils.age_set(post_key, post) age = 0 if self.request.url.endswith('.json'): self.response.headers['Content-Type'] = ('application/json; ' 'charset=UTF-8') p = {'content': post.content, 'created': post.created.strftime('%c'), 'subject': post.subject} self.response.write(json.dumps(p)) else: self.render('/templates/permanent.html', post=post, age=utils.age_str(age))
def edit_post(id): if not g.db.doc_exist(id): abort(404) form = PostForm(request.form) post = Post.get(id) errors = [] if request.method == 'POST' and form.validate(): post.title = form.title.data post.text = form.text.data post.tags = set(form.tags.data.split()) post.save() flash('Post was successfully updated') return redirect(url_for('show_posts')) elif request.method == 'POST' and not form.validate(): errors.extend(format_form_errors(form.errors.items())) elif request.method == 'GET': form.title.data = post.title form.text.data = post.text form.tags.data = ' '.join(post.tags) return render_template \ ('edit_post.html', id = id, form = form, submit = 'Update', errors = errors)
def before_request(): g.db = connect_db(app.config['DB']) User.set_db(g.db) Post.set_db(g.db)
def process_post(data): nonlocal req user = get_current_user(req) with db: Post.create(user=user, content=data['content']) return
async def home_screen(req, resp): user = get_current_user(req) friends = get_friends(user) posts = Post.select().where(Post.user << [user, *friends]).order_by( Post.date.desc()) resp.content = api.template('home.html', user=user, posts=posts)
def show_posts_tag(tag): posts = list(Post.view('posts/by_tag', key=tag)) return render_template('posts.html', posts = posts)
def show_posts_starred(): # I think it's not a good idea to use such implementation. user = User.get(session.get('uid')) posts = [elem for elem in Post.view('posts/by_date') if elem._id in user.starred] return render_template('posts.html', posts = posts)
from database import db, User,Post,Comment,Anon,Target from werkzeug.security import generate_password_hash, check_password_hash from app import ap #from database import db db.init_app(ap) with ap.app_context(): db.create_all() #two example users b = User(name='test',password='******',email='[email protected]') a = User(name='ethan',password='******',email='a',permission=999) # add and save the users db.session.add(a) db.session.add(b) db.session.commit() #example of an article p1 = Post(topic='misc',title='Example Article',picture='/static/Pic.jpg',body='This is the body of the article, which accepts <i> HTML tags </i>') p2 = Post(topic='misc',title='Ex2',picture='/static/Pic.jpg',body='some random placeholder text here please') p3 = Post(topic='a new topic appears',title='Example Article',picture='/static/Pic.jpg',body='I yote a duck off a cliff... turns out they can fly, so everything was fine') db.session.add(p1) db.session.add(p2) db.session.add(p3) db.session.commit() #c = Comment(title='test',message='I love testing',poster='testman',article=1) #db.session.add(c) db.session.commit() quit()
def blog_view(): return template('blog', posts=Post.select())