Esempio n. 1
0
	def get(self):
		settings = Settings.get() #Force email address update...
		posts = Post.query().order(-Post.date).fetch(1)
		is_newest = True
		if posts:
			post = posts[0]
			is_oldest = post.date == Post.min_date()
		else:
			post = None
			is_oldest = True


		#See if this is the very first time we've been here. In that case
		#send an email immediately to get people started...
		first_time = False
		
		if not Slug.query().get() and not Post.query().get():
			first_time = True
			DailyMail().send(True)

		self.response.write(get_template('frontpage.html').render(
			{
				"page":"frontpage", 
				"post":post, 
				"is_oldest" : is_oldest,
				"is_newest" : is_newest,
				"first_time" : first_time,
				"email" : settings.email_address
			}))
Esempio n. 2
0
    def post(self, authorized, fields):
        """
        Endpoint for creating new Posts
        """
        post = Post(**fields)

        # Fetch location name if not present and valid lat lon exists
        if post.location_lon is not None and post.location_lat is not None and post.location_name is None:
            post._fetch_friendly_location()

        # Save post
        result = _save_post(post, 201)

        # Check if the post was saved OK
        if result[1] != 201:
            return result

        # Tweet if public post
        if post.public:
            try:
                tweet = post_post_as_tweet(post)
            except Exception as e:
                return result

            post.tweet_id = tweet.id_str

            # Over-write result to new save of tweet_id
            result = _save_post(post, 201)

        return result
Esempio n. 3
0
 def new_post(self, title, content, date=datetime.datetime.utcnow()):
     post = Post(blog_id=self._id,
                 title=title,
                 content=content,
                 author=self.author,
                 created_date=date)
     post.save_to_mongo()
Esempio n. 4
0
	def get_old_post(self, today):
		#Lets try to put in an old post...
		old_post = None
		old_type = ''

		#First try a year ago...
		if today.day == 29 and today.month == 2:
			old_post = None
		else:
			year_ago = datetime.date(today.year-1, today.month, today.day)
			old_post = Post.query(Post.date == year_ago).get()
			old_type = 'year'

		if not old_post:
			#lets try a month ago...
			last_day_of_last_month = datetime.date(today.year, today.month, 1) + datetime.timedelta(days=-1)
			if last_day_of_last_month.day >= today.day:
				month_ago = datetime.date(last_day_of_last_month.year, last_day_of_last_month.month, today.day)
				old_post = Post.query(Post.date == month_ago).get()
				old_type = 'month'

		if not old_post:
			week_ago = today + datetime.timedelta(days=-7)
			old_post = Post.query(Post.date == week_ago).get()
			old_type = 'week'

		if not old_post:
			return None, None
		else:
			return old_post, old_type
Esempio n. 5
0
 def new_post(self, title, content, date=datetime.datetime.utcnow()):
     ''' create new post inside blog model'''
     post = Post(blogId=self._id,
                 title=title,
                 content=content,
                 createdDate=date,
                 author=self.author)
     post.save_to_mongo()
Esempio n. 6
0
 def post(self):
     title = self.get_argument("title", None)
     content = self.get_argument("content", None)
     #post = PostService.add(title, content)
     ps = Post()
     ps.title = title
     ps.content = content
     ps.save()
     self.write('good')
Esempio n. 7
0
	def new_post(self):
		title = input("Enter post title: ")
		content = input("Enter post content: ")
		post = Post(blog_id=self.id,
					title=title,
					content=content,
					author=self.author,
					date=datetime.datetime.utcnow())
		post.save_to_db()
Esempio n. 8
0
def create_test_anon_post(**kwargs):
    user = kwargs['user']
    group = kwargs['group']
    post = Post('content', 1)
    post.group_id = group.id
    post.user_id = user.id
    db.session.add(post)
    db.session.commit()
    return post
Esempio n. 9
0
 def new_post(self):
     title = input("Enter post title:")
     content = input("Enter content:")
     date = datetime.datetime.utcnow()
     post = Post(author=self.author,
                 blog_id=self.id,
                 content=content,
                 title=title,
                 created_date=date)
     post.save_to_mongo()
