Exemple #1
0
    def __init__(self,title=None,body=None,date=None,category=None,posttags=None,id=None):

        Action.__init__(self)
        if id==None:
           
            self.title=title
            self.body=body
            self.date=date
            self.postcategory=category
            self.posttags=posttags
            
        elif title==None:
            self.obj =BlogPost.get_by_id(int(id))
            self.id = self.obj.key().id()
            self.post_tags_keys = self.obj.tags
            
        else:
            self.obj = BlogPost.get_by_id(int(id))
            self.id = self.obj.key().id()
            self.post_tags_keys = self.obj.tags
            self.title=title
            self.body=body
            self.date=date
            self.postcategory=category
            self.posttags=posttags
Exemple #2
0
  def test_subscribe(self):
    expected = {
      'hub.mode': 'subscribe',
      'hub.topic': 'fake feed url',
      'hub.callback': 'http://localhost/fake/notify/foo.com',
      'format': 'json',
      'retrieve': 'true',
      }
    item_a = {'permalinkUrl': 'A', 'content': 'a http://a.com a'}
    item_b = {'permalinkUrl': 'B', 'summary': 'b http://b.com b'}
    feed = {'items': [item_a, {}, item_b]}
    self.expect_requests_post(superfeedr.PUSH_API_URL, feed,
                              data=expected, auth=mox.IgnoreArg())

    post_a = BlogPost(id='A', source=self.source.key, feed_item=item_a,
                      unsent=['http://a.com/'])
    post_b = BlogPost(id='B', source=self.source.key, feed_item=item_b,
                      unsent=['http://b.com/'])
    self.expect_task('propagate-blogpost', key=post_a)
    self.expect_task('propagate-blogpost', key=post_b)
    self.mox.ReplayAll()

    with self.app.test_request_context():
      superfeedr.subscribe(self.source)
      self.assert_blogposts([post_a, post_b])
Exemple #3
0
    def test_subscribe(self):
        expected = {
            'hub.mode': 'subscribe',
            'hub.topic': 'fake feed url',
            'hub.callback': 'http://localhost/fake/notify/foo.com',
            'format': 'json',
            'retrieve': 'true',
        }
        item_a = {'permalinkUrl': 'A', 'content': 'a http://a.com a'}
        item_b = {'permalinkUrl': 'B', 'summary': 'b http://b.com b'}
        feed = json.dumps({'items': [item_a, {}, item_b]})
        self.expect_requests_post(superfeedr.PUSH_API_URL,
                                  feed,
                                  data=expected,
                                  auth=mox.IgnoreArg())
        self.mox.ReplayAll()

        superfeedr.subscribe(self.source, self.handler)
        self.assert_blogposts([
            BlogPost(id='A',
                     source=self.source.key,
                     feed_item=item_a,
                     unsent=['http://a.com/']),
            BlogPost(id='B',
                     source=self.source.key,
                     feed_item=item_b,
                     unsent=['http://b.com/']),
        ])
Exemple #4
0
 def post(self):
     title = self.request.get("title")
     slug = self.request.get("slug")
     text = self.request.get("text")
     if title and slug and text:
         BlogPost.create(title, slug, text)
     return self.redirect_to("main")
Exemple #5
0
def add_post(request):
    if request.method == 'POST':
        form = BlogPostForm(request.POST)

        if form.is_valid():
            new_post = BlogPost(
                title=form.cleaned_data['title'],
                content=form.cleaned_data['content'],
                published=True,
                author=request.user
            )

            new_post.save()

            return redirect('view_posts', post_id=new_post.id)
    else:
        form = BlogPostForm()

    return render(
        request,
        'add_post.html',
        {
            'form': form,
        }
    )
Exemple #6
0
    def get(self, slug):
        # query to pull blog entry where slug from input matches slug of entry
        post = BlogPost.select().where(BlogPost.slug == slug).get()

        # query to list all blog entries by created field
        posts = BlogPost.select().order_by(BlogPost.created.desc())

        self.render_template("post.html", {'post': post, 'posts': posts})
