Example #1
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
Example #2
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()
 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()
Example #4
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
Example #5
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
Example #6
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
Example #7
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
Example #8
0
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)))
Example #9
0
def init_data(**kwargs):
    link=Link(text="dengmin's blog",href="http://www.iyouf.info")
    link.save()
    
    default_cate=Category(name=u'未分类',slug='default',desc=u'未分类')
    default_cate.save()
    
    entry=Entry(title='Hello World!',content='<b>Hello World, welcome to use youflog! thank you!</a>',tags='youflog')
    entry.allow_comment=True
    entry.slug='hello-world'
    entry.category=default_cate
    entry.author_id=1
    entry.save(True)
    
    comment=Comment(author='admin',email='*****@*****.**',weburl='http://iyouf.info',content=u'测试第一条评论')
    comment.content_object=entry
    comment.save()
Example #10
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 ""
Example #11
0
	def setUp(self):
		author = User(last_name="chocolate", email="*****@*****.**")
		author.save()
		call_command('populatedb')
		entry_new = Entry(
			author=User.objects.get(pk=1),
			body='foo',
			language=Language.objects.get(pk=5),
			title='foo bar',
		)
		entry_new.save()
		entry_old = Entry(
			author=User.objects.get(pk=1),
			body='test',
			language=Language.objects.get(name="French"),
			title='Test de langue',
		)
		entry_old.save()
Example #12
0
def insert_blog(request):
    if request.method == 'POST':

        blog_form = BlogForm(request.POST)
        if blog_form.is_valid():

            blog_name_from_user = blog_form.cleaned_data['blog_name']
            blog_tagline_from_user = blog_form.cleaned_data['blog_tag_line']

            blog_object = Blog(name=blog_name_from_user,
                               tagline=blog_tagline_from_user)
            blog_object.save()  # will save the data from the form to database

            blog_object = Blog()
            blog_object.name = "Blog"
            blog_object.tagline = "Lorem ipsum dolor sit amet"
            blog_object.save(
            )  # will save the data from the form to database table blog

            entry_object = Entry()
            entry_object.headline = "Lorum Ipsum"
            entry_object.body_text = """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."""
            entry_object.pub_date = "2018-07-04"
            entry_object.mod_date = "2018-07-04"
            entry_object.n_comments = 0
            entry_object.n_pingbacks = 0
            entry_object.rating = 5
            entry_object.blog = blog_object  # will insert the blog id into blog_entry
            entry_object.save()

            john = Author.objects.create(
                name="John")  # will create new author in blog_authers table
            paul = Author.objects.create(
                name="Paul")  # will create new author in blog_authers table
            george = Author.objects.create(
                name="George")  # will create new author in blog_authers table

            entry_object.authors.add(
                john, paul, george)  # will add data to blog_entry_authors
            return HttpResponse('Data Inserted successfully')

    else:
        blog_form = BlogForm(request.POST)
        return render(request, 'blog-insert-form.html', {'form': blog_form})
Example #13
0
def quick_post(request):
    title=request.POST.get('title')
    content=request.POST.get('content','')
    tags=request.POST.get('tags','')
    save=request.POST.get('save')
    publish=request.POST.get('publish')
    
    if not title and not content:
        return HttpResponse(u"文章标题和内容不能为空!")
    entry=Entry(title=title,content=content,tags=tags,slug='',allow_comment=True)
    entry.author=request.user
    entry.category_id=1
    if save:
        entry.save(False)
        html=u"<p>文章已保存.&nbsp;<a href='/admin/editpost/%s'>编辑文章</a></p>"%(str(entry.id))
    elif publish:
        entry.save(True)
        html=u"<p>文章已发布.&nbsp;<a href='%s' target='_blank'>查看文章</a></p>"%(entry.get_absolute_url())
    
    return HttpResponse(html)
    def test_entry_is_updated___created_time_is_unchanged(self, mock_now):
        def now_time():
            for date in (datetime(2013, 1, 1,
                                  tzinfo=utc), datetime(2014, 1, 1,
                                                        tzinfo=utc)):
                yield date

        mock_now.side_effect = now_time()

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

        entry.save()
        entry.title = "new title"
        entry.save()

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

        self.assertEqual(datetime(2013, 1, 1, tzinfo=utc), entry.creation_time)