Esempio n. 10
0
    def get(self):
        burger_string = self.fetch_burger_string()

        if(burger_string != ''):
            post = Post(content=burger_string)
            post.put()
            logging.info("UpdateHandler::get() - Created new post with id: %s",
                post.key().id())
        else:
            logging.error('UpdateHandler::get() - fetch_burger_string()' +
                'returned an empty string, no post created')
Esempio n. 11
0
 def post(self):
     subject = self.request.get('subject')
     content = self.request.get('content')
     if subject and content:
         b = Post(parent=blog_key(), subject=subject, content=content,
                  author=self.user.name)
         b.put()
         self.redirect('/blog/%s' % str(b.key().id()))
     else:
         error = "We need both a subject and some content"
         self.render_front(subject, content, error)
Esempio n. 12
0
def create_new_post(blog_id):
	if request.method == 'GET':
		return render_template('new_post.html', blog_id=blog_id)
	else:
		title = request.form['title']
		content = request.form['content']
		user = User.get_by_email(session['email'])

		new_post = Post(blog_id, title, content, user.email)
		new_post.save_to_mongo()

		return make_response(blog_posts(blog_id))
Esempio n. 13
0
def create(parameters):
    parameters["body"] = parameters["body"].replace("\n", "<br>")
    user = current_user(parameters)
    if user:
        parameters.update({"author_id": user.id})
        new_post = Post(Post.cxn, "posts", parameters)
        new_post.save()
        parameters.update({"id": str(new_post.id)})
        return show(parameters)
    else:
        page = "<html><head></head><body><h2>{0}</h2>{1}</body></html>".format("You must be logged in to submit a new post", "<a href='/'><em>(home)</em></a>")
        return page
Esempio n. 14
0
def get_single_post(post_id=None, via_comment=None):
    if post_id is not None:
        post = Post.get_by_id(post_id)
    else:
        post_id = via_comment.post.id()
        post = Post.get_by_id(post_id)
    try:
        content = (post, map(lambda x: x.voter_id, post.voters))
    except AttributeError:
        abort(404)

    return content
    def post(self):
        subject = self.request.get('subject')
        content = self.request.get('content')

        if subject and content:
            post = Post(subject = subject, content = content)
            post.put()

            post_id = str(post.key().id())
            self.redirect('/%s' % post_id)
        else:
            error = 'You should write both subject and content.'
            self.render_form(subject, content, error)
Esempio n. 16
0
	def new_post(self):
		title = input("Enter post title: ")
		content = input("Enter post content: ")
		date = input("Enter post date, or leave blank for today (in format DDMMYYYY): ")
		if date == "":
			date = datetime.datetime.utcnow()
		else:
			date = datetime.datetime.strptime(date, "%d%m%Y")
		post = Post(blog_id=self.id,
					title=title,
					content=content,
					author=self.author,
					date=date)
		post.save_to_mongo()
Esempio n. 17
0
	def post(self):
		file_info = self.get_file_infos()[0]
		self.response.headers['Content-Type'] = "application/json"
		year = self.request.get('year')
		month = self.request.get('month')
		day = self.request.get('day')
		date = datetime.datetime(int(year), int(month), int(day))

		if file_info.content_type.lower() not in ('image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp'):
			return self.response.write(json.dumps({"status" : "error", "message" : "Unsupported content type: " + file_info.content_type}))

		bytes = filestore.read(file_info.gs_object_name)
		existing_images = [u.filename for u in UserImage.query(UserImage.date == date).fetch()]

		filename = UserImage.create_image_name(file_info.filename, date, existing_images)
		img = UserImage()
		img.import_image(filename, file_info.filename, bytes, date)
		img.put()
		filestore.delete(file_info.gs_object_name)
		#If there's a post here we should add the image...
		post = Post.query(Post.date == date).get()
		if post:
			post.has_images = True
			if post.images is None:
				post.images = []
			post.images.append(filename)
			post.put()

		self.response.write(json.dumps({"status" : "ok", "filename" : filename}))