def add_post():
    title = request.form.get('title', None)
    content = request.form.get('content', None)
    if title and content:
         if len(str(title))==10 and len(str(content))==6:
             BlogPost.create(title, content)
             return redirect(url_for('all_posts'))
    return render_template('new_post.html', error='Username and Password are required')
Exemple #8
0
  def test_handle_feed_allows_bridgy_publish_links(self):
    item = {'permalinkUrl': 'A', 'content': 'a https://brid.gy/publish/twitter b'}
    self.expect_task('propagate-blogpost', key=BlogPost(id='A'))
    self.mox.ReplayAll()

    superfeedr.handle_feed({'items': [item]}, self.source)
    self.assert_equals(['https://brid.gy/publish/twitter'],
                       BlogPost.get_by_id('A').unsent)
Exemple #9
0
 def post(self, blog_id):
     blog = BlogPost.get_by_id(int(blog_id))
     title = self.request.get("title")
     slug = self.request.get("slug")
     text = self.request.get("text")
     if title and slug and text:
         blog = BlogPost.update(blog_post=blog, title=title, slug=slug, text=text)
     return self.redirect_to("blog-details", slug=blog.slug)
def create_blog_post(title, blurb, content):

    published = datetime.now() + timedelta(days=-random.randint(1, 50))
    p = BlogPost(title=title, blurb=blurb, content=content, published=published)
    p.put()

    for i in range(0, random.randint(0, 5)):
        random_comment(p)
Exemple #11
0
    def test_label(self):
        for feed_item in None, {}:
            bp = BlogPost(id='x', feed_item=feed_item)
            bp.put()
            self.assertEqual('BlogPost x [no url]', bp.label())

        bp = BlogPost(id='x', feed_item={'permalinkUrl': 'http://perma/link'})
        bp.put()
        self.assertEqual('BlogPost x http://perma/link', bp.label())
Exemple #12
0
def recover(request):
    xmldoc = dom.parse(dazhu.settings.BASE_DIR + '/backup.xml')
    itemlist = xmldoc.getElementsByTagName('blog')
    result = "over"
    tools.debug("start import")
    for item in itemlist:
        tempguid = item.attributes['guid'].value
        tools.debug("current guid is ", tempguid)
        try:
            tempblog = BlogPost.objects.get(guid=tempguid)
        except:
            tools.debug(tempguid, "tempguid is exist")
            result += tempguid + " imported <br>"
            tempblog = BlogPost()
            tempblog.guid = item.attributes["guid"].value
            tempblog.author = item.attributes["author"].value
            tools.debug("author ", tempblog.author)
            tempblog.title = item.attributes["title"].value
            tempblog.category = item.attributes["category"].value
            tempblog.timestamp = datetime.strptime(
                item.attributes["timestamp"].value, "%Y%m%d %H%M%S")

            bodynode = item.getElementsByTagName('value')[0]
            tempblog.body = bodynode.firstChild.nodeValue
            tools.debug("value ", tempblog.body)

            tempblog.save()

            attachments = item.getElementsByTagName('attachment')
            for atts in attachments:
                rndName = atts.attributes["rndName"].value
                sourceName = atts.attributes["sourceName"].value

                tempAttachment = attachment()
                tempAttachment.blog = tempblog
                tempAttachment.sourceName = sourceName
                tempAttachment.rndName = rndName
                tempAttachment.save()

            cmts = item.getElementsByTagName('comment')
            for cmt in cmts:
                author = cmt.attributes["author"].value
                body = cmt.attributes["body"].value
                timestamp = datetime.strptime(
                    cmt.attributes["timestamp"].value, "%Y%m%d %H%M%S")

                tempComment = Comment()
                tempComment.author = author
                tools.debug("commentUser ", author)
                tempComment.body = body
                tools.debug("message ", body)
                tempComment.blog = tempblog
                tempComment.timestamp = timestamp
                tools.debug("timestamp ", timestamp)
                tempComment.save()

    return HttpResponse(result)
