示例#1
0
    def test_multiple_blog_entry_present_with_earliest_updated_and_another_created_after___the_latest_created_is_the_entry(
            self):
        Entry(
            title="Test Title",
            content="Test Content",
            owner=self.owner,
        ).save()

        Entry(
            title="Second Test Title",
            content="Second Test Content",
            owner=self.owner,
        ).save()

        entry = Entry.objects.get(title="Test Title")
        entry.title = "Modified Test Title"
        entry.save()

        Entry(
            title="Third Test Title",
            content="Third Test Content",
            owner=self.owner,
        ).save()

        self.driver.get(self.live_server_url)

        self.assertEqual("Third Test Title",
                         wait_for_element(self.driver, By.ID, "title").text)
示例#2
0
    def get(self):

        item_type = self.request.get('item')
        if item_type == "entry":
            object_list = Entry.all()
        elif item_type == "country":
            object_list = Country.all()
        else:
            item_type = None
            object_list = Entry.all()

        object_list = object_list.order('-publish_date')
        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'object_list': object_list,
            'item_type': item_type,
            'url': url,
            'url_linktext': url_linktext,
        }

        path = os.path.join(os.path.dirname(__file__),
                            'templates/admin/view.html')
        self.response.out.write(template.render(path, template_values))
示例#3
0
    def doget(self,page):
        page=int(page)
        #entrycount=self.blog.postscount()
        entrycount=Entry.postscount()
        max_page = entrycount / self.blog.posts_per_page + ( entrycount % self.blog.posts_per_page and 1 or 0 )

        if page < 1 or page > max_page:
            return self.error(404)

        offset_start = (page-1) * self.blog.posts_per_page
        offset_end = offset_start + self.blog.posts_per_page
        entries = Entry.all().filter(entrytype = 'post').\
                filter(published = True).order_by('-date')[offset_start:offset_end]#.\
                #fetch(self.blog.posts_per_page, offset = (page-1) * self.blog.posts_per_page)
        #import pdb; pdb.set_trace()

        show_prev =entries and  (not (page == 1))
        #show_prev = True
        show_next =entries and  (not (page == max_page))
        #show_next = True
        #print page,max_page,self.blog.entrycount,self.blog.posts_per_page


        self.render('index',{'entries':entries,
                           'show_prev' : show_prev,
                        'show_next' : show_next,
                        'pageindex':page,
                        'ishome':True,
                        'pagecount':max_page,
                        'postscounts':entrycount
                            })
示例#4
0
    def GET(self,tags=None):
        try:
            all=self.param('all')
        except:
            all=False

        if(all):
            entries = Entry.all().order('-date')
            filename='micolog.%s.xml'%datetime.now().strftime('%Y-%m-%d')
        else:
            str_date_begin=self.param('date_begin')
            str_date_end=self.param('date_end')
            try:
                date_begin=datetime.strptime(str_date_begin,"%Y-%m-%d")
                date_end=datetime.strptime(str_date_end,"%Y-%m-%d")
                entries = Entry.all().filter('date >=',date_begin).filter('date <',date_end).order('-date')
                filename='micolog.%s.%s.xml'%(str(str_date_begin),str(str_date_end))
            except:
                self.render2('views/admin/404.html')

        cates=Category.all()
        tags=Tag.all()

        self.response.headers['Content-Type'] = 'binary/octet-stream'#'application/atom+xml'
        self.response.headers['Content-Disposition'] = 'attachment; filename=%s'%filename
        self.render2('views/wordpress.xml',{'entries':entries,'cates':cates,'tags':tags})
示例#5
0
    def get(self):

        item_type = self.request.get('item')
        if item_type == "entry":
            object_list = Entry.all()
        elif item_type == "country":
            object_list = Country.all()
        else:
            item_type = None
            object_list = Entry.all()

        object_list = object_list.order('-publish_date')
        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'object_list': object_list,
            'item_type': item_type,
            'url': url,
            'url_linktext': url_linktext,
        }

        path = os.path.join(os.path.dirname(__file__), 'templates/admin/view.html')
        self.response.out.write(template.render(path, template_values))