Esempio n. 18
0
 def __init__(self, db, collection, obj):
     super(UserModel, self).__init__(db, collection, obj)
     self.username = obj['username']
     self.password = obj['password']
     self.voted = obj['voted']
     self.posts = Post()
     self.comments = Comment()
Esempio n. 19
0
def generate_posts_json(update = False):
    mc_key = "JSON_POSTS"
    news_dict, age = age_get(mc_key)
    if update or news_dict is None:     
        q = Post.all().order('-pubDate')       
        posts = list(q.fetch(limit=20))
        news_dict = dict()    
        for newstype in urllist:
            news_dict[newstype] = []            
        news_dict["carousel_posts"] = []        
        for p in posts:
            news_dict[p.newstype].append({
                    "TITLE":p.title,
                    "DESCRIPTION":p.description,
                    "PUBDATE":p.pubDate.isoformat(),
                    "LINK":p.link,
                    "IMAGE":p.image,
                    "SRC":p.src,
                    "NEWSTYPE":p.newstype #remove later
                    })
        carousel_posts = list(q.filter('srckey IN', [1, 6, 10]).fetch(limit=6))
        for p in carousel_posts:
            news_dict["carousel_posts"].append({
                    "TITLE":p.title,
                    "DESCRIPTION":p.description,
                    "PUBDATE":p.pubDate.strftime("%X, %x"),
                    "LINK":p.link,
                    "IMAGE":p.image,
                    "SRC":p.src,
                    "NEWSTYPE":p.newstype #remove later
                    })
        news_dict = json.dumps(news_dict)
        age_set(mc_key, news_dict)
        logging.info("DB QUERY!!")  
    return news_dict, age    
    def get(self, post_id):
        post = Post.get_by_id(int(post_id))

        if post:
            self.render('post.html', post = post)
        else:
            self.error(404)
Esempio n. 21
0
    def post(self):
        """Handles post request to store the blog post information into database"""
        title = self.request.get("subject")
        content = self.request.get("content")

        if self.authenticated():
            if title and content:
                a = Post(title = title, content = content, author = self.user)
                a.put()
                self.redirect("/blog/%s" % (a.key().id()))
            else:
                error = "Both title and art needed for submitting !"
                self.render("new.html",subject = title, content = content, error = error)
        else:
            # if the user is not autheticated it redirects to login page
            self.login_redirect()
Esempio n. 22
0
    def get(self):

        rss_items = []

        # fetch all posts from the db
        logging.info("FeedHandler::get() - Fetching posts from the db")
        q = Post.all()
        q.order("-created_at")
        results = q.fetch(20)

        for p in results:
            rss_items.append(
                PyRSS2Gen.RSSItem(
                    title = "Tasty Burger Friday",
                    link = "http://www.tasty-babelsberg.de",
                    description = p.content,
                    # guid = PyRSS2Gen.Guid('Guid{0}'.format(p.key().id())),
                    pubDate = p.created_at
                )
            )

        logging.info("Building the RSS")

        # build the rss
        rss = PyRSS2Gen.RSS2(
            title = "Tasty Burger Feed",
            link = "http://www.tasty-babelsberg.de",
            description = "Tasty Burger Friday",
            lastBuildDate = datetime.datetime.now(),

            items = rss_items
        )

        self.response.headers['Content-Type'] = 'application/rss+xml'
        self.response.out.write(rss.to_xml())
Esempio n. 23
0
def test_kind(db_conn, posts_table):
    """
    Expect a post to have a kind.
    """

    post = Post({
        'user_id': 'A',
        'topic_id': 'B',
        'body': 'C',
    })
    del post['kind']
    post, errors = post.save()
    assert len(errors) == 1
    post['kind'] = 'post'
    post, errors = post.save()
    assert len(errors) == 0
Esempio n. 24
0
    def post(self):
        key = 'front_page'
        time_key = 'front_queried'

        subject = self.request.get('subject')
        content = self.request.get('content')
        
        if subject and content:
            post = Post(subject=subject, content=content)
            post.put()
            post_id = post.key().id()
            update_front(key, time_key)
            self.redirect('/blog/post/%s' % post_id)
        else:
            error = "Need both subject and content"
            self.render('newpost.html', subject=subject, content=content, error=error)