Exemple #13
0
 def test_handle_feed_cleans_links(self):
   item = {
     'permalinkUrl': 'A',
     'id': 'A',
     'content': 'x <a href="http://abc?source=rss----12b80d28f892---4',
   }
   superfeedr.handle_feed(json.dumps({'items': [item]}), self.source)
   posts = list(BlogPost.query())
   self.assert_blogposts([BlogPost(id='A', source=self.source.key,
                                   feed_item=item, unsent=['http://abc'])])
 def test_handle_feed_unwraps_t_umblr_com_links(self):
   item = {
     'permalinkUrl': 'A',
     'id': 'A',
     'content': 'x <a href="http://t.umblr.com/redirect?z=http%3A%2F%2Fwrap%2Fped&amp;t=YmZkMzQy..."></a> y',
   }
   superfeedr.handle_feed(json.dumps({'items': [item]}), self.source)
   posts = list(BlogPost.query())
   self.assert_blogposts([BlogPost(id='A', source=self.source.key,
                                   feed_item=item, unsent=['http://wrap/ped'])])
    def post(self):
        form = BlogPostForm(self.request.POST)

        if form.validate():
            post = BlogPost(**form.data)
            post.save()
            self.redirect_to("admin-blog-post-edit-extra", post_id = post.key().id(), extra="saved")

        return {
            "admin_section": "admin-blog-posts-new",
            "form": form,
        }
Exemple #16
0
 def post(self):
     subject = self.request.get("subject")
     content = self.request.get("content")
     if subject and content:
         newpost = BlogPost(subject=subject, content=content)
         key = newpost.put()
         memcache.set("front_page", None)
         self.redirect("/unit3/blog/%s" % key.id())
     else:
         self.write(
             blog_post_form,
             {"subject": subject, "content": content, "error": "Both subject and content are required."},
         )
Exemple #17
0
    def add_post(self, title, content, author, tags=[], make_visible=True):
        '''
        Create a new blog post

        Parameters
        ----------
        title: str,
            Blog post title.
        content: str,
            Blog post content.
        author : Admin,
            Admin user who is authring the post.
        tags : list,
            A list of Tag objects, defaults to empty list.
        make_visible: Boolean,
            Whether to make the post visible to public (publish), defaults to True.

        Returns
        -------
        BlogPost
            The blog post object that is added.
        '''

        blog_post = BlogPost()
        blog_post.author = author
        blog_post.title = title
        blog_post.content = content
        blog_post.is_visible = make_visible
        blog_post.tags = tags
        blog_post.post_date = datetime.now()

        db_session.add(blog_post)
        db_session.commit()

        return blog_post
Exemple #18
0
    def get(self, post_id):
        if not self.user:
            return self.redirect('/login')

        comments = Comment.by_post(post_id)
        commenting = self.request.get("commenting")
        error = self.request.get("error")
        uid = self.get_user_id()
        blog_post = BlogPost.get_by_id(int(post_id))
        blog_post.like = 0
        like = Likes.get_like(post_id, uid)

        if like:
            blog_post.like = 1

        if blog_post:
            if commenting:
                self.render("permalink.html",
                            post=blog_post,
                            commenting=True,
                            comments=comments,
                            error=error)
            else:
                self.render("permalink.html",
                            post=blog_post,
                            comments=comments,
                            error=error)
        else:
            self.redirect('/blog')
