def cleanup(): global LAST_CLEANUP now = time.time() if not LAST_CLEANUP or (now - LAST_CLEANUP > app.config['CLEANUP_INTERVAL']): Post.disable_stale_posts() LAST_CLEANUP = now
def post_item(): if request.method == 'POST': init_data = request.get_json(silent=True) data = {'item': init_data.get('item'), 'rating': init_data.get( 'rating'),'headline': init_data.get('headline'), 'content': init_data.get('content'), 'username': init_data.get('username')} user = User.query.filter_by(username=data['username']).first() item = Item.query.filter_by(name=data['item']).first() post = Post(id=uuid.uuid4().hex, name=data['headline'], content=data['content'], rating=data['rating'], post_file={"urls":[1,2,3]}, post_user=data['username'], post_item=item.id) if item.rating['overall']<0: item.num_posts = 1 new_rating = {} for feature in item.rating: if feature in data['rating']: new_rating[feature] = data['rating'][feature] item.rating = new_rating else: item.num_posts += 1 new_rating = {} for feature in item.rating: if feature in data['rating']: new_rating[feature] = round((((item.rating[feature] * (item.num_posts -1)) + data['rating'][feature])/item.num_posts),2) item.rating = new_rating db.session.add(post) db.session.commit() return jsonify({'status':'200'})
def post_create_ajax(request): print 'in ajax view' print request.POST text = request.POST['data'] #print request.POST response = {'status' : 'E'} try: print 'got text %s' % text post = Post(data=text) post.save() print 'got here' response['status'] = 'S' print 'and here' except: pass json = simplejson.dumps(response) return HttpResponse(json, mimetype='application/json')
def test_follow_posts(self): # create four users u1 = User(username='******', email='*****@*****.**', password_hash="") u2 = User(username='******', email='*****@*****.**', password_hash="") u3 = User(username='******', email='*****@*****.**', password_hash="") u4 = User(username='******', email='*****@*****.**', password_hash="") db.session.add_all([u1, u2, u3, u4]) # create four posts now = datetime.utcnow() p1 = Post(body="post from john", author=u1, timestamp=now + timedelta(seconds=1)) p2 = Post(body="post from susan", author=u2, timestamp=now + timedelta(seconds=4)) p3 = Post(body="post from mary", author=u3, timestamp=now + timedelta(seconds=3)) p4 = Post(body="post from david", author=u4, timestamp=now + timedelta(seconds=2)) db.session.add_all([p1, p2, p3, p4]) db.session.commit() # setup the followers u1.follow(u2) # john follows susan u1.follow(u4) # john follows david u2.follow(u3) # susan follows mary u3.follow(u4) # mary follows david db.session.commit() # check the followed posts of each user f1 = u1.followed_posts().all() f2 = u2.followed_posts().all() f3 = u3.followed_posts().all() f4 = u4.followed_posts().all() self.assertEqual(f1, [p2, p4, p1]) self.assertEqual(f2, [p2, p3]) self.assertEqual(f3, [p3, p4]) self.assertEqual(f4, [p4])
def new_post(): form = PostForm() 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('Posted!', 'success') return redirect(url_for('main.home')) return render_template('new_post.html', title='New Post', form=form, legend='New Post')
def queue_one_news_post(post, source, quintile, db_session): added_new = False try: post_id = post['id_str'] if 'id_str' in post else str(post['id']) post_item = Post.query.filter_by(original_id=post_id, source=source).first() if not post_item: post_item = Post(post_id, source, post, True) db_session.add(post_item) added_new = True else: post_item.update_content(post, is_news=True) post_item.political_quintile = quintile db_session.commit() success = True tasks.analyze_post.delay(post_item.id) except: logger.error('An error adding post {}'.format(post['id'])) success = False return {'success': success, 'added_new': added_new}
def insertDummyPosts(userID): user = User.query.filter_by(id=userID).first() posts = Post.query.all() if not posts: post1 = Post(title='Post 1', body='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', dateCreated='2018-10-27', user=user, category='Nouvelles', image="/dist/images/post1.jpg") post2 = Post(title='Post 2', body='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', dateCreated='2018-10-28', user=user, category='Drole', image="/dist/images/post1.jpg") post3 = Post(title='Post 3', body='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', dateCreated='2018-10-29', user=user, category='Nouvelles', image="/dist/images/post1.jpg") post4 = Post(title='Post 4', body='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', dateCreated='2018-10-30', user=user, category='Nouvelles', image="/dist/images/post1.jpg") post5 = Post(title='Post 5', body='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', dateCreated='2018-10-31', user=user, category='Drole', image="/dist/images/post1.jpg") post6 = Post(title='Post 6', body='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', dateCreated='2018-11-01', user=user, category='Nouvelles', image="/dist/images/post1.jpg") post7 = Post(title='Post 7', body='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', dateCreated='2018-11-02', user=user, category='Nouvelles', image="/dist/images/post1.jpg") post8 = Post(title='Post 8', body='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', dateCreated='2018-11-03', user=user, category='Drole', image="/dist/images/post1.jpg") post9 = Post(title='Post 9', body='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', dateCreated='2018-11-04', user=user, category='Nouvelles', image="/dist/images/post1.jpg") db.session.add(post1) db.session.add(post2) db.session.add(post3) db.session.commit()
def post_form(request): print 'in post_form' if request.is_ajax(): print 'in post_form ajax' text = request.POST['data'] response = {'status' : 'E'} try: print 'got text %s' % text post = Post(data=text) post.save() print 'got here' response['status'] = 'S' print 'and here' except: pass json = simplejson.dumps(response) return HttpResponse(json, mimetype='application/json') pass print 'in post_form' return create_update.create_object( request, model=Post, post_save_redirect='/posts')
def new_post(): form = PostForm() if form.validate_on_submit(): if Post.query.filter_by(title=form.title.data).first(): flash('Пост с таким заголовком уже существует!', 'danger') else: post = Post(title=form.title.data, content=form.content.data, author=current_user) db.session.add(post) db.session.commit() flash('Ваш пост создан!', 'success') return redirect(url_for('home')) return render_template('new_post.html', title='Новый пост', form=form, legend='Новый пост')
def post(post: Post, thread: Thread, user: User): """ Post Object representation from Post Database Object. :param post: Post object :param thread: Thread parent object :param user: Requesting User object :return: Post Object JSON representation """ return { 'id': post.id, 'thread': post.thread, 'anon': not user.admin and post.anon, 'text': post.text, 'image': post.get_image(), 'op': post.op, 'reply': post.reply, 'author': post_author(post, user), 'delete': user.admin or post.author == user.id }
def new_post(): # Initialize form object form = PostForm() # Validate form POST if form.validate_on_submit(): # Store post data post = Post(title=form.title.data, content=form.content.data, author=current_user) # Add post to DB db.session.add(post) db.session.commit() # Feedback message to user flash('Your post has been created!', 'success') return redirect(url_for('main.home')) return render_template('create_post.html', title='New Post', form=form, legend='New Post')
def post_author(post: Post, thread: Thread, user=None): """ Post author JSON representation, from Post object. :param post: Post object :param thread: Thread parent object :param user: Requesting User object :return: Post author object JSON representation """ if user is None or user.id != post.author: user = User.query.get(post.author) if user is None: raise AssertionError('Author has to be present') elif post.anon: return {'gender': user.get_gender(), 'authid': post.get_authid(), 'chat': get_request(thread, user)} else: # TODO: implement chat requests return { 'nickname': user.nickname, 'university': University.query.get(user.university).name, 'gender': user.gender, 'chat': get_request(thread, user) }
def queue_additive_rule(rule_id, level): """Fetches posts for this rule to be analyzed. Only Facebook and Twitter are supported currently.""" max_posts = 3 if level is None: links = session.query(AdditiveRule).filter_by( id=rule_id).first().additive_links else: links = [ link for link in session.query(AdditiveRule).filter_by( id=rule_id).first().additive_links if link.level == level ] for link in links: if link.source == 'twitter': posts = get_tweets(max_posts, link) elif link.source == 'facebook': posts = get_facebook_posts(max_posts, link) for post in posts: post_id = post['id_str'] if 'id_str' in post else str(post['id']) post_item = session.query(Post).filter_by( original_id=post_id, source=link.source).first() if not post_item: post_item = Post(post_id, link.source, post) session.add(post_item) session.commit() tasks.analyze_post.delay(post_item.id) association = session.query(PostAdditiveRule).filter_by( rule_id=link.rule_id, post_id=post_item.id).first() if not association: association = PostAdditiveRule(link.rule_id, post_item.id, link.level) session.add(association) session.commit()
def index(): form = PostForm() if form.validate_on_submit(): post = Post(body=form.post.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post is now live!') return redirect( url_for('index') ) # redirect so that this is a GET request, avoids duplicate submit in browser page = request.args.get('page', 1, type=int) posts = Post.query.order_by(Post.timestamp.desc()).paginate( page, app.config['POSTS_PER_PAGE'], False) # query is actually only triggerd after the ALL()! next_url = url_for('index', page=posts.next_num) if posts.has_next else None prev_url = url_for('index', page=posts.prev_num) if posts.has_prev else None return render_template("index.html", title='Home Page', form=form, posts=posts.items, next_url=next_url, prev_url=prev_url)
def diaglogic(): chickenList = ["c**k", "hen", "chicken", "bird", "quail", "partridge", "pillow"] isCorrect = True # load a single image name = f'{len(Post.query.all())+1}.jpg' photo = request.files["photo"] photo.save(f'E:/fbiz/api/server/images/data/{name}') img = image.load_img(f'E:/fbiz/api/server/images/data/{name}', target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) # check prediction predRs = checkChicken.predict(x) predCheck = decode_predictions(predRs, top=3)[0] print(predCheck) check = False for i in predCheck: if i[1] in chickenList: check = True break if check == False: res = {"success": False, "mgs": "Vui lòng chụp ảnh rõ hơn hoặc gần đối tượng để có được kết quả chính xác. Xin cám ơn!"} return jsonify(res) new_image = load_image(f'E:/fbiz/api/server/images/data/{name}', 64) # check prediction pred = model.predict(new_image) print("Thong so cac benh:", pred) rs = max(pred[0]) if rs < 90: isCorrect = False pred = pred[0] pred = pred.tolist() idx = pred.index(rs) print("Ket qua tra ve:", idx) result = Sickness.query.filter_by(id=(idx + 1)).first() newPost = Post(int(idx+1), name, float(request.values["lng"]), float( request.values["lat"]), int(request.values["userId"])) userAddress = User.query.filter_by( id=int(request.values["userId"])).first().address department = Department.query.filter_by(name=userAddress).first() try: db.session.add(newPost) db.session.commit() except: return jsonify( success=False, error="cannot post" ) res = {"success": True, "sickness": result.name, "description": result.description, "solution": result.solution, "isCorrect": isCorrect, "Department": department.phonenumber} return jsonify(res)
def adminPosts(): if request.method == 'POST': data = request.get_json() # handles admin post search if data.get('searchPosts'): searchInput = data.get('searchPosts') pageRequested = data.get('pageRequested') perPage = data.get('perPage') posts = Post.query.filter(or_(Post.title.like('%' + searchInput + '%'), Post.body.like('%' + searchInput + '%'))).order_by(desc(Post.title)).paginate(pageRequested, perPage, error_out=True) if posts: return jsonifyPosts(posts) else: return false # handles admin getNextPage if data.get('getNextPage'): perPage = data.get('perPage') pageRequested = data.get('pageRequested') posts = Post.query.order_by(desc(Post.dateCreated)).paginate(pageRequested, perPage, error_out=True) return jsonifyPosts(posts) # handles create post if data.get('createPost'): postImage = data.get('postImage') postTitle = data.get('postTitle') postBody = data.get('postBody') postCategory = data.get('postCategory') postImage = data.get('postImage') postUser = data.get('postUser') dateCreated = datetime.datetime.today().strftime('%Y-%m-%d') user = User.query.filter_by(username=postUser).first() post = Post(title=postTitle, body=postBody, user=user, category=postCategory, image=postImage, dateCreated=dateCreated) db.session.add(post) db.session.commit() return json.dumps({"postCreated": True}) # handles update post if data.get('updatePost'): postID = data.get('postID') postTitle = data.get('postTitle') postBody = data.get('postBody') postImage = data.get('postImage') postCategory = data.get('postCategory') post = Post.query.filter_by(id=postID).first() # updates post post.title = postTitle post.body = postBody post.image = postImage post.category = postCategory db.session.commit() return json.dumps({'postUpdated': True}) # handles delete post if data.get('deletePost'): postID = data.get('postID') post = Post.query.filter_by(id=postID).first() db.session.delete(post) db.session.commit() return json.dumps({"postDeleted": True}) return redirect(url_for('admin'))
def create_post(): payload = request.json logger.debug('validating request body') # validate payload assert payload is not None, 'missing json body' for required_field in ['title', 'body', 'collaborators', 'explicit_tags']: ValidationError.raise_assert( bool=required_field in payload, msg='"{}" required'.format(required_field)) logger.debug('create Post object') # init Post object post = Post(title=payload['title'], body=encode_body(payload['body'])) logger.debug('process tags') # get implicit tags explicit_tag_names = map(clean_whitespace, payload['explicit_tags']) explicit_tag_names = map(lambda x: (x, True), explicit_tag_names) # compute implicit tags from title implicit_tag_names = map(clean_whitespace, title_tokenizer(post.title)) implicit_tag_names = map(lambda x: (x, False), implicit_tag_names) known_tags = set() logger.debug('get/create tag objects') for (tag_name, is_explicit) in chain(explicit_tag_names, implicit_tag_names): tag_key = tag_name.strip().lower() if tag_key in known_tags: continue known_tags.add(tag_key) tag = db.session.query(Tag).filter( db.func.lower(Tag.tag) == db.func.lower(tag_name)).first() # allow on-the-fly tag creation if tag is None: tag = Tag(tag=tag_name, has_explicit=is_explicit) db.session.add(tag) else: if is_explicit and tag.has_explicit == False: tag.has_explicit = True db.session.add(tag) post_tag = PostTag(is_explicit=is_explicit) post_tag.tag = tag post.post_tags.append(post_tag) # add collaborators # TODO: allow mixed types (users & teams) logger.debug('get collaborators') for user_id in payload['collaborators']: user = db.session.query(User).filter_by(id=user_id).first() QueryError.raise_assert(user is not None, 'user "{}" not found'.format(user_id)) post.collaborators.append(user) if g.current_user not in post.collaborators: post.collaborators.append(g.current_user) logger.debug('persist Post object to db') db.session.add(post) db.session.commit() logger.debug('created Post(id={})'.format(post.id)) output = { 'post_id': post.id, 'title': post.title, 'body': decode_body(post.body), 'created_date': post.created_date, 'modified_date': post.modified_date, 'explicit_tags': [], 'implicit_tags': [], 'collaborators': [user.id for user in post.collaborators], 'upvotes': [user.id for user in post.upvotes], } for post_tag in post.post_tags: if post_tag.is_explicit: output['explicit_tags'].append(post_tag.tag.tag) else: output['implicit_tags'].append(post_tag.tag.tag) return jsonify({'post': output}), 201