Esempio n. 25
0
	def post(self, filename):
		self.response.headers['Content-Type'] = "application/json"
		img = UserImage.query(UserImage.filename == filename).get()
		if not img:
			return self.response.write(json.dumps({"status" : "error", "message" : "Image does not exit"}))

		post = Post.query(Post.date == img.date).get()
		
		#Remove it from the post
		if post:
			try:
				post.images.remove(filename)
			except:
				pass

			if len(post.images) == 0:
				post.has_images = False

			post.put()

		filestore.delete(img.serving_size_key)
		filestore.delete(img.original_size_key)
		img.key.delete()

		self.response.write(json.dumps({"status" : "ok"}))
Esempio n. 26
0
def index(parameters):
    template = open('./templates/posts/index.html').read()
    posts = Post.all(Post.cxn, "posts")
    post_template = open('./templates/posts/show.html').read()
    rendered_posts = "<br><br>".join([TemplateEngine(post_template, definitions(post, {"id": post.id, "comments_link": '<p><a href="/posts/{0}#comments">{1} comments</a></p>'.format(post.id, len(post.comments(globals())))})).render_partial() for post in posts])
    index_definitions = {"number_of_pages": str(parameters["number_of_pages"]), "rendered_posts": rendered_posts}
    index_definitions["login_status_message"] = login_status_message(parameters)
    return TemplateEngine(template, index_definitions).render()
Esempio n. 27
0
    def post(self, thread_id):
        try:
            thread = Thread.query.filter_by(id=thread_id).one()
        except NoResultFound:
            abort(404)
        form = ThreadReplyForm()

        if form.validate():
            post = Post(form.content.data, thread, current_user.id)
            post.op = False

            db.session.add(post)
            db.session.commit()

            return redirect(url_for("forum.ThreadView:get_0", thread_id=thread_id, page=1))  # TODO: Redirect to last page of thread

        return render_template("forum_thread_reply.jinja2", form=form, thread=thread)
Esempio n. 28
0
	def add_posts_to_zip(self, export_task, archive, day_string):

		export_task.update('Fetching posts...', status='inprogress')

		posts = [p for p in Post.query().order(Post.date).fetch()]

		export_task.update('Got %s posts, adding to zip...' % len(posts))
		post_text = ''
		for p in Post.query().order(Post.date).fetch():
			post_text += p.date.strftime('%Y-%m-%d')
			post_text += '\r\n\r\n'
			post_text += p.text.replace('\r\n', '\n').replace('\n', '\r\n').rstrip()
			post_text += '\r\n\r\n'

		archive.writestr('/export_%s.txt' % day_string, post_text.encode('utf-8'))

		export_task.update('Added %s posts to zip...' % len(posts))
Esempio n. 29
0
    def get_context_data(self, *args):
        context = super(PostDetailHandler, self).get_context_data(*args)
        context.update({
            'post': Post.objects(slug=args[0], is_published=True).first(),
            'rst': rst.convert_to_html
        })

        return context
Esempio n. 30
0
def get(request):
    url = urlparse(request.url())
    request.put_page('sitemap.xml', {
        'site_link': url.scheme + '://' + url.netloc,
        'tags': TagPostR.count_tags_by_name().iterkeys(),
        'posts_id_time': Post.post_id_time(),
        'last_modified': datetime.now(),
    })
Esempio n. 31
0
	def get(self, kind, year, month, day):
		date = datetime.datetime(int(year),int(month),int(day)).date()
		
		post = Post.query(Post.date == date).get()
		if kind == 'write' and post:
			return self.redirect('/edit/%s' % date.strftime('%Y-%m-%d'))
		if kind == 'edit' and not post:
			return self.redirect('/write/%s' % date.strftime('%Y-%m-%d'))
		
		data = { 
			"date" : date,
			"text" : "",
			"page" : "write",
			"kind" : kind
		}
		if post:
			data["page"] = "edit"
			data["text"] = post.text
			data["images"] = post.images
		else:
			data["images"] = [u.filename for u in UserImage.query(UserImage.date == date).fetch()]

		self.response.write(get_template('edit.html').render(data))
