def post(self): current_user = self.current_user title = self.request.get("title") text = self.request.get("content") if title and text: post = Post(author=current_user, title=title, content=text) post.put() self.redirect("/post/" + str(post.key().id())) else: error = "Title and Text must be provided to submit an article!" self.render("newpost.html", error=error)
def post(self): """ Removes a post entry if user is authenticated, if no redirects to login route :return: """ post_id = self.request.get('id') post = Post.get_by_id(post_id) if Post.is_post_owner(self.request.cookies.get('user_id'), post): post.key.delete() time.sleep(2) self.redirect('/main')
def create(text: str, tags: List[str], link_to_post: str, image: str, source_group: str): return Post(text=text, tags=tags, link_to_post=link_to_post, image=image, source_group=source_group)
def get(self): """ Redirect to main route id user is authenticated (sending posts and user login as parameters), if no redirects to login route :return: """ user_id = self.request.cookies.get('user_id') posts = Post.get_posts() for post in posts: post.owner = User.get_by_hash(user_id) post.is_author = \ post.author == self.request.cookies.get('user_desc') post.liked = self.request.cookies.get('user_desc') in post.likes comments = Comment.get_by_post_id(post.key.id()) for comment in comments: comment.is_author = \ comment.author == self.request.cookies.get('user_desc') post.comments = comments self.render('main.html', posts=posts, user=self.request.cookies.get('user_desc'))
def get_proyect_posts(self, site, page_number=1, page_size=10, sort=None, filter=None): ''' Obtiene posts de un proyecto en concreto. :param site: Es la ID del proyecto del que quiere obtenerse sus perfiles. :param page_number: Puede usarse para páginar los posts. Indicará que página de los posts queremos seleccionar. Por defecto se selecciona la primera página. :param page_size: Indica el tamaño de la página. Se devolverán a los sumo tantos posts como el tamaño de la página. :param sort: Indica el tipo de ordenación de los posts. Los posibles valores son: published_at, retweets_asc, retweets_desc, likes_asc, likes_desc Si no se especifica o se establece a None, el resultado no se ordena (Por defecto es None) :param filter: Es un parámetro adicional que determina el criterio de filtrado de los posts. :return: Devuelve un listado de Posts extraídos. ''' if not filter is None and not filter.can_be_applied_to('post'): raise ValueError('This filter cannot be applied on posts searches') data = self.request(endpoint=endpoints.get_proyect_posts, placeholders={'site': site}, params={ 'pageNumber': page_number, 'pageSize': page_size, 'sort': sort }, use_access_token=True, payload=filter) return Post.get_from_data(data)
def get(self): if Auth.is_logged_in(self.request): posts = Post.by_author(self.current_user) self.render("welcome.html", posts=posts) else: self.redirect("/login")
def get(self): """ Renders a new post page if user is authenticated, if no redirects to login route :return: """ if User.is_authenticated(self.request.cookies.get('user_id')): self.render('post.html', post=Post(title="", content="")) else: self.redirect('/login')
def post(self): if not Auth.is_logged_in(self.request): self.response.content_type = 'application/json' response_obj = { 'type': 'error', 'message': 'You must be logged in to comment on posts!' } self.response.write(json.encode(response_obj)) else: current_user = self.current_user post = Post.by_id(int(self.request.get("pid"))) text = self.request.get("text") comment_id = self.request.get("comment_id") if text: is_edit = False # if is a edit to comment if comment_id: comment = Comment.by_id(int(comment_id)) comment.text = text is_edit = True else: comment = Comment(author=current_user, post=post, text=text) comment.put() self.response.content_type = 'application/json' response_obj = { 'type': 'success', 'message': 'Comment created!', 'editing': is_edit, 'comment': { "id": comment.key().id(), "author": current_user.username, "text": text, "time": comment.created.strftime("%d. %B %Y") } } self.response.write(json.encode(response_obj)) else: self.response.content_type = 'application/json' response_obj = { 'type': 'error', 'message': 'Comment not created!' } self.response.write(json.encode(response_obj))
def get_post_meta(event, context): table = __get_table_client() company_id = event["pathParameters"]["company_id"] post_id = event["pathParameters"]["post_id"] created_at = event["queryStringParameters"]["created_at"] PK, SK = Post.keys_from_ids_and_date(company_id, post_id, created_at) print("Key: ", json.dumps({"PK": PK, "SK": SK}, indent=4)) try: data = table.get_item( Key={ "PK": PK, "SK": SK }, ProjectionExpression= "company_id, user_id, post_id, post_title, post_content, points_map, can_share_on, created_at, updated_at", ReturnConsumedCapacity="TOTAL", ) if not data.get("Item"): raise KeyError # response = table.get_item(Key={"PK":"COMPANY#8fd4728b-89b6-40aa-a57a-85a4672ec9a0", "SK":"#METADATA#8fd4728b-89b6-40aa-a57a-85a4672ec9a0"}, ReturnConsumedCapacity='TOTAL') except ClientError as e: print(e.response["Error"]["Message"]) return _response(500, {"status": "DynamoDB Client Error"}) except KeyError as e: print(e) return _response(404, {"status": "ITEM NOT FOUND"}) else: post = Post(data["Item"]) consumed_cap = data["ConsumedCapacity"] print("GetItem succeeded:") print(json.dumps(data, indent=4, cls=DecimalEncoder)) return _response(200, post.get_item())
def get(self, id): post = Post.get_by_id(int(id)) if post is not None: comments = Comment.by_post(post) if post: self.render("post.html", post=post, comments=comments) else: self.redirect("/not-found") else: self.redirect("/not-found")
def get_latest_group_post(self, group_id): response = self.__api.wall.get( owner_id=group_id, count=1, v='5.101' ) last_post = self.extract_last_post(response) if not last_post: return None return Post( last_post.get('id'), last_post.get('text') )
def get(self, post_id): current_user = self.current_user post = Post.by_id(int(post_id)) if post is not None: # verify if this post matches user logged in if post.author.key().id() == current_user.key().id(): post.delete() self.redirect("/") else: # redirect the user to the view self.redirect("/post/" + str(post.key().id())) else: self.redirect("/not-found")
def get(self, post_id): current_user = self.current_user post = Post.by_id(int(post_id)) # verify if post exists if post is not None: # verify if this post matches user logged in if post.author.key().id() == current_user.key().id(): self.render("editpost.html", post=post) else: # redirect the user to the view self.redirect("/post/" + str(post.key().id())) else: self.redirect("/not-found")
def post(self): if not Auth.is_logged_in(self.request): self.response.content_type = 'application/json' response_obj = { 'type': 'error', 'message': 'You must be logged in to like posts!' } self.response.write(json.encode(response_obj)) else: current_user = self.current_user post = Post.by_id(int(self.request.get("pid"))) # checks if user already liked this post, if returns > 0 user_liked = Like.check_user_liked(current_user, post) # checks if this post belongs to the current_user if post.author.key().id == current_user.key().id: self.response.content_type = 'application/json' response_obj = { 'type': 'error', 'message': 'You can`t like you own posts :(' } self.response.write(json.encode(response_obj)) else: if user_liked > 0: Like.unlike(current_user, post) self.response.content_type = 'application/json' response_obj = { 'type': 'success', 'message': 'Post unliked!', 'action': 'unlike' } self.response.write(json.encode(response_obj)) else: like = Like(author=current_user, post=post) like.put() self.response.content_type = 'application/json' response_obj = { 'type': 'success', 'message': 'Post liked!', 'action': 'like' } self.response.write(json.encode(response_obj))
def post(self): """ Creates a new comment in a post if user is authenticated, if no redirects to login route :return: """ post_id = self.request.get('id') comment = self.request.get('comment') user = User.get_by_hash(self.request.cookies.get('user_id')) post = Post.get_by_id(post_id) comment = Comment(author=user.user, post=post.key.id(), comment=comment, created=datetime.datetime.now(), last_modified=datetime.datetime.now()) comment.put() time.sleep(2) self.redirect('/main')
def post(self): """ Creates a post like or unlike if user is authenticated, if no redirects to login route :return: """ user_id = self.request.cookies.get('user_id') post_id = self.request.get('id_post') user = User.get_by_hash(user_id) post = Post.get_by_id(post_id) if self.like_parameters_are_valid(user, post_id, post): if self.can_like(user, post): post.likes.append(user.user) post.put() elif self.can_unlike(user, post): post.likes.remove(user.user) post.put() time.sleep(2) self.redirect('/main')
def post(self): subject = self.get_argument('subject').strip() subject_error = get_subject_error(subject) content = self.get_argument('content').strip() content_error = get_content_error(content) if subject_error or content_error: self.render( subject=subject, subject_error=subject_error, content=content, content_error=content_error ) else: blog_post = Post() blog_post.subject = subject blog_post.content = content blog_post.put() self.redirect('/{post_id}'.format(post_id=blog_post.key().id()))
def post(self): """ Creates or update a new post entry if user is authenticated, if no redirects to login route :return: """ user_id = self.request.cookies.get('user_id') post_id = self.request.get('id') title = self.request.get('title') content = self.request.get('content') if 'update' in self.request.POST: post = Post.get_by_id(post_id) if Post.is_post_owner(user_id, post): post.title = title post.content = content post.last_modified = datetime.datetime.now() post.put() time.sleep(2) elif 'create' in self.request.POST: title = self.request.get('title') content = self.request.get('content') user = User.get_by_hash(user_id) p = Post(author=user.user, title=title, content=content, created=datetime.datetime.now(), last_modified=datetime.datetime.now()) p.put() time.sleep(2) self.redirect('/main')
def get_posts(self): return Post.from_blog(self._id)
def get(self): posts = Post.gql("ORDER BY date DESC LIMIT 10") self.render(posts=posts)
def create_post(post_id: str, content: str, user: User, secret: bool): new_post = Post(post_id=post_id, owner=user, text=content, secret=secret) logger.logging(new_post) return new_post
def put_post_meta(event, context): # table = __get_table_client() # payload = json.loads(event["body"]) # ( # PK, # SK, # company_id, # user_id, # post_id, # post_title, # post_content, # can_share_on, # points_map, # created_at, # updated_at, # ) = _get_post_meta(payload) # print( # PK, # SK, # company_id, # user_id, # post_id, # post_title, # post_content, # can_share_on, # points_map, # created_at, # updated_at, # ) # import time # post_created_at = int(time.time()) # try: # table.update_item( # Key={"PK": PK, "SK": SK}, # UpdateExpression="SET #company_id = :company_id, #user_id = :user_id, #post_id = :post_id, #post_title = :post_title, #post_content = :post_content, #can_share_on = :can_share_on, #points_map = :points_map, #created_at = if_not_exists(#created_at, :created_at), #post_created_at = if_not_exists(#post_created_at, :post_created_at), #updated_at = :updated_at", # ExpressionAttributeNames={ # "#company_id": "company_id", # "#user_id": "user_id", # "#post_id": "post_id", # "#post_title": "post_title", # "#post_content": "post_content", # "#can_share_on": "can_share_on", # "#points_map": "points_map", # "#post_created_at": "post_created_at", # "#created_at": "created_at", # "#updated_at": "updated_at", # }, # ExpressionAttributeValues={ # ":company_id": company_id, # ":user_id": user_id, # ":post_id": post_id, # ":post_title": post_title, # ":post_content": post_content, # ":can_share_on": can_share_on, # ":points_map": points_map, # ":created_at": created_at, # ":updated_at": updated_at, # ":post_created_at": post_created_at, # }, # ReturnConsumedCapacity="TOTAL", # ) # payload["post_id"] = post_id # except ClientError as e: # print(e.response["Error"]["Message"]) # return _response(500, {"status": "DynamoDB Client Error"}) # except KeyError as e: # print(e) # return _response(404, {"status": "ITEM NOT FOUND"}) # else: # print("PutItem succeeded:") # print(json.dumps(payload, indent=4, cls=DecimalEncoder)) # if json.loads(event["body"]).get("post_id"): # return _response(200, payload) # return _response(201, payload) table = __get_table_client() company_id = event["pathParameters"]["company_id"] post_id = event["pathParameters"]["post_id"] created_at = event["queryStringParameters"]["created_at"] payload = json.loads(event["body"]) payload.update({ "company_id": company_id, "post_id": post_id, created_at: "created_at" }) post = Post(payload) table_record = post.get_record() # PK = table_record["PK"] # SK = table_record["SK"] try: response = table.put_item( ConditionExpression="attribute_exists(PK) and attribute_exists(SK)", Item=table_record, ReturnConsumedCapacity="TOTAL", ) except ClientError as e: if e.response["Error"]["Code"] == "ConditionalCheckFailedException": return _response(404, {"status": "ITEM NOT FOUND"}) print(e.response["Error"]["Message"]) return _response(500, {"status": "DynamoDB Client Error"}) else: print("PutItem succeeded:") print(json.dumps(table_record, indent=4, cls=DecimalEncoder)) # print("Item update response: ", response) # if not response.get("Attributes"): # return _response(404, {"status": "ITEM NOT FOUND"}) # item = UserMeta(response["Attributes"]).get_item() item = post.get_item() return _response(200, item)
from api import API from logger import Logger import logging from entities.post import Post if __name__ == '__main__': # La siguiente sentencia permite guardar los mensajes de depuración en un fichero log # externo. Logger().setLevel(logging.DEBUG) # Creamos el objeto API. Necesitamos el JWT para tener acceso. api = API(access_token='{your access token here}') posts = api.get_profile_posts( profile='46078800', # ID del perfil del cual queremos obtener sus posts page_number=1, page_size=5, sort='retweets_desc') # Imprimimos los mensajes de los posts. for post in posts: print(post.body) # Para obtener un listado con los campos disponibles (para el primer post)... if len(posts) > 0: print(list(posts[0].to_dict().keys())) # Para obtener un listado de los campos de la entidad Post (y metainformación de los mismos)... print(Post.get_fields())
def can_unlike(self, user, post): return not Post.is_post_owner(user.hash, post) \ and 'unlike' in self.request.POST \ and user.user in post.likes