示例#6
0
    def GET(self,slug=None,postid=None):
        if postid:
            postid = int(postid)
            entries = Entry.all().filter(published = True).filter(post_id = postid)[0:1]#.fetch(1)
        else:
            slug=urldecode(slug)
            entries = Entry.all().filter(published = True).filter(link = slug)[0:1]#.fetch(1)
        if not entries or len(entries) == 0:
            self.error(404)
            return

        mp=self.paramint("mp",1)

        entry=entries[0]
        if entry.is_external_page:
            self.redirect(entry.external_page_address,True)
        if self.blog.allow_pingback and entry.allow_trackback:
            self.response.headers['X-Pingback']="%s/rpc"%str(self.blog.baseurl)
        entry.readtimes += 1
        entry.put()
        self.entry=entry


        comments=entry.get_comments_by_page(mp,self.blog.comments_per_page)


##        commentuser=self.request.cookies.get('comment_user', '')
##        if commentuser:
##            commentuser=commentuser.split('#@#')
##        else:
        commentuser=['','','']

        comments_nav=self.get_comments_nav(mp,entry.purecomments().count())

        if entry.entrytype=='post':
            self.render('single',
                        {
                        'entry':entry,
                        'relateposts':entry.relateposts,
                        'comments':comments,
                        'user_name':commentuser[0],
                        'user_email':commentuser[1],
                        'user_url':commentuser[2],
                        'checknum1':random.randint(1,10),
                        'checknum2':random.randint(1,10),
                        'comments_nav':comments_nav,
                        })

        else:
            self.render('page',
                        {'entry':entry,
                        'relateposts':entry.relateposts,
                        'comments':comments,
                        'user_name':commentuser[0],
                        'user_email':commentuser[1],
                        'user_url':commentuser[2],
                        'checknum1':random.randint(1,10),
                        'checknum2':random.randint(1,10),
                        'comments_nav':comments_nav,
                        })
示例#7
0
    def test_two_blog_entries_created_one_is_modified___both_entries_are_listed_in_the_correct_order_with_modified_first(
            self):
        Entry(
            title="First Test Entry",
            content="First Test Content",
            owner=self.owner,
        ).save()

        Entry(
            title="Second Test Entry",
            content="Second Test Content",
            owner=self.owner,
        ).save()

        entry = Entry.objects.get(title="First Test Entry")
        entry.title = "Modified Test Entry"
        entry.save()

        self.driver.get(self.live_server_url + "/browse")

        entries = wait_for_all_elements(self.driver, By.CLASS_NAME,
                                        "blog-listing-entry")
        num_entries = len(entries)
        titles = [
            entry.find_element(By.CLASS_NAME, "title").text
            for entry in entries
        ]

        self.assertEqual(2, num_entries)
        self.assertEqual("Modified Test Entry", titles[0])
        self.assertEqual("Second Test Entry", titles[1])
示例#8
0
    def parse(self):
        url =  "https://%s:%[email protected]/v1/posts/recent" % (self.username, self.password)
        xmlData = xml_parser.parseString(self.fetch(url))
        
        for node in xmlData.getElementsByTagName('post'):
            description = node.getAttribute('description')
            url = node.getAttribute('href')
            temp = node.getAttribute('time')
            temp = temp.split('T')
            d = temp[0].split('-')
            t = temp[1].split(':')
            t[2] = t[2].strip('Z')

            date = []
            for i in d:
                date.append(int(i))
            for j in t:
                date.append(int(j))
    
            acceptable = datetime(date[0], date[1], date[2], date[3], date[4], date[5])

            a = Entry.objects.filter(name=url, date=acceptable)
            if(len(a) < 1):
                u = User.objects.filter(username=self.user)[0]
                entry = Entry(name=url, description=description, date=acceptable, entry_type='delicious', user=u)
                entry.save()
示例#9
0
def blogger_newPost(user, appkey, blogid, content, publish):
    """
    Blogger doesn't support titles, so we will use the standard trick of
    searching for a <title></title> tag and using that for a title. Returns
    post id.
    """

    authorid = blogid
    if not authorid:
        authorid = Author.objects.all()[0].id
    title, body = blogger_split_content(content)

    pub_date = datetime.datetime.now()
    
    entry = Entry(headline = title,
                  slug = slugify(title),
                  content = body,
                  author_id = authorid,
                  pub_date = pub_date,
                  status = publish and PUBLISHED or DRAFT,)
    entry.save()
    # No tagging in this API...at least formally
    # setTags(entry, struct)
    entry.sites.add(Site.obects.get_current())

    return entry.id
示例#10
0
def create_test_blog_entry(author, title="default title"):
    test_post = Entry(
        date_created=timezone.localtime(timezone.localtime()),
        author=author,
        title=title,
        html_content="Don't read this..",
    )
    test_post.save()
    return test_post