Esempio n. 32
0
def test_replies(db_conn, posts_table):
    """
    Expect a proposal to allow a replies to id.
    """

    prev, errors = Post.insert(db_conn, {
        'user_id': 'A',
        'topic_id': 'B',
        'body': 'C',
    })
    proposal, errors = Proposal.insert(
        db_conn, {
            'user_id': 'A',
            'topic_id': 'B',
            'body': 'C',
            'entity_version': {
                'id': 'D',
                'kind': 'unit'
            },
            'name': 'E',
            'replies_to_id': prev['id'],
        })
    assert len(errors) == 0
Esempio n. 33
0
    def post(self, post_id):
        key = db.Key.from_path('Post', int(post_id))
        post = db.get(key)

        subject = self.request.get('subject')
        content = self.request.get('content')

        if self.user and self.user.key().id() == post.author_id:
            if subject and content:
                post.subject = subject
                post.content = content
                post.put()  # store in database
                self.redirect("/blog/posts/%s" % str(post.key().id()))
            else:
                error = 'A post needs both a subject line and content'
                self.render_form(subject=subject, content=content, error=error)
        elif self.user:
            message = "You can only edit your own posts."
            posts = Post.all().order('-created')
            self.render('posts/posts.html', posts=posts, message=message)
        else:
            error = "You need to be logged in to edit a post!"
            return self.render('sessions/login.html', error=error)
Esempio n. 34
0
def get_post_comments(post_id):
	try:
		# gets post by its id
		post = Post.get(Post.id == post_id, Post.soft_delete == False)

		# get all of the posts comment and order by the most recent
		posts_comments = Comment.select().where(Comment.post == post,
										        Comment.user == current_user.id).order_by(Comment.timestamp.desc())

		# converts all of the posts comment to a dictionary
		posts_comments_dict = [model_to_dict(comment) for comment in posts_comments]

		return jsonify(
			data=posts_comments_dict,
			status={'code': 200, 'message': 'successfully created comment.'}
		)

	# if the queried post doesnt exist
	except DoesNotExist:
		return jsonify(
			data={},
			status={'code': 404, 'message': 'Resource does not exist.'}
		)
    def exec(self, *args):
        if len(args) < 2:
            raise BadArgsException
        content = self.raw_command.strip()
        content = content[8:].strip()
        content = content[len(args[0]):].strip()

        try:
            p = Post.get('id', args[0])
        except ObjectNotExist:
            self.write('Post does not exist.')
            return

        uuid = 'comment-{}'.format(gen_uuid())
        username = User.get('id', p.author_id).username
        Comment.create(p, self.user, uuid)

        self.write(
            json.dumps({
                'username': username,
                'uuid': uuid,
                'content': content
            }))
Esempio n. 36
0
    def get(self, id=None):
        # Check user information before processing
        if current_user.role:
            if not current_user.name or not current_user.phone:
                return jsonify(
                    {'message': 'Name and phone number are required!'})
        else:
            if not current_user.name or not current_user.job:
                return jsonify(
                    {'message': 'Name and job information are required!'})

        if id is None:
            id = current_user.id

        posts = Post.query.filter_by(user_id=id)
        if not posts:
            abort(404)
        res = {}
        for post in posts:
            users = Post.get_user_liked(post.id)
            num_users = len(users)
            if num_users > 2:
                like = str(users[0]) + ', ' + str(users[1]) + ' and ' + (
                    num_users - 2) + ' other people liked this post'
            elif num_users == 2:
                like = str(users[0]) + ', ' + str(
                    users[1]) + ' liked this post'
            elif num_users == 1:
                like = str(users[0]) + ' liked this post'
            else:
                like = None
            res[post.id] = {
                'title': post.title,
                'content': post.content[:CONTENT_LENGTH],
                'like': like
            }
        return json.dumps(res)