Exemple #19
0
    def post(self, post_id):
        if not self.user:
            return self.redirect('/login')

        comment = self.request.get("content")
        blog_post = BlogPost.get_by_id(int(post_id))
        uid = self.get_user_id()

        if blog_post is not None:
            if not comment:
                error = "Error: Please enter a valid comment"
                self.redirect("/blog/" + post_id + "?error=" + error)

            elif self.request.get("new-comment"):
                self.add_comment(post_id, uid, comment)

            elif self.request.get("edit-comment"):
                self.edit_comment(post_id, comment,
                                  self.request.get("comment-key"))

            elif self.request.get("edit-post"):
                self.edit_post(post_id, blog_post, uid, comment,
                               self.request.get("subject"))

        else:
            self.redirect('/blog')
Exemple #20
0
 def get(self,page):
     posts = BlogPost.all().order('-pub_date').fetch(limit=10)
     self.templ_vals.update({
         'url':users.create_logout_url("/"),
         'posts':posts,
     })
     self.render_to_response('index.html',self.templ_vals)
Exemple #21
0
def get_post(id):
    if users.is_current_user_admin():
        asked_post = BlogPost.get(id)

        return jsonify(asked_post.to_json())  # dangerous
    else:
        return jsonify({})
Exemple #22
0
def edit_post(id):

    form = PostForm()
    if users.is_current_user_admin() and form.validate_on_submit():
        try:
            tags = Tags()

            categories = Categories()

            updating_post = BlogPost.get(int(id))

            title = request.json['title']
            body = request.json['body']
            raw_category = request.json['category']
            editing_tags = request.json['tags']
            raw_summary = request.json['summary']

            tags_keys = tags.update(editing_tags, updating_post)

            category_key = categories.update(raw_category,
                                             updating_post.category)

            updating_post.edit(title,
                               body,
                               datetime.now(),
                               tags_keys,
                               category_key,
                               raw_summary,
                               raw_answers=request.json['answers'])
        except AttributeError:
            abort(500)

        return jsonify(updating_post.to_json())  # dangerous
Exemple #23
0
def get_post(id):
    if users.is_current_user_admin():
        asked_post = BlogPost.get(id)

        return jsonify(asked_post.to_json())  # dangerous
    else:
        return jsonify({})
Exemple #24
0
def edit_post(id):

    form = PostForm()
    if users.is_current_user_admin() and form.validate_on_submit():

        tags = Tags()

        categories = Categories()

        updating_post = BlogPost.get(int(id))

        title = request.json['title']
        body = request.json['body']
        raw_category = request.json['category']
        editing_tags = request.json['tags']
        raw_summary = request.json['summary']

        tags_keys = tags.update(editing_tags, updating_post)

        category_key = categories.update(raw_category, updating_post.category)

        updating_post.edit(title, body, datetime.now(), tags_keys,
                           category_key, raw_summary, raw_answers=request.json['answers'])

        return jsonify(updating_post.to_json())  # dangerous
Exemple #25
0
def add_blog():

    if request.method == 'POST':
        blog_title = request.form['blog_title']
        blog_text = request.form['blog_text']
        title_error = ''
        text_error = ''
        if blog_title == "":
            title_error = "Please enter a title."
        if blog_text == "":
            text_error = "Please enter blog text."
        if not title_error and not text_error:
            owner = User.query.filter_by(username=session['username']).first()
            new_blog = BlogPost(blog_title, blog_text, owner)
            db.session.add(new_blog)
            db.session.commit()
            id_param = new_blog.id
            return redirect('/blog?id={0}'.format(id_param))

        else:
            return render_template('newpost.html',
                                   title_error=title_error,
                                   text_error=text_error,
                                   blog_text=blog_text,
                                   blog_title=blog_title)

    else:
        return render_template('newpost.html')