示例#11
0
文件: views.py 项目: rmalik/dspillini
def create(request):
	if request.is_ajax():
		e = Entry(title=request.POST['title'],
				  body=request.POST['editor_data'],
				  author = users.get_current_user())
		e.put()
		return archive_index(request)
	else:
		return render_to_response('blog/create.html')
示例#12
0
    def __create_entry(self, lang, author, cat, title, post, date):
        entry = Entry(lang=lang, author=author, title=title, post=post,
                      date=date, mod_date=date, published=True)

        entry.save()
        entry.cat.add(cat)

        print "Created entry : {} | {} | ".format(lang, title)

        return entry
    def test_two_objects_created___result_is_first_created_object(self):
        Entry(
            title="First Title",
            content="First Content",
            owner=self.owner,
        ).save()

        Entry(
            title="Second Title",
            content="Second Content",
            owner=self.owner,
        ).save()

        self.assertEqual(Entry.objects.get(title="First Title"), first_or_none(Entry.objects.all()))
    def test_two_objects_created_accessed_in_reverse_order___result_is_second_created_object(self):
        Entry(
            title="First Title",
            content="First Content",
            owner=self.owner,
        ).save()

        Entry(
            title="Second Title",
            content="Second Content",
            owner=self.owner,
        ).save()

        self.assertEqual(Entry.objects.get(title="Second Title"), first_or_none(Entry.objects.all().order_by("-id")))
示例#15
0
def create_entry(**kwargs):
    defaults = {
        "title": "Test entry1",
        "body": "Entry body",
        "keywords": "test, entry",
        # 'categories': self.create_category(),
    }
    defaults.update(kwargs)
    entry = Entry(**defaults)
    entry.slug = slugify(entry.title)
    entry.save()
    category = create_category()
    entry.categories.add(category)
    return entry
示例#16
0
    def __create_entry(self, lang, author, cat, title, post, date):
        entry = Entry(lang=lang,
                      author=author,
                      title=title,
                      post=post,
                      date=date,
                      mod_date=date,
                      published=True)

        entry.save()
        entry.cat.add(cat)

        print "Created entry : {} | {} | ".format(lang, title)

        return entry
示例#17
0
def create_or_edit_entry(**kwargs):
    # GET
    entry_id = kwargs.pop('entry_id', None)
    form = EntryForm()
    entry = None
    errors = None
    if entry_id:
        entry = Entry.query.filter_by(id=entry_id).first_or_404()
        form = EntryForm(obj=entry)

    # POST
    if request.method == 'POST':
        if form.validate_on_submit():
            if entry_id:
                form.populate_obj(entry)
                db.session.commit()
                flash(
                    'Zmiany w poscie zostały zapisane. '
                    'Aby wyświetlić go na stronie głównej pamiętaj aby zaznaczyć "Wpis opublikowany"'
                )
            else:
                entry = Entry(title=form.title.data,
                              body=form.body.data,
                              is_published=form.is_published.data)
                db.session.add(entry)
                db.session.commit()
                flash(
                    'Nowy post został dodany. '
                    'Aby wyświetlić go na stronie głównej pamiętaj aby zaznaczyć "Wpis opublikowany"'
                )
        else:
            errors = form.errors
    return render_template('entry_form.html', form=form, errors=errors)
示例#18
0
def create_update(entry_id=None):
    errors = None
    if entry_id is None:
        form = EntryForm()
        if request.method == 'POST':
            if form.validate_on_submit():
                entry = Entry(
                    title=form.title.data,
                    body=form.body.data,
                    is_published=form.is_published.data
                )
                db.session.add(entry)
                db.session.commit()
                flash('The post has been successfully added!')
                return redirect(url_for("index"))
            else:
                errors = form.errors
    elif entry_id != 0:
        entry = Entry.query.filter_by(id=entry_id).first_or_404()
        form = EntryForm(obj=entry)
        if request.method == 'POST':
            if form.validate_on_submit():
                form.populate_obj(entry)
                db.session.commit()
                flash('The post has been successfully changed!')
                return redirect(url_for("index"))
            else:
                errors = form.errors
    return render_template("entry_form.html", form=form, errors=errors)
示例#19
0
def create_update(entry_id=None):
    errors = None
    if entry_id != None:
        entry = Entry.query.filter_by(id=entry_id).first_or_404()
        form = EntryForm(obj=entry)
        if request.method == 'POST':
            if form.validate_on_submit():
                form.populate_obj(entry)
                db.session.commit()
            else:
                errors = form.errors
    else:
        form = EntryForm()
        if request.method == 'POST':
            if form.validate_on_submit():
                entry = Entry(
                    title=form.title.data,
                    body=form.body.data,
                    is_published=form.is_published.data
                )
                db.session.add(entry)
                db.session.commit()
            else:
                errors = form.errors
    return form, errors