Example #15
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)
Example #16
0
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)
Example #17
0
def load():
    """
    Load a series of markdown and yaml files from content folders. YAML is for
    blogpost metadata and markdown files are blogpost content.
    """
    # Clearout the old db
    # FIXME: this should check itself before it deletes things.
    old_entries = Entry.objects.all()
    old_entries.delete()

    # Recreate the content of the db
    years = ['02011'] # only one year of content for now, append later
    # TODO: use this in a blog-wide yaml config file, can generate 1996-2010(c)
    for year in years:
        folder = './content/blog/' + year + '/'
        files = set([os.path.splitext(f)[0] for f in os.listdir(folder)])
        for file in files:
            meta_file   = open(folder + file + '.yaml', 'r')
            metadata    = yaml.load(meta_file)
            meta_file.close()

            post_file   = open(folder + file + '.md', 'r')
            post        = post_file.read()
            post_file.close()

            e = Entry()
            # TODO: implement django-tagging here
            # Metadata
            e.title     = metadata['title']
            e.slug      = slugify(metadata['title'])
            e.pub_date  = metadata['pub_date']
            e.published = metadata['published']
            # Post
            e.body      = post
            e.snip      = post[:139]            # 140 characters of fun
            e.save()
    pass
Example #18
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()
Example #19
0
def metaWeblog_newPost(user, blogid, struct, publish):



    # Check if we are getting a userid in the post,
    # if we are not, default to the first author entered...
    authorid = blogid
    if not authorid:
        authorid = Author.objects.all()[0].id

    pub_date = struct.get('dateCreated', None)
    if not pub_date:
        pub_date = datetime.datetime.now()
    else:
        # ISO 8601 time parsing is one of those things that sucks, and Python
        # doesn't have any decent way of handling the variety of formats
        # it may come in.  So, we make an effort to parse the most common
        # form, and then default to today if we can't figure it out correctly.
        try:
            pub_date = datetime.datetime.strptime( str(pub_date), "%Y%m%dT%H:%M:%S" )
        except ValueError:
            pub_date = datetime.datetime.now()
    

    content = struct['description']
    # todo - parse out technorati tags

    # Handle Movable Type extensions
    # We ignore pings, tb_ping_urls, keywords, and convert_breaks
    # If we get text_more we just append it to the content
    comments = struct.get('mt_allow_comments', None)
    if comments is not None:
        comments = bool(comments)
    else:
        # User default value
        comments = True
    
    abstract = struct.get('mt_excerpt', None)
    if abstract is None:
        abstract = ''
    
    footer = struct.get('mt_text_more', None)
    if footer is not None:
        content += footer


    entry = Entry(headline = struct['title'],
                  slug = slugify(struct['title']),
                  content = content,
                  author_id = authorid,
                  pub_date = pub_date,
                  comments = comments,
                  abstract = abstract,
                  status = publish and PUBLISHED or DRAFT,)

    # entry.prepopulate()
    entry.save()
    
    # Add any tags needed
    setTags(entry, struct.get('categories', None))
    # Add site by using blogid
    entry.sites.add(Site.objects.get_current())

    return entry.id
Example #20
0
def test_blog_save():
    e = Entry(id=1, body="foo")
    e.save()
    e.refresh_from_db()