Exemple #26
0
  def test_subscribe(self):
    expected = {
      'hub.mode': 'subscribe',
      'hub.topic': 'fake feed url',
      'hub.callback': 'http://localhost/fake/notify/foo.com',
      'format': 'json',
      'retrieve': 'true',
      }
    item_a = {'permalinkUrl': 'A', 'content': 'a http://a.com a'}
    item_b = {'permalinkUrl': 'B', 'summary': 'b http://b.com b'}
    feed = json.dumps({'items': [item_a, {}, item_b]})
    self.expect_requests_post(superfeedr.PUSH_API_URL, feed,
                              data=expected, auth=mox.IgnoreArg())
    self.mox.ReplayAll()

    superfeedr.subscribe(self.source, self.handler)

    posts = list(BlogPost.query())
    self.assert_entities_equal(
      [BlogPost(id='A', source=self.source.key, feed_item=item_a,
                unsent=['http://a.com']),
       BlogPost(id='B', source=self.source.key, feed_item=item_b,
                unsent=['http://b.com']),
       ], posts,
      ignore=('created', 'updated'))

    tasks = self.taskqueue_stub.GetTasks('propagate-blogpost')
    self.assert_equals([{'key': posts[0].key.urlsafe()},
                        {'key': posts[1].key.urlsafe()}],
                       [testutil.get_task_params(t) for t in tasks])
Exemple #27
0
def validate_post_addition(post_json, requesting_user):
    required = ['title', 'subtitle', 'body']
    try:
        missing = [
            key for key in required if key not in list(post_json.keys())
        ]
    except (AttributeError, TypeError):
        return make_response(
            jsonify(
                response=
                f"You are missing the following keys: {', '.join(required)}"),
            400)
    if not missing:
        try:
            new_post = BlogPost(title=post_json['title'],
                                subtitle=post_json['subtitle'],
                                body=post_json['body'],
                                author=requesting_user,
                                img_url=post_json.get('img_url', ''),
                                date=generate_date())
        except KeyError:
            return make_response(jsonify(response="Malformed request."), 400)
        else:
            db.session.add(new_post)
            db.session.commit()
            log_api_post_addition(requesting_user=requesting_user,
                                  post=new_post)
            return make_response(jsonify(message="Post published."), 201)
    else:
        return make_response(
            jsonify(
                response=
                f"You are missing the following keys: {', '.join(missing)}"),
            400)
Exemple #28
0
    def _blog_fetch_callback(self, rpc):

        content = rpc.get_result().content
        d = feedparser.parse(StringIO(content))
        s = Signatures.get_single()
        signatures_and_times = dict(zip(s.hashes, s.times))
        posts = []

        tags_entity = Tags.get_single()
        tags = set(tags_entity.available)

        for entry in d['entries']:
            blog_post = BlogPost.blog_post_from_feed_entry(entry)
            signature_time = signatures_and_times.get(blog_post.signature)
            if signature_time:
                signature_time = datetime.datetime.fromtimestamp(signature_time).strftime('%m/%d/%Y %H:%M')
            posts.append((blog_post, signature_time))

            for tag in blog_post.tags:
                tags.add(tag.lower())

        template_values = {"posts":posts}

        tags_entity.available = list(tags)
        tags_entity.save()

        template = jinja_environment.get_template('moderate.html')
        self.response.out.write(template.render(template_values))
    def post(self, blog_id):
        user = self.validate_user()
        # redirect to login if cookie wrong
        if not user:
            return self.redirect("/blog/login")

        # retrieve blog post from db
        blog = BlogPost.get_by_id(int(blog_id))

        # delete and redirect to /blog
        if blog:
            # check if blog belongs to user
            if blog.user.username != user.username:
                return self.redirect("/blog/login")

            subject = blog.subject
            # delete associated comments
            comments = db.Query(Comment).filter('blog =', blog)
            db.delete(comments)
            # delete blog itself
            blog.delete()
            # render delete_success page
            self.render("delete_success.html", subject=subject, user=user)
        else:
            self.error_404("The requested blog URL was not found.")