示例#20
0
def seed():
    content = """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."""

    for i in range(25):
        entry = Entry(title="Test Entry #{}".format(i), content=content)
        session.add(entry)
    session.commit()
示例#21
0
 def get_all_entries_by_month(year, month, **kwargs):
     return Service.get_all(
         Entry.query(
             ndb.AND(
                 Entry.created > datetime.datetime(year, month, 1, 1, 0, 0),
                 Entry.created < datetime.datetime(year, month + 1, 1, 0,
                                                   0))), **kwargs)
示例#22
0
    def get(self):

        key = self.request.get('key')
        item_type = self.request.get('item_type')
        if item_type == "entry":
            entry = Entry.get(key)
            form = EditEntryForm(instance=entry)
        else:
            entry = Country.get(key)
            form = EditCountryForm(instance=entry)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'form': form,
            'item_type': item_type,
            'key': key,
            'url': url,
            'url_linktext': url_linktext,
        }

        path = os.path.join(os.path.dirname(__file__),
                            'templates/admin/edit.html')
        self.response.out.write(template.render(path, template_values))
示例#23
0
 def handle(self, *args, **options):
     Blog.objects.all().delete()
     blog = Blog.objects.create(**BLOG_KWARGS)
     Author.objects.all().delete()
     Author.objects.bulk_create((Author(name=author) for author in AUTHOR_LIST))
     Entry.objects.all().delete()
     Entry.objects.bulk_create((Entry(blog=blog, **entry) for entry in ENTRY_LIST))
示例#24
0
    def test_single_blog_entry_created_and_modified___published_time_is_present_in_listing_entry(
            self, mock_now):
        def now_time():
            for date in (datetime(2013, 2, 3, 4, 5, 6, tzinfo=utc),
                         datetime(2014, 7, 8, 9, 10, 11, tzinfo=utc)):
                yield date

        mock_now.side_effect = now_time()

        Entry(
            title="Test Post Title",
            content="Test Post Content",
            owner=self.owner,
        ).save()

        entry = Entry.objects.all()[0]
        pk = entry.id
        entry.title = "Modified Title"
        entry.save()

        self.driver.get(self.live_server_url + "/browse")
        publish_time = wait_for_element(
            self.driver, By.CSS_SELECTOR,
            ".blog-listing-entry .publish-time").text

        self.assertEqual(
            "Published: 03 Feb 2013 04:05:06 (Edit: 08 Jul 2014 09:10:11)",
            publish_time)
示例#25
0
def test_add2(req):
    #查询实体
    entry2 = Entry(id=7)
    blog1 = Blog.objects.create(name="博客aaa", entry=entry2)
    blog2 = Blog.objects.create(name="博客bbb", entry=entry2)

    return HttpResponse("<h2>创建成功 2</h2>")
示例#26
0
 def action_updatecomments(self):
     for entry in Entry.all():
         cnt=entry.comments().count()
         if cnt<>entry.commentcount:
             entry.commentcount=cnt
             entry.put()
     self.write(_('"All comments updated"'))
示例#27
0
    def GET(self,tags=None):
        urls = []
        def addurl(loc,lastmod=None,changefreq=None,priority=None):
            url_info = {
                'location':   loc,
                'lastmod':    lastmod,
                'changefreq': changefreq,
                'priority':   priority
            }
            urls.append(url_info)

        addurl(self.blog.baseurl,changefreq='daily',priority=0.9 )

        entries = Entry.all().filter(published = True).order_by('-date')[0:self.blog.sitemap_entries]#.fetch(self.blog.sitemap_entries)

        for item in entries:
            loc = "%s/%s" % (self.blog.baseurl, item.link)
            addurl(loc,item.mod_date or item.date,'never',0.6)

        if self.blog.sitemap_include_category:
            cats=Category.all()
            for cat in cats:
                loc="%s/category/%s"%(self.blog.baseurl,cat.slug)
                addurl(loc,None,'weekly',0.5)

        if self.blog.sitemap_include_tag:
            tags=Tag.all()
            for tag in tags:
                loc="%s/tag/%s"%(self.blog.baseurl, urlencode(tag.tag))
                addurl(loc,None,'weekly',0.5)