Esempio n. 37
0
def profile(username=None):
    userInfo = {}
    if username and not checkForJunk(
            usrtext=username) and not (len(username) > 20):
        userInfo = User.findUser(username=username)
        if userInfo:
            userInfo = User.toClass(userInfo)
            user = User.findUser(username=username)
            # print('profilePicture: ',userInfo.profilePicture)
            if request.method == "POST":
                if current_user.is_authenticated:

                    cuser = User.findUser(userID=current_user.userID)

                    if request.form.get('follow'):
                        User.follow(cuser, user)
                        print('about to start following..')
                    elif request.form.get('unfollow'):
                        User.follow(cuser, user, unfollow=True)
                        print('about to start unfollowing..')
                    return redirect(f'/profile/{username}')
                else:
                    print('user is not authenticated')

            posts = Post.getPostsByUserID(userID=user.get('userID'), all=True)

            return render_template('profile.html',
                                   userInfo=userInfo,
                                   posts=posts)
        else:
            return redirect('/'), 404, {'Refresh': '1; url = /'}

    elif username is None and current_user.is_authenticated:
        return redirect(f'/profile/{current_user.username}')

    else:
        return redirect('/'), 404, {'Refresh': '1; url = /'}
    def post(self, post_id):
        username = self.get_username()
        post = Post.get_by_id(int(post_id))

        # If the user is the owner of the post, the post method from the form
        # will be to edit the post
        if username == post.username:
            subject = self.request.get('subject')
            content = self.request.get('content')

            ok_form = True

            if not subject:
                error = 'You must enter a subject'
                ok_form = False
            if not ok_form and not content:
                self.redirect('/%s' % post_id)
            if ok_form and not content:
                error = 'You must enter some content'
                ok_form = False

            if ok_form:
                post.subject = subject
                post.content = self.br_substitution(content)
                post.put()
                self.redirect('/')

            else:
                post.subject = '%s ' % subject
                post.content = '%s ' % self.br_substitution(content)

                self.render("post.html", post=post, error=error)

        # If the user is not the owner of the post, redirect them to /login
        else:
            self.redirect('/login')
Esempio n. 39
0
    def get(self):
        """Get logged in user posts from DB and render it.
        """
        per_page = 5
        page = self.request.get('page')

        if page:
            page = int(page)
        else:
            page = 1

        post_all = Post.all().order('-created')
        my_posts = post_all.filter('user ='******'main.html', posts=posts, page=page,
                    total_page=total_page)
Esempio n. 40
0
def create_like():
    try:
        # gets data from the client - contains a post id
        data = request.get_json()

        # tries to get the post by its id
        post_id = Post.get(Post.id == data['postId'])

        try:
            # checks if a like for that post and user already exists
            like = Like.get(Like.post == post_id, Like.user == current_user.id)

        # if the user has not already likes the post
        except DoesNotExist:

            # creates a new like for the post
            like = Like.create(post=post_id, user=current_user.id)

            # convert like to dictionary and remove both users password
            like_dict = model_to_dict(like)
            del like_dict['user']['password']
            del like_dict['post']['user']['password']

            return jsonify(data=like_dict,
                           status={
                               'code': 201,
                               'message': 'User successfully liked post.'
                           })

    # exception thrown if the post doesnt exist
    except DoesNotExist:
        return jsonify(data={},
                       status={
                           'code': 404,
                           'message': 'Failure to get resource.'
                       })
Esempio n. 41
0
    def put(self, id):
        title, body, userId = self.update_params()

        post = Post.query.filter(Post.id == id).first()
        if post is not None:
            if title:
                Post.query.filter_by(id=id).update({'title': title})

            if body:
                Post.query.filter_by(id=id).update({'body': body})

            if userId:
                Post.query.filter_by(id=id).update({'userId': userId})

            db.session.commit()
            post = Post.query.filter(Post.id == id).first()

            db.session.commit()
            post_json = Post.serialize(post)
            response = BasicSchema(result=post_json)
            return BasicResponseSchema().dump(response)
        else:
            raise BasicError(message='Post not found',
                             status=HTTPStatus.NOT_FOUND)