Exemple #30
0
    def test_subscribe(self):
        expected = {
            "hub.mode": "subscribe",
            "hub.topic": "fake feed url",
            "hub.callback": "http://localhost/fake/notify/foo.com",
            "format": "json",
            "retrieve": "true",
        }
        item_a = {"permalinkUrl": "A", "content": "a http://a.com a"}
        item_b = {"permalinkUrl": "B", "summary": "b http://b.com b"}
        feed = json.dumps({"items": [item_a, {}, item_b]})
        self.expect_requests_post(superfeedr.PUSH_API_URL, feed, data=expected, auth=mox.IgnoreArg())
        self.mox.ReplayAll()

        superfeedr.subscribe(self.source, self.handler)

        posts = list(BlogPost.query())
        self.assert_entities_equal(
            [
                BlogPost(id="A", source=self.source.key, feed_item=item_a, unsent=["http://a.com"]),
                BlogPost(id="B", source=self.source.key, feed_item=item_b, unsent=["http://b.com"]),
            ],
            posts,
            ignore=("created", "updated"),
        )

        tasks = self.taskqueue_stub.GetTasks("propagate-blogpost")
        self.assert_equals(
            [{"key": posts[0].key.urlsafe()}, {"key": posts[1].key.urlsafe()}],
            [testutil.get_task_params(t) for t in tasks],
        )
Exemple #31
0
def add_post():
    # if not logged in, redirect

    if "username" not in session:
        return redirect("/login")
    
    if request.method == "POST":
        username = session["username"]
        title = request.form["title"]
        content = request.form["content"]

        if not title or not content:
            return redirect("/add-post")
        
        user = User.query.filter_by(username=username).first()

        new_post = BlogPost(title, content, user)
        db.session.add(new_post)
        db.session.commit()

        return render_template("single-post.html",
        post=new_post, user=user)


    return render_template("add-post.html")
  def assert_blogposts(self, expected):
    got = list(BlogPost.query())
    self.assert_entities_equal(expected, got, ignore=('created', 'updated'))

    tasks = self.taskqueue_stub.GetTasks('propagate-blogpost')
    self.assert_equals([{'key': post.key.urlsafe()} for post in expected],
                       [testutil.get_task_params(t) for t in tasks])
 def test_handle_feed(self):
   item_a = {'permalinkUrl': 'A',
             'content': 'a http://a.com http://foo.com/self/link b'}
   superfeedr.handle_feed(json.dumps({'items': [item_a]}), self.source)
   self.assert_blogposts(
     [BlogPost(id='A', source=self.source.key, feed_item=item_a,
               unsent=['http://a.com'])])  # self link should be discarded
Exemple #34
0
    def __init__(self):
        """load basic members using memcache"""
        logging.info("initialized")
        self.posts_tags_db=[]
        self.catdict={}
        self.posts_tags_dict={}
        self.posts=memcache.get(KEY)

      
        if self.posts is None:
            logging.info('cache is empty creating index')
            self.posts = BlogPost.all().order('-timestamp')
   
            createIndex(self.posts)
            memcache.add(KEY,self.posts)
        if isinstance(self.posts,list):self.nofposts=len(self.posts)-2
        else:self.nofposts=self.posts.count()-2
        self.tags=memcache.get(TAG)
        if self.tags is None:
            self.tags = Tag.all()
            memcache.add(TAG,self.tags)
        self.categories=memcache.get(CATEGORY)
        if self.categories is None:
            self.categories= Category.all()
            memcache.add(CATEGORY,self.categories)

        for post in self.posts:
            logging.info(['posts',post.title])
            self.posts_tags_db.extend(post.tags)
            tags=[]
            for key in post.tags:tags.append(db.get(key).tag)
            self.posts_tags_dict[post.key()]=tags
            self.catdict[post.category.key()]=post.category.category
        logging.info(['catdict',self.catdict])
        self.tagnames=list(chain.from_iterable(self.posts_tags_dict.values()))
    def get(self, post_id):
        post = BlogPost.get_by_id(long(post_id))

        return {
            "section": "blog",
            "post": post,
        }