##        self.response.headers['Content-Type'] = 'application/atom+xml'
        self.render('/admin/views/sitemap.xml', {'urlset':urls}, content_type='text/xml')#, content_type='application/xhtml+xml')
示例#28
0
def detail(request, entry_id):
    if request.method == "POST":
        form = CommentForm(request.POST, error_class=DivErrorList)
        if form.is_valid():
            author = request.user
            text = request.POST['text']
            entry = entry = Entry.objects.get(pk=entry_id)
            pub_date = timezone.now()
            comment = Comment(author=author,
                              entry=entry,
                              text=text,
                              pub_date=pub_date)
            comment.save()

    dates = Entry.get_dates()
    form = CommentForm()

    try:
        entry = Entry.objects.get(pk=entry_id)
    except Entry.DoesNotExist:
        raise Http404
    comments = Comment.objects.filter(entry=entry)
    context = {'entry': entry, 'dates': dates,
               'comments': comments, 'form': form}
    return render(request, 'blog/detail.html', context)
示例#29
0
    def get(self):


        key = self.request.get('key')
        item_type = self.request.get('item_type')
        if item_type == "entry":
            entry = Entry.get(key)
            form = EditEntryForm(instance=entry)
        else:
            entry = Country.get(key)
            form = EditCountryForm(instance=entry)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'form': form,
            'item_type': item_type,
            'key': key,
            'url': url,
            'url_linktext': url_linktext,
        }

        path = os.path.join(os.path.dirname(__file__), 'templates/admin/edit.html')
        self.response.out.write(template.render(path, template_values))
示例#30
0
def get_entries(entry_id):
    errors = None
    if entry_id != 0:
        entry = Entry.query.filter_by(id=entry_id).first_or_404()
        form = EntryForm(obj=entry)
        flash_mess = f'Edytowano post {entry.title} na blogu.'

    else:
        form = EntryForm()
        entry = Entry(
            title=form.title.data,
            body=form.body.data,
            is_published=form.is_published.data
            )
        flash_mess = f'Dodano post {entry.title} na bloga.'
        

    if request.method == 'POST':
        if form.validate_on_submit():
            if entry_id != 0:
                form.populate_obj(entry)
            else:
                db.session.add(entry)
            db.session.commit()
            flash(flash_mess)
            return redirect(url_for("index"))
        else:
            errors = form.errors

    return render_template("entry_form.html", form=form, errors=errors)
示例#31
0
def create_edit_entry(entry_id=0):
    errors = None
    if entry_id == 0:
        entry_form = EntryForm()
    else:
        entry = Entry.query.filter_by(id=entry_id).first_or_404()
        entry_form = EntryForm(obj=entry)

    if request.method == "POST":
        if request.form["btn"] == "Save":
            if entry_form.validate_on_submit():
                if entry_id == 0:
                    entry = Entry(title=entry_form.title.data,
                                  body=entry_form.body.data,
                                  is_published=entry_form.is_published.data)
                    db.session.add(entry)
                else:
                    entry_form.populate_obj(entry)
            else:
                errors = entry_form.errors
                flash('Nie wpowadzono zmian', 'danger')

        if request.form["btn"] == "Cancel":
            return redirect(url_for("index"))

        db.session.commit()
        flash('Zmiany dodane pomyślnie', 'success')
        return redirect(url_for("index"))

    return render_template("entry_form.html",
                           entry_form=entry_form,
                           errors=errors)
示例#32
0
def entry(entry_id=None):
    if entry_id is None:
        form = EntryForm()
        errors = None
        if request.method == "POST":
            if form.validate_on_submit():
                entry = Entry(
                    title = form.title.data,
                    body = form.body.data,
                    is_published = form.is_published.data
                )
                db.session.add(entry)
                db.session.commit()
                flash(f'Dodano wpis {form.title.data} do bloga!')
            else:
                errors = form.errors
        return render_template("entry_form.html", form=form, errors=errors)
    else:
        entry = Entry.query.filter_by(id=entry_id).first_or_404()
        form = EntryForm(obj=entry)
        errors = None
        if request.method == 'POST':
            if form.validate_on_submit():
                form.populate_obj(entry)
                db.session.commit()
                flash(f'Zmieniono wpis {form.title.data}')
            else:
                errors = form.errors
        return render_template("entry_form.html", form=form, errors=errors)