def profile_page(id):   
    #user profile page
    user = User.get_by_id(id)

    #followers = Followers.to_user_id == user.id
    followers = user.followers
    # User.select().join(Relationship, on=(User.id == Relationship.from_user_id)).where(Relationship.to_user_id == user.id)

    #following
    # approved must be true in order for the user to be following the person
    following = user.following
    # User.select().join(Relationship, on=(User.id == Relationship.to_user_id)).where(Relationship.from_user_id == user.id, Relationship.approved == True)

    # if user.is_private == False or if user in user.following:
    # else:
        
        # need to find if the relationship has been approved
        # need to find the relationship based on the user id
        # if Relationship.approved == True, then allow pepole to see this profile 

    #query for posts
    post_query = Post.select().where(Post.user_id == user.id).order_by(Post.updated_at.desc())

    return render_template('users/profile_page.html', user = user, followers = followers, following = following, post_query = post_query)
Esempio n. 43
0
def init_posts(discussion_id, user_bob_id, user_john_id, user_anna_id):
    return [
        Post(text='Post 1',
             discussion_id=discussion_id,
             creator_id=user_bob_id).persist(),
        Post(text='Post 2 -> reply to post 1',
             discussion_id=discussion_id,
             creator_id=user_john_id).persist(),
        Post(text='Post 3 -> Reply to post 1',
             discussion_id=discussion_id,
             creator_id=user_anna_id).persist(),
        Post(text='Post 4 -> Reply to post 2',
             discussion_id=discussion_id,
             creator_id=user_anna_id).persist(),
        Post(text='Post 5 -> Reply to post 4',
             discussion_id=discussion_id,
             creator_id=user_john_id).persist(),
        Post(text='Post 6 -> Reply to post 2',
             discussion_id=discussion_id,
             creator_id=user_john_id).persist(),
        Post(text='Post 7 to delete',
             discussion_id=discussion_id,
             creator_id=user_john_id).persist()
    ]
Esempio n. 44
0
def post_edit(post_id):
    # check if post exists
    try:
        post = Post(post_id, False)
    except:
        error_context = {
            'error_name': "404 Not Found",
            'error_info': "The post you tried to access does not exist"
        }
        return render_template('error.html', **error_context)

    # check if user is logged in
    if not check.logged_in():
        error_context = {
            'error_name': "Unauthorized",
            'error_info': "You must log in first"
        }
        return render_template('error.html', **error_context)

    # check if user is OP
    if not (post.user_id == session['user_id']):
        error_context = {
            'error_name': "Unauthorized",
            'error_info': "You are not the original poster"
        }
        return render_template('error.html', **error_context)

    # get POST input
    form = TextPostEditForm(content=post.content)
    if form.validate_on_submit():
        post.content = form.content.data
        post.content_html = md.render(form.content.data)
        post.save()

        flash("Post edited successfully")
        return redirect(url_for('post_pages.post_view', post_id=post_id))

    return render_template('post_text_edit.html',
                           form=form,
                           body=post.content,
                           name="Post")
Esempio n. 45
0
def new(post_id):
    post = Post.get_by_id(post_id)  #<object>
    client_token = gateway.client_token.generate()
    return render_template('endorsement/new.html',
                           post=post,
                           client_token=client_token)
Esempio n. 46
0
 def get_posts(self):
     return Post.from_blog(self._id)
Esempio n. 47
0
 def test_post_all(self):
     self.create_post('001', 'username')
     posts = Post.all()
     self.assertEquals(1, len(posts))
Esempio n. 48
0
 def test_post_instance(self):
     post = Post()
     self.assertIsNotNone(post)
Esempio n. 49
0
from models.post import Post
from database import Database

Database.initialize()

post1 = Post(title="Title Post 1",
             content="Content Post 1",
             author="Author Post1",
             id=1,
             blog_id=1)

post1.save_post()

print('First post {}'.format(Post.get_post(1)))

post2 = Post(title="Title Post 2",
             content="Content Post 2",
             author="Author Post2",
             id=2,
             blog_id=1)

post2.save_post()

for post in Post.get_blog_posts(1):
    print('Post in blog 1: author = {0}; title = {1}; date created  = {2}'.
          format(post.author, post.title,
                 post.time_created.strftime('%d %b %Y: %H:%M')))
