def make_post(user_id): form = newPostForm() if request.method == "POST": db.session.commit(post) user = Users.query.filter_by(user_id=user.id).first() description = request.form['description'] photo = request.files['photo'] now = datetime.datetime.now() post_picture = secure_filename(photo.filename) post = Posts(userID = user, photo = post_picture, caption = description, created_on = now) db.session.add(post) db.session.commit(post) photo.save(os.path.join(filefolder, post_picture)) post_body = [{"message": "Successfully created a new post"}] return jsonify(result=post_body) elif request.method == "GET": user_posts = Users.query.filter_by(user_id=user_id).all() if not user: return jsonify({'message': "no user found"}) # output list to hold dictionary output = [] for user_post in user_posts: # create dictionary post_data = {} # add data from database to dictionary user_post['id'] = user_post.id user_post['userID'] = user_post.userID user_post['photo'] = user_post.photo user_post['caption'] = user_post.caption user_post['created_on'] = user_post.created_on output.append(post_data) return jsonify({'posts': output}) error_collection = form_errors(form) error = [{'errors': error_collection}] return jsonify(errors=error)
def add_post(user_id): form = PostForm() if request.method == "POST": if form.validate_on_submit(): userid = user_id caption = request.form['caption'] photo = request.files['postimage'] post_date = datetime.datetime.now() post_photo = secure_filename(photo.filename) post = Posts(user_id=userid, postimage=post_photo, caption=caption, created_on=post_date) db.session.add(post) db.session.commit() photo.save(os.path.join(filefolder, post_photo)) return jsonify({'message': "Successfully created a new post"}) elif request.method == "GET": user = Users.query.filter_by(id=user_id).first() if not user: return jsonify({'message': "no user found"}) user_posts = Posts.query.filter_by(user_id=user_id).all() userposts = [] for user_post in user_posts: post_data = { 'id': user_post.id, 'user_id': user_post.user_id, 'postimage': user_post.post_photo, 'caption': user_post.caption, 'created_on': user_post.post_date } userposts.append(post_data) return jsonify(data=userposts) error_msgs = form_errors(form) error = [{'errors': error_msgs}] return jsonify(errors=error)
def addtoblog(): if current_user.is_authenticated: if request.method == "POST": found_user = UserModel.query.filter_by( username=current_user.username).first() Entry = request.form["Entry"] current_date = str(get_date()) new_post = Posts(entry=Entry.strip(), date=current_date, owner=found_user) db.session.add(new_post) db.session.commit() return redirect('/blogs') return render_template('addtoblog.html') return render_template('home.html')
def posts(user_id): if request.method == 'GET': posts = Posts.query.filter_by(user_id = user_id).all() user = Users.query.filter_by(id=user_id).first() user_follower_count = len(Follows.query.filter_by(user_id=user.id).all()) response = {"status": "ok", "post_data":{"firstname":user.first_name, "lastname": user.last_name, "location": user.location, "joined_on": "Member since "+strf_time(user.joined_on, "%B %Y"), "bio": user.biography, "postCount": len(posts), "followers": user_follower_count, "profile_image": os.path.join(app.config['PROFILE_IMG_UPLOAD_FOLDER'],user.profile_photo), "posts":[]}} for post in posts: postObj = {"id":post.id, "user_id": post.user_id, "photo": os.path.join(app.config['POST_IMG_UPLOAD_FOLDER'], post.photo), "caption": post.caption, "created_on": post.created_on} response["post_data"]["posts"].append(postObj) return jsonify(response) if request.method == 'POST': form = PostF() if form.validate_on_submit(): u_id = form.user_id.data photo = form.photo.data captn = form.caption.data user = Users.query.filter_by(id=u_id).first() filename = user.username+secure_filename(photo.filename) create_date = str(datetime.date.today()) post = Posts(user_id=u_id,photo=filename,caption=captn ,created_on=create_date) photo.save(os.path.join("./app", app.config['POST_IMG_UPLOAD_FOLDER'],filename)) db.session.add(post) db.session.commit() return jsonify(status=201, message="Post Created") print form.errors.items() return jsonify(status=200, errors=form_errors(form))
def archive(cls, post): ''' Lazy moebooru archive function adds a post to our db and moves the image to our dump area. ''' if isinstance(post.get('tags'), list): post['tags'] = ' '.join(post.get('tags')) tags = '|{}|'.format(post.get('tags').replace(' ', '|')) local_path = '' archive_path = '' filename = '{}.{}'.format(post.get('md5'), post.get('file_ext')) local_path = 'gazer/static/temp/{}'.format(filename) archive_path = 'gazer/static/dump/{}/{}/{}'.format( post.get('md5')[:2], post.get('md5')[2:4], filename) dd_tags = ddInterface.evaluate(local_path) dd_tags = ddInterface.union(tags=post.get('tags'), dd_tags=dd_tags) new_post = Posts(filename='{}.{}'.format(post.get('md5'), post.get('file_ext')), id=post.get('id'), booru=cls.source, source=post.get('source'), score=post.get('score'), tags=tags, dd_tags=dd_tags, rating=post.get('rating'), status=post.get('status'), created_at=post.get('created_at'), creator_id=post.get('creator_id')) session.add(new_post) session.commit() os.makedirs(os.path.dirname(archive_path), exist_ok=True) shutil.copyfile(local_path, archive_path) return new_post.id
def get_posts_by_tags(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.content, pt.id as pt_id, pt.tag_id, pt.post_id FROM posts p JOIN posttags pt on pt.post_id = p.id JOIN tags t on t.id = pt.tag_id WHERE pt.tag_id = ? """, (id, )) posts = [] #convert rows into a python list dataset = db_cursor.fetchall() #Iterate through list of data returned for row in dataset: post = Posts(row["id"], row["user_id"], row["category_id"], row["title"], row["publication_date"], row["content"]) #add post to posts posts.append(post.__dict__) return json.dumps(posts)
def make_post(user_id): form = newPostForm() if request.method == "POST": if form.validate_on_submit(): user = Users.query.filter_by(user_id=user.id).first() description = request.form['description'] photo = request.files['photo'] now = datetime.datetime.now() post_picture = secure_filename(photo.filename) post = Posts(userID = user, photo = post_picture, caption = description, created_on = now) db.session.add(post) db.session.commit(post) photo.save(os.path.join(filefolder, post_picture)) post_body = [{"message": "Successfully created a new post"}] return jsonify(result=post_body) elif request.method == "GET":
def saveMedia(self, term): media_json = self.getJSON(term) if not media_json: logging.info("Saved 0 media") return 0 for media in media_json['data']: post = Posts() if not post.hasPost(int(media['id'].split('_')[0])): post.orig_post_id = int(media['id'].split('_')[0]) post.orig_user_id = int(media['user']['id']) post.date = int(media['created_time']) post.username = media['user']['username'] post.text = media['caption']['text'] post.image_small = media['images']['low_resolution']['url'] post.image_full = media['images']['standard_resolution']['url'] post.service = 'instagram' post.likes = None post.orig_url = media['link'] post.save()
def saveTweets(self, term): tweets = self.getTweetsJSON(term) return if not tweets: logging.info("Saved 0 tweets") return 0 for tweet in tweets['statuses']: # Discard retweets if tweet.has_key('retweeted_status'): continue post = Posts() if not post.hasPost(tweet['id']): post.orig_post_id = int(tweet['id']) post.orig_user_id = int(tweet['user']['id']) post.date = int( time.mktime( time.strptime(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y'))) post.username = tweet['user']['screen_name'] post.text = tweet['text'] post.image_small = [ tweet['entities']['media'][0]['media_url'] if 'media' in tweet['entities'] else '' ][0] post.image_full = [ tweet['entities']['media'][0]['media_url'] if 'media' in tweet['entities'] else '' ][0] post.service = 'twitter' post.likes = None post.orig_url = None post.save()
def load_data(subreddits, count): reddit = praw.Reddit('ClientSecrets') posts_query = reddit.subreddit(subreddits).top(limit=count, time_filter="week") posts = [{ "subreddit": post.subreddit_name_prefixed, "flair": post.link_flair_text, "author": '[deleted]' if post.author is None else post.author.name, "date": datetime.utcfromtimestamp(post.created_utc).isoformat(), "id": post.id, "title": post.title, "score": post.score, "commentCount": post.num_comments, "upvoteRatio": post.upvote_ratio } for post in tqdm(posts_query, desc="Querying Reddit API", total=count)] queried_at = datetime.utcnow() p = Posts(subreddits, date=queried_at, posts=posts) db_session.add(p) db_session.commit() print("Successfully loaded data")
def submit_post(user_id): """Submit post to database.""" title = request.form["title"] content = request.form["content"] added_tags = request.form.getlist("tags") tag_ids = [] for num in added_tags: if num != '': tag_ids.append(int(num)) tags = Tags.query.filter(Tags.id.in_(tag_ids)).all() user = Users.query.get_or_404(user_id) new_post = Posts(title=title, content=content, user_id=user_id) db.session.add(new_post) db.session.commit() post = Posts.query.get_or_404(new_post.id) for tag in tags: post_tag = PostTags(tag_id=tag.id, post_id=post.id) db.session.add(post_tag) db.session.commit() return redirect(f'/users/{user_id}')
def add_posts(current_user, user_id): """Used for adding posts to the users feed""" pform = UploadForm() if request.method == 'POST' and pform.validate_on_submit(): caption = pform.caption.data photo = pform.photo.data photoname = secure_filename(photo.filename) photo.save(os.path.join(app.config['UPLOAD_FOLDER'], photoname)) ctime = time.strftime("%d %b %Y") posit = randomnum('pid') if Posts.query.filter(Posts.postid == posit): posit = randomnum() upost = Posts(postid=int(posit), userid=current_user.userid, photo=photoname, caption=caption, date=ctime) db.session.add(upost) db.session.commit() return jsonify({'message': 'Post Added!'}) errors = form_errors(pform) return jsonify({'errors': errors})
pForm = NewPostForm() uFolder = app.config['UPLOAD_FOLDER'] myPost = Posts(myid, fil, caption, created) myid = int(user_id) if request.method == "POST" and pForm.validate_on_submit(): caption = request.form['caption'] pic = request.files['photo'] filename = secure_filename(pic.filename) pic.save(os.path.join(uFolder, filename)) now = datetime.datetime.now() created = "" + format_date_joined(now.year, now.month, now.day) myPost = Posts(myid, filename, caption, created) db.session.add(myPost) db.session.commit() info = {'message': 'Successfully created a new post'} return jsonify(info=info) else: errors = form_errors(pForm) return jsonify(errors=errors) # Registers new users #@app.route('/api/users/register', methods=['POST']) #def register():
db.create_all() # """Empty tables if they aren't already empty""" # Users.query.delete() # add dummy user data adam = Users( first_name='Adam', last_name='Levitz', image_url= 'https://cdn-04.independent.ie/regionals/newrossstandard/lifestyle/3f1d5/37048554.ece/AUTOCROP/w620/2018-06-26_wex_42023220_I1.JPG' ) richard = Users(first_name='Richard', last_name='Dowdy') adam_post = Posts(title="Adam Test 1", content="Test post 1 for Adam User.", user_id=1) richard_post = Posts(title="Richard Test 1", content="Test post 1 for Richard user.", user_id=2) #add new instances to the session db.session.add(adam) db.session.add(richard) db.session.add(adam_post) db.session.add(richard_post) #commit sessions db.session.commit()
def add_pet(): try: auth_token = request.headers.get('Authorization') firebase_uid = "" if auth_token: id_token = auth_token.split(" ")[1] decoded_token = auth.verify_id_token(id_token) firebase_uid = decoded_token['uid'] else: return "Auth invalid", 400 form = request.form.to_dict() # check required key req_fields = [ 'name', 'email', 'tel', 'social_account', 'post_type', 'pet_type', 'gender', 'topic', 'description', 'size', 'missing_found_date', 'breed', 'color', 'address', 'province' ] for key in form: if key in req_fields: req_fields.remove(key) else: return key + ' is not in the required field', 400 if len(req_fields) != 0: return 'Required fields is missing', 400 if (form['post_type'] not in ['Lost', 'Found']): return 'The request is invalid', 400 # pic upload pic = request.files['pic'] if not pic: return 'No picture uploaded.', 400 elif pic.content_type not in {'image/jpeg', 'image/png'}: return 'Only image file type is allow', 400 gcs = storage.Client() bucket = gcs.get_bucket(CLOUD_STORAGE_BUCKET) blob = bucket.blob(uuid.uuid4().hex) blob.upload_from_string( pic.read(), content_type=pic.content_type ) post = Posts( name=form['name'], email=form['email'], tel=form['tel'], social_account=form['social_account'], user_uid=firebase_uid, post_type=form['post_type'], pet_type=form['pet_type'], topic=form['topic'], is_found = False, pic_url=blob.public_url, description=form['description'], size=form['size'], gender=form['gender'], breed=form['breed'], color=form['color'], address=form['address'], province=form['province'], missing_found_date=datetime.strptime( form['missing_found_date'], '%d/%m/%Y') ) db.session.add(post) db.session.commit() return 'Post uploaded', 200 except Exception as e: logging.exception(e) return "Internal server error", 500
#coding=utf-8 from models import Posts,dbSession new = Posts.Posts("搞","萌") dbSession.add(new) dbSession.commit() dbSession.close()
def like(request): p=Posts(body=post_body,time=datetime.now(),user=user) p.save()
def posts(user_id): """Render the user's posts.""" myform = PostForm() cid = session['current_user'] if request.method == 'GET': user = Users.query.filter_by(id=cid).first() data = { 'id': user.id, 'username': user.username, 'firstname': user.firstname, 'lastname': user.lastname, 'location': user.location, 'profile_photo': '/static/uploads/' + user.profile_photo, 'biography': user.biography, 'joined': user.joined_on } posts = Posts.query.filter_by(user_id=cid).all() follows = Follows.query.filter_by(user_id=cid).all() following = Follows.query.filter_by(follower_id=session['userid'], user_id=uid).first() isfollowing = '' if following is None: isfollowing = 'No' else: isfollowing = 'Yes' return jsonify(user=cid, response=[{ 'posts': [postinfo(posts)], 'postamt': len(posts), 'follows': len(follows), 'data': data, 'following': isfollowing }]) elif request.method == 'POST' and myform.validate_on_submit(): user = Users.query.filter_by(id=user_id).first() photo = myform.photo.data caption = myform.caption.data user_id = user_id postid = random.getrandbits(16) filename = secure_filename(photo.filename) post = Posts(postid=postid, user_id=user_id, photo=filename, caption=caption, created_on=format_date_joined()) photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) db.session.add(post) db.session.commit() return jsonify({'message': 'Post successfully created'}) return jsonify({"message": "Bad Request"})
def fetch_everything_from_db(): return Posts(), Tags(), Categories()
def rebuild_index(): if users.is_current_user_admin(): delete_all_in_index() posts = Posts() posts.rebuild_index() return redirect(url_for('index'))
def answers(title): posts = Posts() current_post = posts.get_by_title(title) if request.method == 'GET': # all entitites return jsonify(current_post.strip_answers_jsoned()) elif request.method == 'POST': raw_post = request.get_json() p_answer = raw_post["p_answer"] is_correct = raw_post["is_correct"] if not session.get('posts'): session['posts'] = [] if title not in session.get('posts'): remaining_attempts = REMAINING_ATTEMPTS \ if len(current_post.answers) != 2 else 0 session['posts'].append(title) session[title] = remaining_attempts else: remaining_attempts = session.get(title) - 1 session[title] = remaining_attempts answers_form = AnswerRadioForm() answers_form.r_answers.data = p_answer answers_form.r_answers.choices = [(answer.p_answer, answer.p_answer) for answer in current_post.answers] if answers_form.validate_on_submit(): answers_stats = {} if remaining_attempts < 0: result = False alert_type = "warning" msg = "Sorry, no attempts left!" else: current_post.set_selected_answer(p_answer) if current_post.is_answer_correct(): result = True alert_type = "success" msg = "Great!" answers_stats = current_post.get_answers_statistics() elif remaining_attempts == 1: result = False alert_type = "danger" msg = "You have one last attempt!" elif remaining_attempts == 0: result = False alert_type = "warning" msg = "Sorry, no attempts left!" else: result = False alert_type = "warning" msg = 'Please try again, {} attempts remaining.'.format( remaining_attempts) return jsonify(result=result, msg=msg, remaining_attempts=remaining_attempts, answers_stats=answers_stats, alert_type=alert_type) else: return jsonify({})
from models import User, Posts, Tag, PostTag, db from app import app db.drop_all() db.create_all() u1 = User(first_name="Hunter", last_name="Piggot") u2 = User(first_name="Apollo", last_name="Piggot") u3 = User(first_name="Annie", last_name="Oakley") p1 = Posts(title="Test1", content="Hello World", created_at="10-26-2020", user_id=1) p2 = Posts(title="Test2", content="World Hello", created_at="10-25-2020", user_id=2) p3 = Posts(title="Test3", content="Test Commment", created_at="10-24-2020", user_id=3) t1 = Tag(name="funny") t2 = Tag(name="NFSW") t3 = Tag(name="serious") pt1 = PostTag(post_id=1, tag_id=1) pt2 = PostTag(post_id=2, tag_id=1) pt3 = PostTag(post_id=3, tag_id=1) pt4 = PostTag(post_id=1, tag_id=2)
def add_posts(user_id): pForm = NewPostForm() uFolder = app.config['UPLOAD_FOLDER'] myPost = Posts(myid, fil, caption, created)
from flask import Flask, render_template, jsonify, request from mysqlconnection import MySQLConnector from models import Posts app = Flask(__name__) mysql = MySQLConnector(app, 'real_notes') post = Posts(mysql, jsonify) @app.route('/') def index(): return render_template('index.html') @app.route('/posts/create', methods=['POST']) def create(): # this function should take the submitted form info and submits it to the database # 1. type text into form # see form on template # 2. submit text from form to /posts/create route # see line 16 on template # 3. extract data from form content = request.form['post_content'] print content # 4. run query to insert that data into database # see line 15 of models post.add_post_to_db(content)
def POST(self): data = web.input() data.username = session_data['user']['username'] post_model = Posts.Posts() post_model.insert_post(data) return 'success'
def get_single_user(id): #open connection with sqlite3.connect("./rare.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() #SQL query db_cursor.execute( """ SELECT u.id, u.first_name, u.last_name, u.email, u.username, u.password, u.is_staff, u.bio, u.created_on, u.active, p.id, p.user_id, p.category_id, p.title, p.publication_date, p.content, s.id, s.follower_id, s.author_id, s.created_on, s.ended_on, c.id, c.post_id, c.author_id, c.content, c.created_on FROM Users as u JOIN Posts p ON p.user_id = u.id JOIN Subscriptions s ON s.author_id = u.id JOIN Comments c ON c.author_id = u.id WHERE u.id = ? """, (id, )) #Load the single return data = db_cursor.fetchone() #create a user instance from current row user = Users(data['id'], data['first_name'], data['last_name'], data['email'], data['username'], data['password'], data['is_staff'], data['bio'], data['created_on'], data['active']) #created joined instances post = Posts(data['id'], data['user_id'], data['category_id'], data['title'], data['publication_date'], data['content']) comment = Comments(data['id'], data['id'], data['author_id'], data['content'], data['created_on']) subscription = Subscriptions(data['id'], data['follower_id'], data['author_id'], data['created_on'], data['ended_on']) # postReaction = PostReaction(data['postReaction_id'], data['postReaction_user_id'], data['postReaction_post_id'], data['postReaction_reaction_id']) #add the new dictionaries to user instance user.post = post.__dict__ user.comment = comment.__dict__ user.subscription = subscription.__dict__ # user.postReaction = postReaction.__dict__ #return the data return json.dumps(user.__dict__)
def GET(self): post_model = Posts.Posts() posts = post_model.get_all_posts() return render.home(posts)
def GET(self): # data = type('obj', (object,), {"username": "******", "password": "******"}) post_model = Posts.Posts() posts = post_model.get_all_posts() return render.Home(posts)
def post(self): if users.get_current_user(): error_str = "" #checking upload size upload_files = self.get_uploads('file') if upload_files.__sizeof__() > blobstore.MAX_BLOB_FETCH_SIZE: upload_files = None error_str = error_str + "<p>Picture size is too large.</p>" if upload_files: blob_info = upload_files[0] blob_key = blob_info.key() else: blob_key = None post_sub = self.request.get('subject') post_content = self.request.get('content') if self.request.get('video'): if MediaHelper().validate_vid_url(self.request.get('video')): vid_url = self.request.get('video') else: vid_url = None error_str = error_str + "<p>The youtube url you entered is invalid.</p>" else: vid_url = None date_str = self.request.get('date') #make datetime if not date_str == None: date = datetime.strptime(date_str, '%m/%d/%Y') time = datetime.time(datetime.now()) dt = datetime.combine(date, time) else: dt = None posttype = self.request.get('posttype') is_post = False post_stat = "" if str(posttype) == 'POST': post_stat = "Published" is_post = True else: post_stat = "Saved" #save/update post if not self.request.POST.get('id', None): post = Posts(title=post_sub, text=post_content, status=post_stat, video_url=vid_url, blob_key=blob_key, date=dt) #editing else: post = db.get(self.request.get('id')) post.title = post_sub post.text = post_content post.status = post_stat post.video_url = vid_url post.date = dt if blob_key and post.blob_key: if not post.blob_key == blob_key: blobstore.delete(post.blob_key.key()) post.blob_key = blob_key elif blob_key: post.blob_key = blob_key elif post.blob_key: blobstore.delete(post.blob_key.key()) if not self.setPageTags(post) and is_post: error_str = error_str + "<p>Select at least one publish area.</p>" #save is error if error_str: post.status = "Saved" post.put() if error_str: self.redirect('/post?post_id=' + str(post.key()) + "&error=" + error_str) elif is_post: self.redirect('/') else: self.redirect('/post?post_id=' + str(post.key())) else: message = "You must login to access this page".encode("utf8") self.redirect('/logout?message=' + message)