示例#33
0
def add_post(id=None):
    if id:
        post = Entry.query.filter_by(id=id).first()
        form = EntryForm(
            data={
                'title': post.title,
                'body': post.body,
                'is_published': post.is_published
            })
        post.title = form.title.data
        post.body = form.body.data
        post.is_published = form.is_published.data
        if form.is_published.data:
            flash(f'Post "{form.title.data.upper()}" updated!')
        else:
            flash('Required box not checked. Post not added.')
    else:
        form = EntryForm()
        new_post = Entry(title=form.title.data,
                         body=form.body.data,
                         is_published=form.is_published.data)
        db.session.add(new_post)
        if form.is_published.data:
            flash(f'New post "{form.title.data.upper()}" added!')
        else:
            flash('Required box not checked. Post not added.')
    db.session.commit()
示例#34
0
文件: views.py 项目: Yookkee/Django
def add(request, secret_key, title, text):
    users = User.objects.filter(first_name=secret_key)
    ab = {}
    if users.count() == 0:
        ab['result'] = "Incorrect query"
        return HttpResponse("{}".format(json.dumps(ab)))
    else:
        user = users[0]

    pub_date = timezone.now()
    post = Entry(title=title, text=text, author=user, pub_date=pub_date)
    post.save()

    ab = {}
    ab['result'] = "New node created"
    return HttpResponse("{}".format(json.dumps(ab)))
示例#35
0
 def create(self, form):
     entry = Entry(parent=Service.to_key(form.category.data))
     entry.title = form.title.data
     entry.summary = form.summary.data
     entry.post = form.post.data
     entry.tags = [Key(urlsafe=tag) for tag in form.tags.data]
     entry.slug = Service.slugify(entry.title)
     # entry.user = users.get_current_user()
     return entry.put()
示例#36
0
 def simulate_add_entry(self, title, content):
     """
     define this method to add test data for edit and delete workflow
     """
     entry = Entry(title=title, content=content)
     session.add(entry)
     session.commit()
     return entry.id
示例#37
0
def fake_posts(quantity=10):
    fake = Faker()
    for i in range(quantity):
        new_post = Entry(title=fake.sentence(),
                         body='\n'.join(fake.paragraphs(15)),
                         is_published=True)
        db.session.add(new_post)
        db.session.commit()
示例#38
0
def link(request, id):
    link = get_object_or_404(Link, id=id)
    return render(request,
                  'blog/link.html',
                  {'item': link,
                   'popular_entries': Entry.popular_entries(),
                   # 'form': form
                   })
示例#39
0
    def test_multiple_blog_entry_present___the_latest_created_is_the_entry(
            self):
        Entry(
            title="Test Title",
            content="Test Content",
            owner=self.owner,
        ).save()

        Entry(
            title="Second Test Title",
            content="Second Test Content",
            owner=self.owner,
        ).save()

        self.driver.get(self.live_server_url)

        self.assertEqual("Second Test Title",
                         wait_for_element(self.driver, By.ID, "title").text)
示例#40
0
 def GET(self,tags=None):
     entries = Entry.all().filter(entrytype = 'post').filter(published = True).order_by('-date')[0:10]#.fetch(10)
     if entries and entries[0]:
         last_updated = entries[0].date
         last_updated = last_updated.strftime("%a, %d %b %Y %H:%M:%S +0000")
     for e in entries:
         e.formatted_date = e.date.strftime("%a, %d %b %Y %H:%M:%S +0000")
     self.response.headers['Content-Type'] = 'application/rss+xml; charset=utf-8'
     self.render2('/admin/views/rss.xml',{'entries':entries,'last_updated':last_updated})
示例#41
0
def generate_entries(how_many=3):
    fake = Faker()

    for i in range(how_many):
        post = Entry(title=fake.sentence(),
                     body='\n'.join(fake.paragraphs(15)),
                     is_published=True)
        db.session.add(post)
    db.session.commit()
示例#42
0
def create_entry():
    form = EntryForm()
    entry_id = None
    entry = Entry(
        title=form.title.data,
        body=form.body.data,
        is_published=form.is_published.data
        )
    return create_or_edit_entry(entry_id, entry, form)
示例#43
0
    def test_entry_is_created___creation_time_is_updated_to_current_time(self):
        Entry(
            title="Title",
            content="Entry Content",
            owner=self.owner,
        ).save()

        entry = Entry.objects.get(title="Title")

        self.assertEqual(datetime(2014, 1, 1, tzinfo=utc), entry.creation_time)