Exemple #36
0
    def post(self, blog_id):
        subject = self.request.get("subject")
        content = self.request.get("content")

        # validate subject and content present
        if not (subject and content):
            error = "Please enter both subject and content."
            self.render("edit_page.html", error=error,
                        subject=subject, content=content)
        else:
            user = self.validate_user()
            # redirect to login if cookie wrong
            if not user:
                return self.redirect("/blog/login")

            # retrieve blog post from db and edit fields
            blog = BlogPost.get_by_id(int(blog_id))
            if blog:
                # check if blog belongs to user
                if blog.user.username != user.username:
                    return self.redirect("/blog/login")

                blog.subject = subject
                blog.content = content
                blog.put()
                self.redirect('/blog/' + blog_id)
            # 404 error if blog not found
            else:
                self.error_404("The requested blog URL was not found.")
Exemple #37
0
def your_posts():
    qry1 = BlogPost.query()  # Retrieve all Account entitites
    list_to_return = []

    for item in qry1:
        body = item.body
        author = item.author
        title = item.title
        the_time = item.time
        the_real_time = datetime.datetime.strptime(the_time, '%B %d, %Y')
        item_id = item.key.id()
        dict_to_append = {
            "body": body,
            "author": author,
            "title": title,
            "time": the_real_time,
            "id": item_id
        }
        list_to_return.append(dict_to_append)

    list_to_return.sort(key=lambda r: r["time"])

    list_to_return.reverse()

    return jsonify(data=list_to_return)
    def get(self):
        posts = BlogPost.all().order("-date_created")

        return {
            "admin_section": "admin-blog-posts",
            "posts": posts,
        }
Exemple #39
0
    def get(self, category):

        posts = BlogPost.select().where(BlogPost.category == category)
        self.render_template('category.html', {
            'posts': posts,
            'category': category
        })
Exemple #40
0
  def test_label(self):
    for feed_item in None, {}:
      bp = BlogPost(id='x')
      bp.put()
      self.assertEquals('BlogPost x [no url]', bp.label())

    bp = BlogPost(id='x', feed_item={'permalinkUrl': 'http://perma/link'})
    bp.put()
    self.assertEquals('BlogPost x http://perma/link', bp.label())
    def get(self, category = None):
        cur_category = None
        categories = BlogCategory.all()

        if category:
            cur_category = BlogCategory.all().filter("slug =", category).get()
            posts = BlogPost.all().filter("category =", cur_category).order("-date_created")
        else:
            posts = BlogPost.all().order("-date_created")
            cur_category = None

        return {
            "section": "blog",
            "posts": posts,
            "cur_category": cur_category,
            "categories": categories,
        }
Exemple #42
0
 def refetch(self):
     self.posts =BlogPost.all().order('-timestamp')
     memcache.add(KEY,self.posts)
     self.tags = Tag.all()
     memcache.add(TAG,self.tags)
     self.categories= Category.all()
     memcache.add(CATEGORY,self.categories)
     createIndex(self.posts)
Exemple #43
0
 def get(self,blog,id):
     post = BlogPost.get_by_id(int(id))
     templ_val = {
         'post': post,
         'active_blogs':True,
         'comments':post.comments.order('date')
     }
     self.render_to_response('post.html',templ_val)
Exemple #44
0
  def test_notify_url_too_long(self):
    item = {'id': 'X' * (_MAX_KEYPART_BYTES + 1), 'content': 'a http://x/y z'}
    resp = self.client.post('/notify/foo.com', json={'items': [item]})

    self.assertEqual(200, resp.status_code)
    self.assert_blogposts([BlogPost(id='X' * _MAX_KEYPART_BYTES,
                                    source=self.source.key, feed_item=item,
                                    failed=['http://x/y'], status='complete')])
Exemple #45
0
 def get(self, **kwargs):
     language = self.get_locale()
     posts = BlogPost.get_latest_posts(10, language=language)
     context = {
         'posts': posts,
         'language': language,
     }
     return self.render_response('blog/index.html', **context)
