def new_post(community_name): community = Community.query.filter_by( community_name=community_name).first() members_count = CommunityMembers.query.filter_by( community_id=community.id).count() form = PostForm() if form.validate_on_submit(): # Put data into our database here if form.picture.data: picture_file = save_picture(form.picture.data) #Upload Picture to Cloudinary # cloudinary.uploader.upload("./static/images/" + picture_file) cloudinary_response = cloudinary.uploader.upload( "./static/images/" + picture_file) print(cloudinary_response) print(dir(cloudinary_response)) print(cloudinary_response['public_id']) cloudinary_url = cloudinary_prefix + str( cloudinary_response['version']) + "/" + str( cloudinary_response['public_id']) + "." + str( cloudinary_response['format']) print('Sassy' * 100) print(cloudinary_url) #cloudinary_response.public_idj example to get items post = Post(user_id=current_user.id, community_id=community.id, title=form.title.data, body=form.content.data, image_url=picture_file, cloud_version=cloudinary_response['version'], cloud_public_id=cloudinary_response['public_id'], cloud_format=cloudinary_response['format'], cloudinary_url=cloudinary_url) db.session.add(post) db.session.commit() flash('Your post has been created!', 'success') # How to route user back to the community's page efficiently? return redirect('/k/' + community_name) else: post = Post(user_id=current_user.id, community_id=community.id, title=form.title.data, body=form.content.data) db.session.add(post) db.session.commit() flash('Your post has been created!', 'success') # How to route user back to the community's page efficiently? return redirect('/k/' + community_name) return render_template('create_post.html', form=form, community=community, legend='New Post', members_count=members_count)
def test_post_tag(self): t1 = Tag(name='iot') t2 = Tag(name='web') p1 = Post(content='This is a post contain iot and web tags.') p2 = Post(content='This is a post contain web.') p1.add_all_tags([t1, t2]) p2.tags.append(t2) self.session.add_all([t1, t2, p1, p2]) self.session.commit() self.assertCountEqual(t1.posts, [p1]) self.assertCountEqual(t2.posts, [p1, p2]) self.assertCountEqual(p1.tags, [t1, t2]) self.assertCountEqual(p2.tags, [t2])
def post_page(): if request.method == "POST": owner = User.query.filter_by(username=session['username']).first() species = request.form["species"] breed = request.form["breed"] color = request.form["color"] size = request.form["size"] name = request.form["name"] city = request.form["city"] state = request.form["state"] species = strip_str(species) species = species.upper() breed = strip_str(breed) breed = breed.upper() color = strip_str(color) color = color.upper() name = strip_str(name) name = name.upper() city = strip_str(city) city = city.upper() post_id = Post(species, breed, color, size, name, city, state, owner) db.session.add(post_id) db.session.commit() return redirect("/") return render_template("post.html")
def create_new_post(patient_id, img_path, form_data): """Add a new post to the database.""" time_stamp = datetime.now() meal_time = form_data.get("meal-time") meal_setting = form_data.get("meal-setting") TEB = form_data.get("TEB") hunger = form_data.get("hunger") or None fullness = form_data.get("fullness") or None satisfaction = form_data.get("satisfaction") or None meal_notes = form_data.get("meal-notes") new_post = Post(patient_id=patient_id, time_stamp=time_stamp, meal_time=meal_time, img_path=img_path, meal_setting=meal_setting, TEB=TEB, hunger=hunger, fullness=fullness, satisfaction=satisfaction, meal_notes=meal_notes) db.session.add(new_post) db.session.commit() return "Success"
def add_post_post(): post = Post(title=request.form["title"], content=mistune.markdown(request.form["content"]), author=current_user) session.add(post) session.commit() return redirect(url_for("posts"))
def load(self, fname): X, y = [], [] df = pd.read_csv(fname, encoding='latin1') for index, row in df.iterrows(): # post = Post(id=row['Date'], data=row['Comment'], actual_label=row['Insult'], tagged_data=row['pos_tag'], # bad_word='') post = Post(id=row['ID'], data=row['Comment'], actual_label=row['Label'], bad_word='') '''if row['post_type'] == 'Question': question = Question(id=row['id'], data=row['post'], actual_label=row['label'], bad_word=row['bad_word'], tagged_data=row['pos_tag_question']) X.append(question) y.append(row['label']) elif row['post_type'] == 'Answer': answer = Answer(id=row['id'], data=row['post'], actual_label=row['label'], bad_word=row['bad_word'], tagged_data=row['pos_tag_answer']) X.append(answer) y.append(row['label'])''' X.append(post) y.append(row['Label']) return np.array(X), np.array(y)
def blog(): current_user = request.user if request.method == "POST": title = request.form.get("posttitle") text = request.form.get("posttext") post = Post(title=title, text=text, user=current_user) db.add(post) db.commit() # send notification email msg = Message(subject="WebDev Blog - Registration Successful", sender=SENDER, recipients=[current_user.email]) msg.body = f"Hi {current_user.username}!\nWelcome to our WebDev Flask site!\nEnjoy!" msg.html = render_template("new_post.html", username=current_user.username, link=f"{HOST_ADDR}/posts/{post.id}", post=post) mail.send(msg) return redirect(url_for('blog')) if request.method == "GET": posts = db.query(Post).all() return render_template("blog.html", posts=posts, user=request.user)
def post(self): """create a post and redirect to MyPost handler""" if self.with_no_user(): self.redirect("/") return uid = self.user.key().id() uname = self.user.name title = self.request.get("title") subtitle = self.request.get("subtitle", "") content = self.request.get("content") if title and content: content = content.replace('\n', '<br>') post = Post(uid=uid, uname=uname, title=title, subtitle=subtitle, content=content) post.put() self.redirect("/post/" + str(post.key().id())) else: error = "Both title, subtitle and content are needed!" self.render("new_post.html", title=title, content=content, error=error)
def post_wall_post(wall_id): #get request data request_json = json.loads(request.form['data']) media_type = request_json['type'] text = request_json['text'] user = request_json['user'] if media_type == 'image': #it is an image that we should save file_hash = ''.join( random.choice(string.ascii_letters) for x in range(20)) print request.files.keys() f = request.files['file'] filename = '../tmp/' + file_hash + secure_filename(f.filename) f.save(filename) else: filename = None p = Post(text=text, type=media_type, content_local_path=filename, user=user) wm = WalledModel() #small abstraction layer for redis post = wm.create_post(p) wm.add_post_to_wall(wall_id, post.id) #store post in redis wallize.delay(wall_id, post.id) #ask celery to create image from post return post.to_json() #return
def create_post(): """Generates a new post from sources.""" bot_id = request.form.get('bot_id') bot = Bot.query.get(bot_id) try: chains = markovify.Text(bot.source.content) text = chains.make_sentence() except KeyError as error: print(error) text = None if text == None: flash('*the bot hums gently*') return redirect("/bot/" + bot_id) post = Post(bot_id=bot_id, content=text) db.session.add(post) db.session.commit() return redirect("/bot/" + bot_id)
def post(self): post = Post() post.title = self.request.get('title_input') post.content = self.request.get('content') post.tags_commas = self.request.get('tags') user = users.get_current_user() post.author = user post.catalog = self.request.get('blogcatalog') private = self.request.get('private') if private: post.private = True; else: post.private = False; #try: #no need this ugly permalink now! # permalink = util.get_permalink(post.date,util.translate('zh-CN','en', util.u(post.title,'utf-8'))) # if not permalink: # raise Exception #except Exception: # self.response.out.write("transalte error in title %s = %s<br />\n" % (post.title,util.get_permalink(post.date,util.translate('zh-CN','en', util.u(post.title,'utf-8'))))) # return #check the permalink duplication problem. #maxpermalinkBlog = db.GqlQuery("select * from Post where permalink >= :1 and permalink < :2 order by permalink desc",permalink, permalink+u"\xEF\xBF\xBD").get() #if maxpermalinkBlog is not None: # permalink = maxpermalinkBlog.permalink+ post.date.strftime('-%Y-%m-%d') #post.permalink = permalink post.save() util.flushCategoryLists() util.flushArchiveLists() util.flushTagLists() util.flushPublicPosts() return self.redirect(post.full_permalink())
def pub(ctx,request:YuHeLg.Request): payload = request.json post = Post() try: post.title = payload.get("title") post.author_id = request.user.id post.postdate = datetime.datetime.now() cont = Content() cont.content = payload.get("content") post.content = cont tags = payload["tags"] except Exception as e: print(e) raise exc.HTTPBadRequest() taglist = re.split('[\s,]',tags) for tag in taglist: t = session.query(Tag).filter(Tag.tag == tag).first() if t is None: t = Tag() t.tag = tag session.add(t) pt = Post_tag() pt.tag = t pt.post = post session.add(pt) session.add(post) try: session.commit() return jsonify(post_id=post.id) except: session.rollback() raise exc.HTTPInternalServerError()
def load_posts(post_filename): """Load posts from u.post into database.""" for row in open(post_filename): row = row.rstrip() patient_id, time_stamp, meal_time, img_path, meal_setting, TEB, hunger, fullness, satisfaction = row.split( "|") if not hunger: hunger = None if not fullness: fullness = None if not satisfaction: satisfaction = None post = Post(patient_id=patient_id, time_stamp=time_stamp, meal_time=meal_time, img_path=img_path, meal_setting=meal_setting, TEB=TEB, hunger=hunger, fullness=fullness, satisfaction=satisfaction) db.session.add(post) db.session.commit()
def index(): form = PostForm() if current_user.can(Permission.WRITE_ARTICLES) and \ form.validate_on_submit(): post = Post(body=form.body.data, author=current_user._get_current_object()) db.session.add(post) return redirect(url_for('.index')) page = request.args.get('page', 1, type=int) show_followed = False if current_user.is_authenticated: show_followed = bool(request.cookies.get('show_followed', '')) if show_followed: query = current_user.followed_posts else: query = Post.query pagination = query.order_by(Post.timestamp.desc()).paginate( page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False) posts = pagination.items return render_template('index.html', form=form, posts=posts, show_followed=show_followed, pagination=pagination)
def new_post(): """ New post page """ user_id = login_session["user_id"] if request.method == "GET": return render_template("new_post.html", user=user_id, catalogs=CATALOGS) else: if ((not request.form["title"]) or (not request.form["body"]) or (not request.form["catalog"])): return render_template("new_post.html", catalogs=CATALOGS, error="missing") new_post = Post(title=request.form["title"], body=request.form["body"], catalog=request.form["catalog"], author=user_id) session.add(new_post) session.commit() post = session.query(Post).order_by(Post.create_at.desc()).first() return redirect(url_for("post_detail", post_id=post.id))
def posts(): current_user = request.user if request.method == "POST": title = request.form.get("posttitle") text = request.form.get("posttext") post = Post(title=title, text=text, user=current_user) db.session.add(post) db.session.commit() # send notification email msg = Message(subject="WebDev Blog - Posted a post", sender=SENDER, recipients=[current_user.email]) full_post_link = HOST_ADDR + url_for('blog.post', post_id=post.id) msg.body = f"Hi {current_user.username}!\n" \ f"There is news, check this out:{full_post_link}\n" \ f"Enjoy!" msg.html = render_template("new_post.html", username=current_user.username, link=f"{full_post_link}", post=post) mail.send(msg) return redirect(url_for('blog.posts')) if request.method == "GET": posts = Post.query.all() return render_template("posts.html", posts=posts, user=request.user, active1="active")
def load_posts(): """Load users from posts.txt into database.""" print("Posts") for i, row in enumerate(open("seed_data/posts.txt")): row = row.rstrip() post_id, account, shortcode, location_name, slug, lat, lng, viewport_ne_lat, viewport_ne_lng, viewport_sw_lat, viewport_sw_lng, formatted_address, maps_name, rating, place_id = row.split( "|") post = Post(post_id=post_id, account=account, shortcode=shortcode, location_name=location_name, slug=slug, lat=lat, lng=lng, viewport_ne_lat=viewport_ne_lat, viewport_ne_lng=viewport_ne_lng, viewport_sw_lat=viewport_sw_lat, viewport_sw_lng=viewport_sw_lng, formatted_address=formatted_address, maps_name=maps_name, rating=rating, place_id=place_id) db.session.add(post) # provide some sense of progress if i % 100 == 0: print(i) db.session.commit()
def post(self): form = PostForm() post = Post(body=form.body.data, user_id=current_user.id) db.session.add(post) db.session.commit() flash('Post was send!') return redirect(url_for('index'))
def insert_post(): """ Inserts post into databases. """ # File upload section file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) pdf_url = '{}{}'.format(UPLOAD_URL_PREFIX, filename) else: pdf_url = None # Post creation section title = request.form.get('title-input') cat_id = request.form.get('category') text = request.form.get('post-content') date = datetime.now() # Make post ID the datetime to ensure uniqueness post_id = '{:0>4}{:0>2}{:0>2}{:0>2}{:0>2}{:0>2}'.format(date.year, date.month, date.day, date.hour, date.minute, date.second) emp_id = session['emp_id'] post = Post(post_id=post_id, title=title, cat_id=cat_id, date=date, text=text, emp_id=emp_id, pdf_url=pdf_url) db.session.add(post) # Determine who sees this post. This is a list of stores. audience = request.form.getlist('audience') # Add each employee from audience to assigned_post table: for store in audience: # Sales associates (03-SS) are excluded from seeing posts unless # it is assigned to them. employees = Employee.query.filter(Employee.store_id == store, db.not_(Employee.pos_id.in_(['03-SS']))).all() # consolidate this, refactor to make more flexible for employee in employees: emp_assigned_post = AssignedPost(post_id=post_id, emp_id=employee.emp_id, was_read=False) db.session.add(emp_assigned_post) # Task section: if request.form.get('has_task'): for store in audience: desc = request.form.get('task_item') deadline = request.form.get('deadline') task = Task(post_id=post_id, store_id=store, desc=desc, assigned_date=date, deadline=deadline, is_complete=False) db.session.add(task) db.session.commit() flash("Post created.") return redirect('/')
def add_post(post, fix_photosets, blog_name="", offline_mode=False, monolithic=False): tag_list = [] for tag_element in post.find_all("tag"): this_tag = Tag(post_id=post["id"], tag=tag_element.text.strip()) tag_list.append(this_tag) base_post = Post( id=post["id"], # url=post["url"], # url_with_slug=post["url-with-slug"], # slug=post["slug"], type=post["type"], # state=post["state"], # date_gmt=post["date-gmt"], # date=post["date"], unix_timestamp=post["unix-timestamp"], # format=post["format"], # reblog_key=post["reblog-key"], is_reblog=post["is_reblog"], tumblelog=post["tumblelog"], tags=tag_list, # private=post.get("private", "false"), # width=int(post.get("width")) if post.get("width") else None, # width=post.get("width"), # height=post.get("height"), # direct_video=post.get("direct-video"), audio_plays=post.get("audio-plays")) if offline_mode: replace_links(post, blog_name, monolithic) specific_post = None if post["type"] == "regular": specific_post = make_regular(post) elif post["type"] == "photo": specific_post = make_photo(post, fix_photosets, blog_name) elif post["type"] == "link": specific_post = make_link(post) elif post["type"] == "answer": specific_post = make_answer(post) elif post["type"] == "quote": specific_post = make_quote(post) elif post["type"] == "conversation": specific_post = make_conversation(post) elif post["type"] == "video": specific_post = make_video(post) elif post["type"] == "audio": specific_post = make_audio(post) return base_post, specific_post
def make_post(user_name, text, image_url): session = session_factory() post = Post(user_name=user_name, text=text, image_url=image_url, claps_num=0) session.add(post) session.commit() return post
def post(self, subdomain, lense=None): if self.request.headers['Content-type'] == 'application/json': post = Post(**json.loads(self.request.body)) post.prefix = self.request.uri post.author = self.current_user post.save(db=self.db) self.set_header('Location', post.url) self.set_status(201) else: self.send_error(500)
def add_post(title,content,picture,username): add_post=Post( title=title, content=content, picture=picture, username=username ) session.add(add_post) session.commit()
def register_post(): from model import Post title = request.form.get('title') body = request.form.get('body') categoryid = request.form.get('categoryid') post = Post(title=title, body=body, category_id=categoryid) db.session.add(post) db.session.commit() return 'done'
def seed_posts(): for i in range(1, 35): fuser_id = randint(1,50) fdescription = fake.sentence() fzipcode = session.query(Zipcode).get(i) fzipcode = fzipcode.valid_zipcode fpost = Post(user_id=fuser_id, description=fdescription, zipcode=fzipcode) print("Commiting all new posts.") db.session.commit()
def write_post_perWindow(): mid,uid,forward_num,like_num,comment_num,time_window,content = yield print "write_post_perWindow received: \n"+mid+"\n"+uid+"\n"+forward_num+"\n"+like_num+"\n"+comment_num+"\n"+time_window+"\n"+content DBSession = sessionmaker(bind=engine) session = DBSession() content = content.encode("utf-8") new_post = Post(mid = mid,uid = uid,forward_number = forward_num,like_number = like_num,comment_number = comment_num,time_window = time_window,content = content) session.merge(new_post) session.commit() session.flush()
def add_child_post(post_id, page_num=1): """Uses POST request to create a new child (response) post within a forum (Tested)""" #Defining the central forums (within app context) to be rendered cam = Forum.query.filter_by(forum_id=1).one() dom = Forum.query.filter_by(forum_id=2).one() escort = Forum.query.filter_by(forum_id=3).one() p**n = Forum.query.filter_by(forum_id=4).one() dance = Forum.query.filter_by(forum_id=5).one() phone = Forum.query.filter_by(forum_id=6).one() sugar = Forum.query.filter_by(forum_id=7).one() other = Forum.query.filter_by(forum_id=8).one() #Creates lists for all of the children forums of the main 8 forums cam_query = Forum.query.filter_by(parent_forum_id=1).all() dom_query = Forum.query.filter_by(parent_forum_id=2).all() escort_query = Forum.query.filter_by(parent_forum_id=3).all() porn_query = Forum.query.filter_by(parent_forum_id=4).all() dance_query = Forum.query.filter_by(parent_forum_id=5).all() phone_query = Forum.query.filter_by(parent_forum_id=6).all() sugar_query = Forum.query.filter_by(parent_forum_id=7).all() other_query = Forum.query.filter_by(parent_forum_id=8).all() #Gets the new posts content post_content = request.form['child_content'] #Checks to see the users info and which posts they have flagged user = User.query.filter_by(email=session['current_user']).one() flag_query = Flag.query.filter(Flag.user_id == User.user_id).all() flags = [] if len(flag_query) > 0: for item in flag_query: flags.append(item.post_id) #Queries the data for the parent post parent_post = Post.query.filter_by(post_id=post_id).one() #Adds the new post to the database new_post = Post(user_id=user.user_id, username=user.username, forum_id=parent_post.forum_id, parent_post_id=post_id, content=post_content, p_datetime=datetime.now(), date_posted=(str(datetime.now())[:16])) #Doublechecks that the user isn't creating a duplicate post if Post.query.filter(Post.content == post_content, Post.username == user.username).all() == []: db.session.add(new_post) db.session.commit() #Redirects everything back to the same forum page return redirect("/forums/order_by_date/" + str(parent_post.forum_id) + "/" + str(page_num))
def new_post(community_name): ''' Create new post route. Allows users to create a new post in it's specific community. Registered user login required. ''' # Queries community = Community.query.filter_by(community_name=community_name).first() members_count = CommunityMembers.query.filter_by(community_id=community.id).count() form = PostForm() if form.validate_on_submit(): # If a picture is uploaded: if form.picture.data: picture_file = save_picture(form.picture.data) # Upload Picture to Cloudinary cloudinary_response = cloudinary.uploader.upload("./static/images/" + picture_file) # Performing debug print statement to see options: # print(dir(cloudinary_response)) # Create picture's cloudinary url # Cloudinary_response.public_id example to get items cloudinary_url = cloudinary_prefix + str(cloudinary_response['version']) + "/" + str(cloudinary_response['public_id']) + "." + str(cloudinary_response['format']) post = Post(user_id=current_user.id, community_id=community.id, title=form.title.data, body=form.content.data, image_url=picture_file, cloud_version=cloudinary_response['version'], cloud_public_id=cloudinary_response['public_id'], cloud_format= cloudinary_response['format'], cloudinary_url=cloudinary_url) db.session.add(post) db.session.commit() flash('Your post has been created!', 'success') # How to route user back to the community's page efficiently? return redirect('/k/'+community_name) else: post = Post(user_id=current_user.id, community_id=community.id, title=form.title.data, body=form.content.data) db.session.add(post) db.session.commit() flash('Your post has been created!', 'success') return redirect('/k/'+community_name) return render_template('create_post.html', form=form, community=community, legend='New Post', members_count=members_count)
def add_post(title, description, category, username, contact): session = session_factory() print("Added a post!") post = Post(title=title, description=description, category=category, username=username, contact=contact) session.add(post) session.commit()
def create_post(): user = SESSION.get(request.headers.get('Authorization')) if user is None: abort(400, {'message': 'TOKEN_NOT_FOUND'}) input_data = request.get_json() from model import Post post = Post() post.user_id = user.id post.content = input_data['content'] post.save() return jsonify(post.to_dict())