def get_postTag_by_post_id(postId): with sqlite3.connect("./rare.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() db_cursor.execute( """ SELECT pt.id, pt.post_id, pt.tag_id, t.name FROM post_tag pt JOIN tag t on t.id = pt.tag_id WHERE pt.post_id = ? """, (postId, )) postTags = [] dataset = db_cursor.fetchall() for row in dataset: postTag = PostTag(row['id'], row['post_id'], row['tag_id']) postTags.append(postTag.__dict__) tag = Tag(row['tag_id'], row['name']) postTag.tag = tag.__dict__ return json.dumps(postTags)
def get_single_post(id): with sqlite3.connect("./rare.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() # Use a ? parameter to inject a variable's value # into the SQL statement. db_cursor.execute( """ SELECT p.id, p.user_id, p.category_id, p.title, p.publication_date, p.image_url, p.content, p.approved FROM Posts p WHERE p.id = ? """, (id, )) # Load the single result into memory data = db_cursor.fetchone() # Create an animal instance from the current row post = Post(data['id'], data['user_id'], data['category_id'], data['title'], data['publication_date'], data['image_url'], data['content'], data['approved']) db_cursor.execute( """ SELECT pt.id, pt.tag_id, pt.post_id, t.id tagId, t.label FROM PostTags pt JOIN Tags t ON t.id = pt.tag_id WHERE pt.post_id = ? """, (id, )) post_tags = db_cursor.fetchall() postTags = [] for row in post_tags: post_tag = PostTag(row['id'], row['tag_id'], row['post_id']) tag = Tag(row['tag_id'], row['label']) post_tag.tag = tag.__dict__ postTags.append(post_tag.__dict__) post.postTags = postTags return json.dumps(post.__dict__)
def add_to_post_tags_table(object1, type1, query): """Add a row to the post_tags_table """ ids = request.form.getlist(query) for id in ids: tag_or_post_object = type1.query.get(id) if type1 == Post: tag_or_post_object.post_tag.append(PostTag(post_id=int(id), tag_id=object1.id)) else: tag_or_post_object.post_tag.append(PostTag(post_id=object1.id, tag_id=int(id))) db.session.commit()
def commit_post(id): title = request.form.get('title') content = request.form.get('content') post = Post.add_post(title, content, id) tags = Tag.get_tags() for tag in tags: if (request.form.get(tag.name, None) is not None): PostTag.add(post.id, tag.id) return redirect(f'/users/{id}')
def setup_db(): "Function for setting up database each time we run app.py" # Create all tables db.drop_all() db.create_all() # If table isn't empty, empty it User.query.delete() Post.query.delete() Tag.query.delete() PostTag.query.delete() # Add users graham = User(first_name="Graham", last_name="Trail") brit = User(first_name="Brit", last_name="Juravic") # Add posts post_1 = Post(title="First Post", content="This is our first post", user_id=1) post_2 = Post(title="Second Post", content="This is our second post", user_id=2) # Add tags tag_1 = Tag(name="tag1") tag_2 = Tag(name="tag2") # Add posts_tags post_tag_1 = PostTag(post_id=1, tag_id=1) post_tag_2 = PostTag(post_id=2, tag_id=2) post_tag_3 = PostTag(post_id=1, tag_id=2) post_tag_4 = PostTag(post_id=2, tag_id=1) # Add new objects to session, so they'll persist db.session.add(graham) db.session.add(brit) db.session.commit() db.session.add(post_1) db.session.add(post_2) db.session.commit() db.session.add(tag_1) db.session.add(tag_2) db.session.commit() db.session.add(post_tag_1) db.session.add(post_tag_2) db.session.add(post_tag_3) db.session.add(post_tag_4) # Commit--otherwise, this never gets saved! db.session.commit()
def post_new(user_id): """Submit post request on form submit to add blog to db""" user = User.query.get(user_id) # get post details from form title = request.form["title"] body = request.form["body"] # get tags the user checked tags = Tag.query.all() tag_ids = [] for tag in tags: if request.form.get(tag.name, None): tag_ids.append(tag.id) # create post and add to db post = Post(title=title, body=body, user_id=user_id) db.session.add(post) db.session.commit() # add tags to post for tag_id in tag_ids: post_tag = PostTag(post_id=post.id, tag_id=tag_id) db.session.add(post_tag) db.session.commit() return redirect(f"/users/{user_id}")
def add_post_to_user(id): title = request.form['post-title'] content = request.form['post-content'] created_at = datetime.datetime.now() post = Post(title=title, content=content, created_at=created_at, user_id=id) add_and_commit(post) curr_post = Post.query.filter(Post.created_at == created_at) #Add tags all_tags = db.session.query(Tag.tag_name).all() all_tags_list = [v for v, in all_tags] for tag in all_tags_list: try: new_tag = request.form[tag] tag_used = Tag.query.filter(Tag.tag_name == new_tag).all() link_tag = PostTag(post_id=curr_post[0].id, tag_id=tag_used[0].id) add_and_commit(link_tag) except: pass return redirect(f'/user-details/{id}')
def commits_new_post(user_id): """pulls in client info, creates a new post in the database, displays all user posts on their details.html page""" user = User.query.get_or_404(user_id) title = request.form['title'] content = request.form['content'] left_blank = False if title == '': flash('Please enter a title to create a post!', 'error') left_blank = True if content == '': flash('Please enter content to create a post!', 'error') left_blank = True if left_blank: return render_template('create_new_user_post.html', user=user) else: new_post = Post(title=title, content=content, creator_id=user_id) db.session.add(new_post) db.session.commit() tag_ids = request.form.getlist("tag_list") for t_id in tag_ids: new_post_tag = PostTag(tag_id=t_id, post_id=new_post.id) db.session.add(new_post_tag) db.session.commit() return redirect(f'/users/{user_id}')
def create_post(username): """Create new post""" if session['username'] != username: flash("Invalid credentials", "danger") return redirect('/') form = PostForm() if form.validate_on_submit(): title = form.title.data content = form.content.data rating = form.rating.data user = User.query.get_or_404(username) post = Post(title=title, content=content, rating=rating, username=username) db.session.add(post) db.session.commit() tags = request.form.getlist('tag') for t in tags: tag = Tag.query.filter_by(name=t).first() pt = PostTag(post_id=post.id, tag_id=tag.id) db.session.add(pt) db.session.commit() flash('Post added', "success") return redirect(f"/users/{username}") tags = Tag.query.all() return render_template("new_post.html", tags=tags, form=form)
def create_post(userid): """Creates a new post for the specified user""" user = User.query.get_or_404(userid) title = request.form.get('title', None) content = request.form.get('content', None) tags = request.form.getlist('tags') # If information is somehow not provided, will show warnings to user missing_title = False missing_content = False if not title: missing_title = True if not content: missing_content = True if missing_title or missing_content: tags = Tag.query.all() return render_template('posts/new_post.html', user=user, missing_content=missing_content, missing_title=missing_title, tags=tags) new_post = Post(title=title, content=content, user_id=user.id) db.session.add(new_post) db.session.commit() for tag in tags: new_post_tag = PostTag(post_id=new_post.id, tag_id=int(tag)) db.session.add(new_post_tag) db.session.commit() return redirect(f'/users/{userid}')
def edit_post(post_id): post = Post.query.get_or_404(post_id) tags = Tag.query.all() tag_ids = post.tag_ids if request.method == 'POST': title = request.form.get('title') content = request.form.get('content') tags = request.form.getlist('tags') tag_list = [PostTag(post_id=post_id, tag_id=tag_id) for tag_id in tags] post.title = title post.content = content PostTag.query.filter_by(post_id=post_id).delete() db.session.commit() post.tags = tag_list db.session.commit() return redirect(f'/posts/{post_id}') else: return render_template('/posts/edit.html', post=post, tags=tags, tag_ids=tag_ids)
def create_post(id): user = User.query.get(id) tags = Tag.query.all() if request.method == 'GET': return render_template("postform.html", user=user, tags=tags) title = request.form['title'] content = request.form['content'] tagstrings = request.form.getlist('checkbox') x = datetime.now() new_post = Post(title=title, content=content, created_at=x, user_id=user.id) db.session.add(new_post) db.session.commit() post = Post.query.filter_by(title=title).first() for tagstring in tagstrings: for tag in tags: if tagstring == tag.name: new_TagPost = PostTag(tag_id=tag.id, post_id=post.id) db.session.add(new_TagPost) db.session.commit() return redirect(f"/users/{id}")
def new_post_view(user_id): """ GET: Display form for adding a new post. POST: Create new post and commit to db; redirect to user_detail_view if successful, else redirect to this page. """ if request.method == 'POST': title = request.form.get('title') content = request.form.get('content') tag_ids = request.form.getlist('tags') try: new_post = Post(title=title, content=content, user_id=user_id) new_post.posttags.extend([ PostTag(post_id=new_post.id, tag_id=tag_id) for tag_id in tag_ids ]) db.session.add(new_post) db.session.commit() flash('Success: post created!', 'success') except exc.SQLAlchemyError: flash('Failed to create post', 'danger') return redirect(url_for('new_post_view', user_id=user_id)) return redirect(url_for('user_detail_view', user_id=user_id)) return render_template('new_post.html', user_name=User.query.get_or_404(user_id).full_name, tags=Tag.query.order_by(Tag.name).all())
def create_post(id): """ verifies and adds post to database """ title = request.form.get("title") content = request.form.get("content") tags = request.form.getlist("tags") posttime = datetime.now() post = Post(title=title, content=content, created_at=posttime, creator_id=id) # tagsid = Tag.query.filter(tags.name != None) db.session.add(post) db.session.commit() import pdb pdb.set_trace() # raise for tag in tags: tagsid = Tag.query.filter(name == tag) posttag = PostTag(post_id=post.id, tag_id=tagsid) db.session.add(posttag) db.session.commit() return redirect(url_for("user_page", id=id))
def submit_add_post(user_id): """Show add post form""" action = request.form.get("add") tags = Tag.query.all() tag_list = [ tag.id if request.form.get(f"tag_{tag.id}") else False for tag in tags ] if action == "add": title = request.form["title"] content = request.form["content"] new_post = Post(title=title, content=content, user_id=user_id) print(new_post) sess.add(new_post) sess.commit() for tag in tag_list: if tag != False: new_post_tag = PostTag(post_id=new_post.id, tag_id=tag) sess.add(new_post_tag) sess.commit() return redirect(f"/users/{user_id}") else: return redirect(f"/users/{user_id}")
def submit_edit_post(post_id): """Submits edit user form and redirects back to users""" action = request.form.get("save") tags = Tag.query.all() tag_list = [ tag.id if request.form.get(f"tag_{tag.id}") else False for tag in tags ] if action == "save": edit_post = Post.query.get_or_404(post_id) edit_post.title = request.form["title"] edit_post.content = request.form["content"] tag_checked = [tag.id for tag in edit_post.tags] sess.add(edit_post) sess.commit() for tag in tag_list: if tag != False and tag not in tag_checked: new_post_tag = PostTag(post_id=post_id, tag_id=tag) sess.add(new_post_tag) sess.commit() return redirect(f"/posts/{post_id}") else: return redirect(f"/posts/{post_id}")
def commit_post_edit(u_id, p_id): """ Commits a post edit and redirects to that updated post page """ #Retrieve form data for Post title = request.form['title'] content = request.form['content'] created_at = get_date_time() #Retreive form data for tags tags = [int(i) for i in request.form.getlist('tag')] #Create new Post post = Post.query.get(p_id) post.title = title post.content = content post.created_at = created_at db.session.add(post) db.session.commit() #Get tag values associated with that post and delete the corresponding PostTags for tag in post.tags: PostTag_to_delete = PostTag.query.filter( PostTag.post_id == p_id, PostTag.tag_id == tag.id).first() db.session.delete(PostTag_to_delete) db.session.commit() #For each tag on the new Post, create an entry in PostTag table for tag in tags: PostTag_to_check = db.session.query new_post_tag = PostTag(post_id=p_id, tag_id=tag) db.session.add(new_post_tag) db.session.commit() return redirect(f'/users/{u_id}/posts/{p_id}')
def new_tag_view(): """ GET: Display form for adding a new tag. POST: Create new tag and commit to db; redirect to user_detail_view if successful, else redirect to this page. """ if request.method == 'POST': name = request.form.get('name') post_ids = request.form.getlist('posts') try: new_tag = Tag(name=name) new_tag.posttags.extend([ PostTag(post_id=post_id, tag_id=new_tag.id) for post_id in post_ids ]) db.session.add(new_tag) db.session.commit() flash('Success: tag created!', 'success') except exc.SQLAlchemyError: flash('Failed to create tag', 'danger') return redirect(url_for('new_tag_view')) return redirect(url_for('tags_view')) return render_template('new_tag.html', posts=Post.query.order_by(Post.title).all())
def setUp(self): """Clean up existing users""" User.query.delete() test_user = User( id=1, first_name='Harry', last_name='Potter', image_url= 'https://cdn.vox-cdn.com/thumbor/7n7Oe4myr7B7nYI-mxuuO3b-QrY=/150x0:1770x1215/1200x800/filters:focal(150x0:1770x1215)/cdn.vox-cdn.com/uploads/chorus_image/image/35330556/3176173-1748009911-hp.jp_.0.jpg' ) db.session.add(test_user) db.session.commit() self.test_user = test_user test_post = Post(title='Title', content='This is the content', creator_id=test_user.id) db.session.add(test_post) db.session.commit() self.test_post = test_post test_tag = Tag(name='neato cheeto!') db.session.add(test_tag) db.session.commit() self.test_tag = test_tag test_post_tag = PostTag(post_id=test_post.id, tag_id=test_tag.id) db.session.add(test_post_tag) db.session.commit() self.test_post_tag = test_post_tag
def setUp(self): """Add sample posts users tags posttags.""" PostTag.query.delete() Post.query.delete() User.query.delete() Tag.query.delete() u1 = User( first_name='Michael', last_name='Schienbein', image_url='https://files.catbox.moe/g1vsie.png') p1 = Post( title='Test Post One', content='This is a models unittest post', user=u1) t1 = Tag(name="Test1") t2 = Tag(name="Test2") db.session.add(u1) db.session.commit() db.session.add_all([p1, t1, t2]) db.session.commit() pt = PostTag(post_id=p1.id, tag_id=t1.id) db.session.add(pt) db.session.commit() self.user_id = u1.id self.post_id = p1.id self.tags_id = t1.id
def create_post(): """ Create a new post --- parameters: - in: "body" name: "body" description: "Create a new post" required: true schema: $ref: "#/definitions/CreatePostRequest" responses: 400: description: "Invalid input" 401: description: "Invalid token or API token not supplied" security: tokenauth: [] definitions: CreatePostRequest: type: "object" properties: subject: type: "string" content: type: "string" public: type: "boolean" tags: type: "[string]" securityDefinitions: tokenauth: type: apiKey in: header name: TIL-API-TOKEN """ post_data = request.json post = Post(subject=post_data.get('subject'), content=post_data.get('content'), author_id=flask.request.user_id, public=bool(post_data.get('public'))) db.session.add(post) db.session.commit() tags_list = post_data.get('tags') if tags_list: for tag in tags_list: tag = tag.strip() t = Tag.query.filter_by(tag=tag).first() if not t: t = Tag(tag=tag) db.session.add(t) db.session.commit() pt = PostTag(post_id=post.id, tag_id=t.id) db.session.add(pt) db.session.commit() # TODO: DB error handling return jsonify({'post_id': post.id})
def add_post(): """Add new post""" user = User.get_single_user(request.form["user"]) title = request.form["title"] content = request.form["content"] tags = request.form.getlist("tags") if (title == "" or content == ""): flash("Missing Input: Please fill out both Title and Content") return redirect(f"/create_post/{user.id}") post = Post(title=title, content=content, user_id=user.id) Post.add_post(post) for tag in tags: PostTag.add_post_tag(PostTag(post_id=post.id, tag_id=tag)) return redirect(f"/post_detail/{post.id}")
def edit_post(id): """Edit existing customer information in database""" title = request.form["title"] content = request.form["content"] tags = request.form.getlist("tags") if (title == "" or content == ""): flash("Missing Input: Please fill out both Title and Content") return redirect(url_for("edit_post_form", id=id)) post = Post.get_single_post(id) Post.update_post(post, [title, content]) PostTag.delete_post_tags(post.id) for tag in tags: PostTag.add_post_tag(PostTag(post_id=post.id, tag_id=tag)) return redirect(f"/post_detail/{id}")
def setUp(self): """Clear Database""" User.query.delete() Post.query.delete() Tag.query.delete() self.user = User(**USER_DATA) db.session.add(self.user) db.session.commit() self.post = Post(**POST_DATA, user_id=self.user.id) db.session.add(self.post) db.session.commit() self.tag = Tag(**TAG_DATA) db.session.add(self.tag) db.session.commit() PostTag.add_post_tag(PostTag(post_id=self.post.id, tag_id=self.tag.id))
def update_postag(post, tags): PostTag.query.filter(PostTag.post_id == post.id).delete() db.session.commit() for tag in tags: new_postag = PostTag(post_id=post.id, tag_id=tag.id) db.session.add(new_postag) try: db.session.commit() except Exception as error: msg = 'failed to update post' return render_template('error.html', msg=msg)
def seed(): db.drop_all() db.create_all() user1 = User( first_name="ash", last_name='g', profile_image_url= 'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg?crop=1.00xw:0.669xh;0,0.190xh&resize=640:*' ) user2 = User( first_name='tristo', last_name='brobo', profile_image_url= 'https://thezebra.org/wp-content/uploads/2020/07/Training-Time-Aug2020-GR-with-ball-scaled.jpg' ) db.session.add_all([user1, user2]) db.session.commit() post1 = Post(title="I want pizza", content="Pizza would be nice given I'm starving to death", posted_by=2) post2 = Post(title="Why is the weekend so suffocatingly, brutally short?", content="just wondering", posted_by=1) db.session.add_all([post1, post2]) db.session.commit() tag1 = Tag(name="food") tag2 = Tag(name="existential") db.session.add_all([tag1, tag2]) db.session.commit() posttag1 = PostTag(post_id=1, tag_id=1) posttag2 = PostTag(post_id=2, tag_id=2) db.session.add_all([posttag1, posttag2]) db.session.commit()
def create_postag(title, user_id, tags): post = Post.query.filter((Post.title == title) & (Post.user_id == user_id)).one() post_id = post.id for tag in tags: new_postag = PostTag(post_id=post_id, tag_id=tag.id) db.session.add(new_postag) try: db.session.commit() except Exception as error: msg = 'oh my god theres an error' return render_template('error.html', msg=msg)
def post_new_post(user_id=None, post_id=None): entry = User.query.get(user_id) if user_id else Post.query.get(post_id) if entry == None: return redirect("/users") # Validate arguments args = {} tags = [] for key, val in request.form.to_dict().items(): # Tag argument if key[0:4] == "tag-": tag = Tag.query.filter(Tag.name == key[4:]).first() if tag == None or val != "1": flash(f"Unknown argument: \"{key}\"") return redirect(request.url) else: tags.append(tag) # Normal argument else: if key not in post_mapper: flash(f"Unknown argument: \"{key}\"") return redirect(request.url) val = val.strip() args[key] = None if not val else val # Create/edit post post = Post(created_at=db.func.now(), user_id=user_id) if post_id == None else entry for key, val in args.items(): setattr(post, key, val) if user_id != None: db.session.add(post) # Delete tags for tag in post.tags: if tag not in tags: db.session.delete( PostTag.query.filter(PostTag.post_id == post_id, PostTag.tag_id == tag.id).first()) # Add tags for tag in tags: db.session.add(PostTag(post_id=post.id, tag_id=tag.id)) # Commit changes to DB try: db.session.commit() except: flash("Error: a title is required") return redirect(request.url) return redirect( f"/users/{user_id}" if user_id != None else f"/posts/{post_id}")
def main(sample_size, show_progress, *args, **kwargs): # Set up progress bar. if show_progress: progress_bar = ProgressBar(maxval=len(TAGS), widgets=[ 'Progress: ', Percentage(), ' ', Bar(marker=RotatingMarker()), ' ', ETA(), ' Fetched posts for ', Counter(), ' / ' + str(len(TAGS)) + ' tags.' ]) progress_bar.start() # Fetch statistics for posts related to each tag for tag_count, tag in enumerate(TAGS, start=1): # As it turns out, we can make the selection of random posts tractable if we # don't do a random ordering in SQL but instead do a random selection # in Python. So we start by fetching all of the post IDs for a tag, # make the random choice locally, and then query for the posts in this subset. post_id_tuples = ( PostTag.select() .join(Tag, on=(PostTag.tag_id == Tag.id)) .where(Tag.tag_name == tag) .select(PostTag.post_id) .tuples() ) # We convert this from a 2D Nx1 matrix to a 1D N-length matrix by taking its # transpose and then getting the "first row" of the transpose. post_ids = np.array(post_id_tuples).T[0] sample_post_ids = np.random.choice(post_ids, sample_size, replace=False).tolist() post_records = ( Post.select(Post.title, Post.creation_date, Post.answer_count, Post.comment_count, Post.favorite_count, Post.score, Post.view_count) .where(Post.id << sample_post_ids) .dicts() ) # Store which tag this record is associated with for record in post_records: record['tag_name'] = tag yield post_records if show_progress: progress_bar.update(tag_count) if show_progress: progress_bar.finish() raise StopIteration
def edit_post(post_id): """ Edits post with id post_id using info user submitted in the form type post_id: int rtype: str """ # get info submitted in form title = request.form["title"] content = request.form["content"] # verify the user entered both title and content if not title or not content: flash("Please fill out all fields", "danger") return redirect(f"/posts/{post_id}/edit") # edit post post = Post.query.get(post_id) post.title = title post.content = content db.session.add(post) db.session.commit() # update tags for post tags = Tag.query.all() post_tags = post.tags for tag in tags: # if checked and wasn't checked before, add tag to post if request.form.get(tag.name, None): tag_added = True for post_tag in post_tags: # if post already had tag, tag was not added if tag.id == post_tag.id: tag_added = False if tag_added: post_tag = PostTag(post_id=post.id, tag_id=tag.id) db.session.add(post_tag) # if not checked and was before, remove tag from post else: tag_removed = False for post_tag in post_tags: # if post used to have tag, tag was removed if tag.id == post_tag.id: tag_removed = True if tag_removed: post_tag = PostTag.query.filter_by(post_id=post.id, tag_id=tag.id).one() db.session.delete(post_tag) db.session.commit() flash("Post has been successfully updated", "success") return redirect(f"/posts/{post_id}")
def test_find_snippet_with_tags(self): # These two posts are equivalent, except that only is tagged with a tag that we # will use for filtering in the test. post1 = create_post(body=self._make_post_body('\n'.join([ 'import re', 'characters = re.findall(r"\w", "foo")', 'for c in characters:', ' print c', ]))) post2 = create_post(body=self._make_post_body('\n'.join([ 'import re', 'characters = re.findall(r"\w", "foo")', 'for c in characters:', ' print c', ]))) tag1 = create_tag(tag_name='javascript') tag2 = create_tag(tag_name='python') PostTag.create(post_id=post1.id, tag_id=tag1.id) PostTag.create(post_id=post2.id, tag_id=tag2.id) self._extract(['re.findall'], tags=['python']) self.assertEqual(PostSnippet.select().count(), 1) self.assertEqual(PostSnippet.select().first().post, post2)
def _create_post(self, body, tag_name='node.js'): post = create_post(body=self._make_post_body(body)) tag = create_tag(tag_name=tag_name) PostTag.create(post_id=post.id, tag_id=tag.id) return post