Esempio n. 50
0
 def test_all_exception(self):
     Post.all()
     self.assertRaises(ApiException)
Esempio n. 51
0
 def test_post_all_empty(self):
     post = Post.all()
     self.assertEquals(0, len(post))
Esempio n. 52
0
import mlab
from models.user import User
from models.post import Post

mlab.connect()

# a_random_user = User.objects(username="******").first()
# if a_random_user is None:
#     print("User not found")
# else:
#     new_post = Post(title="HANGRY",
#                     content="HIC",
#                     owner=a_random_user)
#     new_post.save()
#     print("Done saving...")

# Post => Owner
# for post in Post.objects():
#     print("'" + post.title + "'", "by", post.owner.username)

# Owner => Post
user = User.objects(username="******").first()
print("Posts owned by" + " " + user.username)
posts = Post.objects(owner=user)
for post in posts:
    print(post.title)
Esempio n. 53
0
def getPageEditPost(idPost):
    if "type_account" not in session or session["type_account"] == "renter":
        time.sleep(10)
        return
    if Post().checkEditPost(idPost, session["username"]):
        return render_template("editPost.html")
Esempio n. 54
0
__author__ = "sandy"
# -*- coding: utf-8 -*-
from models.post import  Post
post1 = Post()df
Esempio n. 55
0
 def post(self):
     json = request.get_json(force=True)
     post = Post.from_json(json)
     post.save()
Esempio n. 56
0
 def test_post_last_differs(self):
     self.create_post('001', 'username')
     post1 = Post.last(self.busline_id)
     self.create_post('002', 'username2')
     post2 = Post.last(self.busline_id)
     self.assertNotEqual(post1.busline, post2.busline)
Esempio n. 57
0
async def handle_post_details(request):
    id = request.match_info['id']
    related = request.rel_url.query.get('related', False)

    connection_pool = request.app['pool']
    connection = connection_pool.getconn()
    cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

    cursor.execute(Post.query_get_post_details(id))
    post = cursor.fetchone()

    if not post:
        connection_pool.putconn(connection)
        return web.json_response(
            status=404, data={"message": "Can't find post by slug " + str(id)})

    result = {
        "author": post['nickname'],
        "created": post['post_created'].astimezone().isoformat(),
        "forum": post['forum'],
        "id": post['post_id'],
        "message": post['post_message'],
        "thread": post['thread_id'],
        "isEdited": post['is_edited'],
        "parent": post['parent'] if post['parent'] != int(id) else 0,
    }
    if not related:
        connection_pool.putconn(connection)
        return web.json_response(status=200, data={'post': result})
    else:
        user = False
        thread = False
        forum = False
        related = related.split(',')
        if 'user' in related:
            user = {
                "about": post['about'],
                "email": post['email'],
                "fullname": post['fullname'],
                "nickname": post['nickname'],
            }
        if 'thread' in related:
            thread = {
                "author": post['t_author'],
                "created": post['t_created'].astimezone().isoformat(),
                "id": post['t_id'],
                "message": post['t_message'],
                "slug": post['t_slug'],
                "forum": post['forum'],
                "title": post['t_title'],
                "votes": post['votes'],
            }
        if 'forum' in related:
            forum = {
                "posts": post['posts'],
                "slug": post['f_slug'],
                "threads": post['threads'],
                "title": post['f_title'],
                "user": post['f_nick'],
            }

        data = {'post': result}
        if user:
            data['author'] = user
        if thread:
            data['thread'] = thread
        if forum:
            data['forum'] = forum

        connection_pool.putconn(connection)
        return web.json_response(status=200, data=data)
Esempio n. 58
0
def show(username):
    posts = Post.select()
    user = User.get_or_none(User.username == username)
    return render_template('userprofile.html', user=user, posts=posts)
Esempio n. 59
0
 def get(self):
     p = Post.from_dict({'content':"test"})
     p.save()
     p._content = 'xxxxx'
     p.save()
Esempio n. 60
0
from models.post import Post
from database import Database

Database.initialize()

post = Post(blog_id='123',
            title = "Another great post",
            content = 'This is some sample content',
            author = 'Jose')

post.save_to_mongo()