示例#44
0
def create():
    form = EntryForm()
    if request.method == 'POST' and form.validate_on_submit():
        entry = form.save_entry(Entry(author=g.user))
        db.session.add(entry)
        db.session.commit()
        flash('Enrty {} has been created successfully'.format(entry.title),
              'success')
        return redirect(url_for('.detail', slug=entry.slug))
    return render_template('entries/create.html', form=form)
示例#45
0
 def handle(self, *args, **options):
     """Clear old instances and create new ones."""
     Blog.objects.all().delete()
     blog = Blog.objects.create(**BLOG_KWARGS)
     Author.objects.all().delete()
     Author.objects.bulk_create(
         Author(name=author) for author in AUTHOR_LIST)
     Entry.objects.all().delete()
     Entry.objects.bulk_create(
         Entry(blog=blog, **entry) for entry in ENTRY_LIST)
示例#46
0
	def create(self, form):
		entry = Entry(parent=Service.to_key(form.category.data))
		entry.title = form.title.data
		entry.summary = form.summary.data
		entry.post = form.post.data
		entry.tags = [Key(urlsafe=tag) for tag in form.tags.data]
		entry.slug = Service.slugify(entry.title)
		# entry.user = users.get_current_user()
		return entry.put()
示例#47
0
    def action_init_blog(self,slug=None):

        for com in Comment.all():
            com.delete()

        for entry in Entry.all():
            entry.delete()

        self.blog.entrycount=0
        self.blog.save()
        self.write(_('"Init has succeed."'))
示例#48
0
 def handle(self, *args, **options):
     Blog.objects.all().delete()
     blog = Blog.objects.create(
         name='Recettes', lang='french',
         tagline='Des recettes dans toutes les langues!')
     Author.objects.all().delete()
     Author.objects.bulk_create(
         (Author(name=author) for author in AUTHOR_LIST))
     Entry.objects.all().delete()
     Entry.objects.bulk_create(
         (Entry(blog=blog, **entry) for entry in ENTRY_LIST))
示例#49
0
    def action_update_tags(self,slug=None):
        for tag in Tag.all():
            tag.delete()
        for entry in Entry.all().filter('entrytype =','post'):
            if entry.tags:
                for t in entry.tags:
                    try:
                        Tag.add(t)
                    except:
                        traceback.print_exc()

        self.write(_('"All tags for entry have been updated."'))
示例#50
0
def clean_gae():
   query = Entry.all()
   entries =query.fetch(1000)
   db.delete(entries)

   query = Country.all()
   countries = query.fetch(1000)
   db.delete(countries)

   query = Tag.all()
   tags = query.fetch(1000)
   db.delete(tags)
示例#51
0
    def GET(self):
        #super(MainPage, self).initialize(request)
        params = {}
        page = 1
        entries = Entry.all().filter('entrytype =','post').\
    				filter("published =", True).order('-date').\
    				fetch(self.blog.posts_per_page, offset = (page-1) * self.blog.posts_per_page)
        for entry in entries:
            entry.link = '%s/%s' % (self.app_context.current_app, entry.link)

        params['entries'] = entries
        return self.render('index.html', params)
示例#52
0
 def test_create_unpublished(self):
     user = create_user()
     entry = Entry(title="Title Me", body="Hello world", created_user=user)
     entry.save()
     self.assertEqual(Entry.objects.all().count(), 1)
     entry.publish = True
     entry.save()
示例#53
0
def new_post(request):
    if not request.user.is_authenticated():
        return redirect('login')
    if request.method == "POST":
        form = PostForm(request.POST, error_class=DivErrorList)
        if form.is_valid():
            title = request.POST['title']
            post = request.POST['post']
            p = Entry(author=request.user,
                      title=title,
                      post=post,
                      pub_date=timezone.now())
            p.save()
            entry_id = p.pk
            return redirect('detail', entry_id=entry_id)
    else:
        form = PostForm

    dates = Entry.get_dates()
    context = {'dates': dates, 'form': form}

    return render(request, 'blog/new_post.html', context)
示例#54
0
def link(request, id):
    link = get_object_or_404(Link, id=id)
    form = CommentForm(request)
    if request.method == 'POST':
        form = CommentForm(request, request.POST)
        if form.is_valid():
            comment = form.save_comment_for(link)
            return HttpResponseRedirect(_comment_url(request, comment))
    return render(request,
                  'blog/link.html',
                  {'item': link,
                   'popular_entries': Entry.popular_entries(),
                   'form': form})