Example #21
0
    def POST(self,slug='post'):
        action=self.param("action")
        title=self.param("post_title")
        content=self.param('content')
        tags=self.param("tags")
        cats=self.request.get_all('cats')
        key=self.param('key')
        if self.param('publish')!='':
            published=True
        elif self.param('unpublish')!='':
            published=False
        else:
            published=self.param('published')=='True'

        allow_comment=self.parambool('allow_comment')
        allow_trackback=self.parambool('allow_trackback')
        entry_slug=self.param('slug')
        entry_parent=self.paramint('entry_parent')
        menu_order=self.paramint('menu_order')
        entry_excerpt=self.param('excerpt').replace('\n','<br />')
        password=self.param('password')
        sticky=self.parambool('sticky')

        is_external_page=self.parambool('is_external_page')
        target=self.param('target')
        external_page_address=self.param('external_page_address')

        def mapit(cat):
            return {'name':cat.name,'slug':cat.slug,'select':cat.slug in cats}

        vals={'action':action,'postback':True,'cats':Category.all(),'entrytype':slug,
              'cats':map(mapit,Category.all()),
              'entry':{ 'title':title,'content':content,'strtags':tags,'key':key,'published':published,
                         'allow_comment':allow_comment,
                         'allow_trackback':allow_trackback,
                        'slug':entry_slug,
                        'entry_parent':entry_parent,
                        'excerpt':entry_excerpt,
                        'menu_order':menu_order,
                        'is_external_page':is_external_page,
                        'target':target,
                        'external_page_address':external_page_address,
                        'password':password,
                        'sticky':sticky}
              }

        if not (title and (content or (is_external_page and external_page_address))):
            vals.update({'result':False, 'msg':_('Please input title and content.')})
            self.render2('views/admin/entry.html',vals)
        else:
            if action=='add':
                entry= Entry(title=title,content=content)
                entry.settags(tags)
                entry.entrytype=slug
                entry.slug=entry_slug.replace(" ","-")
                entry.entry_parent=entry_parent
                entry.menu_order=menu_order
                entry.excerpt=entry_excerpt
                entry.is_external_page=is_external_page
                entry.target=target
                entry.external_page_address=external_page_address
                newcates=[]
                entry.allow_comment=allow_comment
                entry.allow_trackback=allow_trackback
                entry.author=self.author.user
                entry.author_name=self.author.dispname
                entry.password=password
                entry.sticky=sticky
                if cats:

                    for cate in cats:
                        c=Category.all().filter('slug =',cate)
                        if c:
                            newcates.append(c[0].key())
                entry.categorie_keys=newcates;

                entry.save(published)
                if published:
                    smsg=_('Saved ok. <a href="/blog/%(link)s" target="_blank">View it now!</a>')
                else:
                    smsg=_('Saved ok.')

                vals.update({'action':'edit','result':True,'msg':smsg%{'link':str(entry.link)},'entry':entry})
                self.render2('views/admin/entry.html',vals)
                if published and entry.allow_trackback and self.blog.allow_pingback:
                    try:
                        autoPingback(str(entry.fullurl),HTML=content)
                    except:
                        pass
            elif action=='edit':
                #try:
                if 1:
                    entry=Entry.get(key)
                    entry.title=title
                    entry.content=content
                    entry.slug=entry_slug.replace(' ','-')
                    entry.entry_parent=entry_parent
                    entry.menu_order=menu_order
                    entry.excerpt=entry_excerpt
                    entry.is_external_page=is_external_page
                    entry.target=target
                    entry.external_page_address=external_page_address
                    entry.settags(tags)
                    entry.author=self.author.user
                    entry.author_name=self.author.dispname
                    entry.password=password
                    entry.sticky=sticky
                    newcates=[]

                    if cats:

                        for cate in cats:
                            c=Category.all().filter('slug =',cate)
                            if c:
                                newcates.append(c[0].key())
                    entry.categorie_keys=newcates;
                    entry.allow_comment=allow_comment
                    entry.allow_trackback=allow_trackback

                    entry.save(published)

                    if published:
                        smsg=_('Saved ok. <a href="/blog/%(link)s" target="_blank">View it now!</a>')
                    else:
                        smsg=_('Saved ok.')
                    vals.update({'result':True,'msg':smsg%{'link':str(entry.link)},'entry':entry})

                    self.render2('views/admin/entry.html',vals)

                #except:
                if 0:
                    vals.update({'result':False,'msg':_('Error:Entry can''t been saved.')})
                    self.render2('views/admin/entry.html',vals)
