def create(): if request.method == 'POST': title = request.form['title'] body = request.form['body'] image_file = request.files['file'] error = None if not title: error = 'Title is required.' if error is not None: flash(error) if not image_file: flash("Please Attach a file") else: folder = f"user_{g.user.id}" # static/images try: image_path = image_helper.save_image(image_file, folder=folder) basename = image_helper.get_path(image_path) userModel = UserModel.find_user_by_id(g.user.id) post = PostModel(title=title, posts=body, image_url=image_path, user_id=userModel.id) post.save_to_db() except UploadNotAllowed: extension = image_helper.get_extension(image_file) flash("file with extension {} not allowed".format(extension)) return redirect(url_for('blog.index')) return render_template('blog/create.html')
def post(self): parser.add_argument( "title", help="Title can't be blank", required=True ) parser.add_argument( "content", help="Content can't be blank", required=True ) postData = parser.parse_args() new_post = PostModel( title=postData["title"], content=postData["content"] ) # new_post = PostModel(title="title", content="content") try: new_post.add_post() return {"message": "Create post sucessfully"} except Exception as e: print(e) return {"message": "Get error when create post"}
class DataBaseIntegrationTests: def setUp(self): if os.path.exists('./db/data.db'): # os.system('rm ../db/data.db') os.remove('./db/data.db') create_database('./db/data.db') def test_post_model_create(self): self.post_model = PostModel( 1, 'www.test_perfil.com', 'www.test_photo.com', '@Test', 1, 10, [ { "login": "******", "comment": "comment1" }, { "login": "******", "comment": "comment2" } ] ) self.assertIsNone(self.post_model.find_post(50)) self.assertIsNotNone(self.post_model.find_post(1)) def tearDown(self): # os.system('rm ./db/data.db') os.remove('./db/data.db')
def post(self): _id = get_jwt_identity() user = UserModel.find_by_id(_id) data = Post.parser.parse_args() data["date_created"] = datetime.date(datetime.now()) try: post = PostModel(**data) post.save_to_db() user.add_post(post) return {"msg" : "Post added"}, 200 except: return {"msg" : "error adding new post"}, 500
def create(): bucket = 'rosius' content_type = request.mimetype if request.method == 'POST': title = request.form['title'] body = request.form['body'] image_file = request.files['file'] client = boto3.client( 's3', region_name='us-east-2', endpoint_url='https://s3.us-east-2.amazonaws.com', aws_access_key_id=os.environ.get('AWS_ACCESS_KEY'), aws_secret_access_key=os.environ.get('AWS_SECRET_KEY')) error = None if not title: error = 'Title is required.' if error is not None: flash(error) if not image_file: flash("Please Attach a file") else: folder = f"user_{g.user.id}" # static/images try: if image_helper.is_filename_safe(image_file): client.put_object(Body=image_file, Bucket=bucket, Key=image_file.filename, ACL="public-read", ContentType=content_type) #image_path = image_helper.save_image(image_file,folder=folder) #basename = image_helper.get_path(image_path) print("https://rosius.s3.us-east-2.amazonaws.com/" + image_file.filename) userModel = UserModel.find_user_by_id(g.user.id) post = PostModel( title=title, posts=body, image_url="https://rosius.s3.us-east-2.amazonaws.com/" + image_file.filename, user_id=userModel.id) post.save_to_db() except UploadNotAllowed: extension = image_helper.get_extension(image_file) flash("file with extension {} not allowed".format(extension)) return redirect(url_for('blog.index')) return render_template('blog/create.html')
def post(self): data = post_parser.parse_args() image_file = data['imageurl'] blob = BlobClient.from_connection_string( conn_str= "DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=image1689;AccountKey=LSKVztWeg3o9R4ufT6o9FtV4eW776/McWu+jaQWzjjrG4RnH8ztwyERNrVv8XIIHrdVnG4heorual1zOuVhjBg==", container_name="images", blob_name=str(uuid.uuid4().fields[-1])[:5] + ".jpg") blob.upload_blob(image_file) post = PostModel(data['content'], data['likes'], blob.url, data['pub_date'], data['feed_id'], data['user_id']) post.save_to_db() return {"message": "Image Post Created."}, 201
def post(self): # get the current user's id user_id = current_identity.id # get the post data data = AddPost.parser.parse_args() # Create a new post using the data and user_id post = PostModel(None, data['title'], data['body'], user_id, data['category_id']) # Try saving the post try: post.save_to_db() except: return {'success': False, 'message': 'Something went wrong'}, 500 return {'sucess': 'Created successfully'}, 201
def get(cls, uuid: str): post = PostModel.find_by_uuid(uuid) if not post: return {"message": "Project not found."}, 404 return post_schema.dump(post), 200
def put(self, id): # get the current user's id user_id = current_identity.id post = PostModel.find_by_id(id) print('here') if post is None: return { 'success': False, 'message': 'Post was not found' }, 404 # check if the current user is the owner of the post if post.user != user_id: return { 'success': False, 'message': 'Not Authorized to Edit this post' }, 401 data = Post.parser.parse_args() post.title = data['title'] post.body = data['body'] post.category_id = data['category_id'] # try to delete the post or 500 try: post.save_to_db() except: return {'message': 'Something went wrong'}, 500 return { 'success': True, 'message': 'Post was edited successfully.' }, 200
def post(self): data = Comment.parser.parse_args() if len(data['name']) > Configuration.MAX_COMMENT_NAME_SIZE: return { 'message': 'A comment\'s name length is more than {}'.format( Configuration.MAX_COMMENT_NAME_SIZE) } if len(data['email']) > Configuration.MAX_EMAIL_ADDRESS_SIZE: return { 'message': 'email\'s length is more than {}'.format( Configuration.MAX_EMAIL_ADDRESS_SIZE) } if not PM.find_by_id(data['post_id']): return { 'message': 'There is no such post: \'{}\''.format(data['post_id']) } post_id = data['post_id'] del data['post_id'] comment = CM(**data) comment.post_id = post_id try: comment.save_to_db() except SQLAlchemyError as e: err = str(e.__class__.__name__) return {'message': '{}'.format(err)}, 500 return comment.get_json(), 201
def put(cls, post_id): post_data = post_schema.load(request.get_json()) post = PostModel.find_by_id(id=post_id) if not post: return {'message': POST_NOT_FOUND}, 404 user_id = get_jwt_identity() if not post.verify_post_author(user_id): abort(403) post.title = post_data.title post.content = post_data.content # if image is updated must delete the prev one if post.image != post_data.image and post_data.image: folder = 'user_{}'.format(user_id) new_filename = post_data.image.split(f'user_{user_id}/')[-1] if post.image: existing_filename = post.image.split(f'user_{user_id}/')[-1] try: os.remove(get_path(filename=existing_filename, folder=folder)) post.image = post_data.image except FileNotFoundError: return {'message': IMAGE_NOT_FOUND.format(existing_filename)}, 404 else: post.image = post_data.image post.save_to_db() return ( '', 204, {'Location': url_for('resources.posts.post', post_id=post.id)} )
def delete(cls, name: str): post = PostModel.find_by_name(name) if post: post.delete_from_db() return {"message": gettext("post_deleted")}, 200 return {"message": gettext("post_not_found")}, 404
def increment_post_saved(postid): target_post = PostModel.find_by_id(postid) if target_post is None: return "Target post not found" target_post.saved += 1 target_post.save_to_db() return ""
def filter_by_writer_id(_id): if not _id: return "ID of the writer is needed", None if not UserModel.find_by_id(_id): return "A user with that id does not exist", None return "", PostModel.filter_by_writer_id(int(_id))
def delete(cls, post_id): post = PostModel.find_by_id(post_id) if post.user_id != current_user.id: return {'message': 'This Action is Unauthorized Bro'}, 401 post.delete_from_db() return {'message': 'Post Deleted'}
def post(self, login): user = UserModel.find_by_username(login) if user: no_of_posts=PostModel.count_posts(login) return {'posts_count': no_of_posts} else: return {"message": "User not found"}, 404
def post(self): data = PostRegister.parser.parse_args() tag_names = data['tags'] if tag_names: tags = get_tags(tag_names) else: tags = [] if len(data['title']) > Configuration.MAX_POST_TITLE_SIZE: return { 'message': 'A title\'s length is more than {}'.format( Configuration.MAX_POST_TITLE_SIZE) } category = data['category_id'] if category: if not CM.query.filter(CM.id == category).first(): return { 'message': 'There is no such category: \'{}\''.format(category) } comments_id = data['comments'] if comments_id: comments = get_comments(comments_id) else: comments = [] del data['tags'] del data['category_id'] del data['comments'] new_post = PostModel(**data) if tags: new_post = get_item_tags(tags, new_post) if comments: new_post = get_item_comments(comments, new_post) try: new_post.save_to_db() except SQLAlchemyError as e: err = str(e.__class__.__name__) return {'message': '{}'.format(err)}, 500 return new_post.get_json(), 201
def put(cls, post_id): data = post_parser.parse_args() post = PostModel.find_by_id(post_id) if post.user_id != current_user.id: return {'message': 'This Action is Unauthorized Bro'}, 401 post.content = data['content'] post.save_to_db() return post.json()
def put(self, name): data = Post.parser.parse_args() post = PostModel.find_by_title(name) if post is None: post = PostModel(data['title'], data['desc']) else: post.title = data['title'] post.desc = data['desc'] post.save_to_db() return post.json()
def setUp(self): self.post_model = PostModel( 1, 'www.test_perfil.com', 'www.test_photo.com', '@Test', 1, 10, [ { "login": "******", "comment": "comment1" }, { "login": "******", "comment": "comment2" } ] )
def get(self): login = get_jwt_identity() user = UserModel.find_by_username(login) if user: last_post = PostModel.get_last_post(login) return post_schema.dump(last_post) else: return {"message": "User not found"}, 404
def post(self): data = self.parser.parse_args() # Foreign key constraint category_exist = CategoryModel.query.get(data['category_id']) if category_exist is None: return {'message': 'Category with such id doesnt exist.'} new_post = PostModel(**data) try: db.session.add(new_post) db.session.commit() except exc.IntegrityError as e: return {"message": e.args[0]}, 500 except: return {"message": "Something went wrong"}, 500 return {'data': new_post.json()}
def get_posts(posts_id): posts = [] for _id in posts_id: post = PM.find_by_id(_id) if post: posts.append(post) else: return {'message': 'There is no such post: \'{}\''.format(_id)} return posts
def get(self, post_id): post_obejct = PostModel.find_post(post_id) if post_obejct: post = [p.json() for p in post_obejct] response = jsonify({'post': post}) response.headers.add('Access-Control-Allow-Origin', '*') return response else: return {'message': 'No post found!'}, 404
def get(self): posts_obj = PostModel.find_all_posts() if posts_obj: posts = [post.json() for post in posts_obj] response = jsonify({'post': posts}) response.headers.add('Access-Control-Allow-Origin', '*') return response else: return {'message': 'No posts found!'}, 404
def filter_by_most_saved(theme): """ checks if input is valid by alphabet or number, and not blank """ if not theme: return "Theme is needed", None theme_nospace = theme.replace(" ", "") if not theme_nospace.isalnum(): return "Theme should only be consisted of alphabets, numbers, and spaces", None return "", PostModel.filter_by_most_saved(theme)
def delete(self, id_post): post = PostModel.find_by_id(id_post) if not post: return {"message": "Post does not exist"}, 400 liked = LikeModel.find_by_id_post_and_user(id_post, current_identity.id) if liked: LikeModel.query.filter_by(id_post=id_post, id_user=current_identity.id).delete() db.session.commit() return {"message": "Post unliked"}, 201 return {"message": "Post not liked yet"}, 400
def delete(cls, uuid: str): post = PostModel.find_by_uuid(uuid) if not post: return {"message": "Post not found."}, 404 post.delete_from_db() return {"message": "Post deleted."}
def get_post(id, check_author=True): post = PostModel.find_by_id(id) if post is None: abort(404, "Post id {0} doesn't exist.".format(id)) if check_author and post.user_id != g.user.id: abort(403) return post
def create_post(theme, anonymity, writer_id, content): # check if that theme exists # check if that username exists # check if content is less than characters writer = UserModel.find_by_id(writer_id) if not ThemeModel.find_by_theme(theme): return "The post's theme doesn't exist.", None if not writer: return "The writer is not a user", None if len(content) > 150: return "The content is too long", None try: new_post = PostModel(theme, anonymity, writer_id, content) new_post.save_to_db() except: return "Error saving to db", None return ""