Exemple #46
0
def getrecentposts(limit=5):
    """ Get html for the [num] most recent posts.
        Return a list of (title, html) tuples. """
        
    q = BlogPost.all()
    q.order('post_date')
    posts = [(post.title, post.html) for post in q.run(limit=limit)]
    return posts
Exemple #47
0
def create_post():
  post = BlogPost(title=request.form["title"], 
                  content=request.form["content"])
  db_session.add(post)
  db_session.commit()
  print(request.form["title"])
  print(request.form["content"])
  return "Was successful"
Exemple #48
0
 def get(self,name):
     cat = Category.all().filter('link = ',name).get()
     posts = BlogPost.all().filter('category = ',cat.key()).order('-pub_date')
     templ_val = {
         'posts': posts,
         'active_blogs':True
     }
     self.render_to_response('index.html',templ_val)
Exemple #49
0
 def test_handle_feed_allows_bridgy_publish_links(self):
     item = {
         'permalinkUrl': 'A',
         'content': 'a https://brid.gy/publish/facebook b'
     }
     superfeedr.handle_feed(json.dumps({'items': [item]}), self.source)
     self.assert_equals(['https://brid.gy/publish/facebook'],
                        BlogPost.get_by_id('A').unsent)
Exemple #50
0
def create_blogpost(request):
    if request.method == 'POST':
        BlogPost(
            title=request.POST.get('title'),
            body=request.POST.get('body'),
            timestamp=datetime.now()
        ).save()
    return HttpResponseRedirect('/blog/')
Exemple #51
0
    def get(self, slug):
        blog_post = BlogPost.query(BlogPost.slug == slug).get()

        # markdown
        markdowner = markdown2.Markdown()
        blog_post.text = markdowner.convert(blog_post.text)

        params = {"blog": blog_post}
        self.render_template('blogpost.html', params)
Exemple #52
0
  def test_notify_utf8(self):
    """Check that we handle unicode chars in content ok, including logging."""
    self.feed = {'items': [{'id': 'X', 'content': 'a ☕ z'}]}
    resp = self.client.post('/notify/foo.com', json=self.feed)

    self.assertEqual(200, resp.status_code)
    self.assert_blogposts([BlogPost(id='X', source=self.source.key,
                                    feed_item={'id': 'X', 'content': 'a ☕ z'},
                                    status='complete')])
Exemple #53
0
    def get(self, page):
        self.set_header('Cache-Control',
                        'no-store, no-cache, must-revalidate, max-age=0')

        posts = BlogPost.select()
        self.render_template(page + '.html', {
            'posts': posts,
            categories: CATEGORIES
        })
    def generate_resource(cls, post, resource):
        from models import BlogPost

        # Query all posts, and filter out drafts.
        q = BlogPost.all().order("-published")
        q.filter("published !=", datetime.datetime.max)

        html = utils.render_template("labnotes.html", {"generator_class": cls.__name__, "posts": q})
        static.set("/labnotes", html, config.html_mime_type)
Exemple #55
0
  def test_preprocess_superfeedr_item(self):
    self.mox.StubOutWithMock(self.source, 'preprocess_superfeedr_item')

    def add_link(item):
      item['content'] += '\nhttp://added/by/preprocess'
    self.source.preprocess_superfeedr_item(self.item).WithSideEffects(add_link)

    self.mox.ReplayAll()
    superfeedr.handle_feed(self.feed, self.source)
    self.assertEquals(['http://added/by/preprocess'], BlogPost.query().get().unsent)
Exemple #56
0
def getblogpost(title):
    """ Get a blog post titled 'title' from the data store.
        Must be an exact match. """
    q = BlogPost.all()
    q.filter("title =", title.lower())
    try:
        post = q.get()
        return post.title, post.html 
    except AttributeError:
        return None