Example #22
0
	def save(self,request):
		entry = Entry(title = self.cleaned_data["title"], content = self.cleaned_data["content"], author = request.user)
		entry.save()
Example #23
0
def submit_post(request):
    published=False
    if request.method == 'POST':
        title = request.POST['title']
        content=request.POST.get('content','')
        excerpt = request.POST.get('excerpt','')
        category_id = request.POST.get("category",1)
        tags = request.POST.get('tags','')
        slug=request.POST.get('slug','')
        allow_comment = request.POST.get('allow_comment',False)
        allow_pingback = request.POST.get('allow_pingback',False)
        action=request.POST.get('action','')
        posttype=request.POST.get('posttype','post')
        sticky=request.POST.get('sticky',False)
        
        sticky= True and sticky=='sticky'
        allow_comment= True and allow_comment == 'open'
        allow_pingback= True and allow_pingback == 'open'
        
        if request.POST.get('publish'):
            published = True
        elif request.POST.get('unpublish'):
            published = False
        else:
            published = request.POST.get('published')=='True'
        
        
        category=Category.objects.get(id=int(category_id))
        
        ctx={'action':action}
        
        if not (title and content):
            ctx.update({'msg':'Please input title and content.'})
            return render_response(request,"admin/post.html",ctx)
        
        if action== 'add':
            entry = Entry(title=title,content=content,excerpt=excerpt,\
                          category=category,slug=slug.replace(" ","-"))
            entry.tags=tags
            entry.allow_comment=allow_comment
            entry.allow_pingback=allow_pingback
            entry.entrytype=posttype
            entry.sticky=sticky
            entry.author=request.user
            if posttype and posttype =='page':
                menu_order=request.POST.get('order',0)
                if menu_order:
                    entry.menu_order=menu_order 
            
            entry.date=datetime.now()
            entry.save(published)
            
            def mapcategoy(cat):
                return  {"id":cat.id,"name":cat.name,\
                         "slug":cat.slug,"select":cat.id == int(category_id)}
            
            ctx.update({'action':'edit','entry':entry,\
                        'entrytype':posttype,'cats':map(mapcategoy,Category.objects.all())})
            
        elif action== 'edit':
            postid = request.POST.get('postid','')
            if postid:
                entry = Entry.objects.get(id=postid)
                entry.tags=tags
                entry.title=title
                entry.content=content
                entry.excerpt=excerpt
                entry.slug=slug.replace(" ","-")
                entry.entrytype=posttype
                entry.sticky=sticky
                entry.category=category
                entry.allow_pingback=allow_pingback
                if posttype and posttype =='page':
                    menu_order=request.POST.get('order',0)
                    entry.menu_order=menu_order
                entry.allow_comment=allow_comment
                entry.save(published)
                def mapcategoy(cat):
                    return  {"id":cat.id,"name":cat.name,"slug":cat.slug,"select":cat.id == entry.category.id}
    
                ctx.update({'action':'edit','entry':entry,\
                    'entrytype':posttype,'cats':map(mapcategoy,Category.objects.all())})
        else:
            pass
        
    return render_response(request,"admin/post.html",ctx)
Example #24
0
 def save(self, request):
     entry = Entry(title=self.cleaned_data["title"],
                   content=self.cleaned_data["content"],
                   author=request.user)
     entry.save()
Example #25
0
def InitBlogData():
	entry=Entry(title=_("Hello world!").decode('utf8'))
	entry.content=_('<p>Welcome to micolog. This is your first post. Edit or delete it, then start blogging!</p>').decode('utf8')
	entry.save(True)
	link=Link(href='http://xuming.net',linktext=_("Xuming's blog").decode('utf8'))
	link.put()