示例#55
0
文件: views.py 项目: Yookkee/Django
def createpost(request):
    args={}
    args.update(csrf(request))
    if request.POST:
        title = request.POST.get('title', '')
        text = request.POST.get('text', '')
        user = auth.get_user(request)
        if not user.is_authenticated():
            args['createpost_error'] = "Login before creating posts!"
            return render_to_response("blog/createpost.html", args)
        elif title is None:
            args['createpost_error'] = "Write some title!"
            return render_to_response("blog/createpost.html", args)
        elif not text:
            args['createpost_error'] = "Write some text!"
            return render_to_response("blog/createpost.html", args)
        else:
            pub_date = timezone.now()
            post = Entry(title=title, text=text, author=user, pub_date=pub_date)
            post.save()
            return redirect('/');
    else:
        return render_to_response("blog/createpost.html", args)
示例#56
0
    def GET(self,slug=None):
        if not slug:
             self.error(404)
             return
        try:
            page_index=int (self.param('page'))
        except:
            page_index=1
        import urllib
        slug=urldecode(slug)

        entries=Entry.all().filter(published = True).filter(tags = slug).order_by("-date")
        entries,links=Pager(query=entries,items_per_page=20).fetch(page_index)
        self.render('tag',{'entries':entries,'tag':slug,'pager':links})
示例#57
0
def index(request):
    entries_list = Entry.objects.all().order_by('-pub_date')
    paginator = Paginator(entries_list, 5)  # Show 5 entries per page
    entries = request.GET.get('page')
    try:
        entries = paginator.page(entries)
    except PageNotAnInteger:
        entries = paginator.page(1)
    except EmptyPage:
        entries = paginator.page(paginator.num_pages)

    dates = Entry.get_dates()
    context = { 'dates': dates, 'entries': entries}
    return render(request, 'blog/index.html', context)
示例#58
0
def metaWeblog_newPost(blogid, username, password, struct, publish):
    user = User.objects.get(username__exact=username)
    if struct.has_key('title') and struct.has_key('description'):
        post = Entry(title=struct['title'],content = struct['description'])
        post.author=user
        if struct.has_key('categories'):
            catename = struct['categories'][0]
            cate=Category.objects.get(name__exact=catename)
            post.category=cate
        else:
            post.category_id=1
        if struct.has_key('mt_keywords'):
            post.tags=struct['mt_keywords']
        if struct.has_key('wp_slug'):
            post.slug=struct['wp_slug']
        post.save(True)
    return ""
示例#59
0
 def parse(self):
     jaikuUrl = "http://%s.jaiku.com/feed/rss" % (self.username)
     data = self.fetch(jaikuUrl)
     print data
     xmlData = xml_parser.parseString(data)
     
     for node in xmlData.getElementsByTagName('item'):
         title = self.getText(node.getElementsByTagName('title')[0].childNodes)
         url =  self.getText(node.getElementsByTagName('link')[0].childNodes)
         #filter out all other entries such as last.fm
         if (url.find('jaiku') != -1): 
             # once again, make a proper datetime out of the date in the xml
             d = self.getText(node.getElementsByTagName('pubDate')[0].childNodes)
             d = d.split(' ')
             d.pop() # remove the day of the week
             d.pop(0) # remove the time zone
             t = d[3].split(':') # divide time to it's own list
             d.pop() # remove the time 
             months = { 'Jan':'1', 'Feb':'2', 'Mar':'3', 'Apr':'4', 'May':'5', 'Jun':'6', 'Jul':'7', 'Aug':'8', 'Sep':'9', 'Oct':'10', 'Nov':'11', 'Dec':'12' }
             d[1] = months[d[1]] # correct three-letter month as a number 
         
             #d and t are now string lists, make one int list out of them
             date = [] 
             for i in d:
                 date.append(int(i))
             for j in t:
                 date.append(int(j))
         
             date = datetime(date[2], date[1], date[0], date[3], date[4], date[5])
         
             # check that entry is not yet in database
             a = Entry.objects.filter(name=title, date=date)
             if (len(a) < 1):
                 u = User.objects.filter(username=self.user)[0]
                 entry = Entry(name=title, url=url, date=date, entry_type='jaiku', user=u)
                 entry.save()
示例#60
0
    def POST(self,slug='post'):
        try:
            linkcheck= self.request.get_all('checks')
            for id in linkcheck:
                kid=int(id)

                entry=Entry.get_by_id(kid)

                #delete it's comments
                #entry.delete_comments()

                entry.delete()
                self.blog.entrycount-=1
        finally:

            self.redirect('/admin/entries/'+slug)