Beispiel #1
0
 def setUp(self):
     self.login()
     self.root_page = Page.objects.get(id=1)
     self.home_page = self.root_page.add_child(instance=HomePage(
         title='New America'))
     self.program_page = self.home_page.add_child(
         instance=Program(title='OTI',
                          name='OTI',
                          description='OTI',
                          location=False,
                          depth=3))
     self.subprogram_page = self.program_page.add_child(instance=Subprogram(
         title='OTI Subprogram',
         name='OTI Subprogram',
         description='OTI Subprogram',
         location=False,
         depth=4,
     ))
     self.program_articles_page = self.program_page.add_child(
         instance=ProgramArticlesPage(title='Program Articles'))
     self.article = self.program_articles_page.add_child(
         instance=Article(title='Article 1', date='2016-02-02'))
     self.subprogram_articles_page = self.subprogram_page.add_child(
         instance=ProgramArticlesPage(title='Subprogram Articles'))
     self.subprogram_article = self.subprogram_articles_page.add_child(
         instance=Article(title='Article 2', date='2016-02-03'))
Beispiel #2
0
def register(request):
    email = request.POST.get('email', '')
    mobile_no = request.POST.get('mobile_no', '')
    confirm_email = request.POST.get('confirm_email', '')
    passwd = request.POST.get('passwd', '')
    confirm_passwd = request.POST.get('confirm_passwd', '')
    country_code = request.POST.get('country_code', '')
    agree = request.POST.get('agree', '')
    p = Article(email = email, confirm_email = confirm_email, passwd = passwd, confirm_passwd = confirm_passwd, country_code = country_code, mobile_no = mobile_no, agree = agree)
    q = Candidate(email=email)
    r = Resume(email=email)
    if Article.objects.filter(email = email).exists():
	return HttpResponseRedirect('/error/')
    else:
	plaintext = get_template('activation.txt')
	htmly = get_template('activation.html')
	a = email.encode('zip')
        b = base64.b64encode(a)
	d = Context({ 'email': email ,'encoded':b})
	text_content = plaintext.render(d)
	html_content = htmly.render(d)
	msg = EmailMultiAlternatives('Registration', text_content, '*****@*****.**', [email])
	msg.attach_alternative(html_content, "text/html")
	msg.send()
	p.save()
	q.save()
	r.save()
	condition = "Registration Successfull, Enter the credentials to login."
        return render_to_response('Signup.html',{ 'cond':condition }, context_instance=RequestContext(request))
Beispiel #3
0
def createArticleId(request):
    try:
        json_req = json.loads(request.body)
        type_id = json_req['type_id']
        user_id = get_userid(json_req['token'])
        login_user = User.objects.get(user_id=user_id)
        # 先查询是否已经存在articleID
        article = Article.objects.filter(user_id=login_user, flag=3, title="")
        # article 已经存在则直接返回
        if article.exists():
            result = {'code': 200, 'article_id': article[0].article_id}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json")
        else:
            article = Article(user_id=login_user, type_id=type_id, flag=3)
            # 保存文章
            article.save()
            result = {'code': 200, 'article_id': article.article_id}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json")
    except:
        return HttpResponse(json.dumps({
            'code': 405,
            'information': '执行异常!'
        }),
                            content_type="application/json")
Beispiel #4
0
def one_to_many_view(reuest):
    # 1.一对多的关联操作
    # article = Article(title='测试标题', content='abc')
    # category = Category.objects.first()
    # author = FrontUser.objects.first()
    #
    # article.category = category
    # article.author = author
    # article.save()

    # 2.获取某个分类下所有文章
    # category = Category.objects.first()
    # # articles = category.article_set.all()
    # articles = category.articles.all()
    # for art in articles:
    #     print(art)

    category = Category.objects.first()
    article = Article(title="ccc", content="ddd")
    article.author = FrontUser.objects.first()
    # article.save()

    category.articles.add(article, bulk=False)
    # category.save()
    return HttpResponse("successfully")
    def test_comments_are_open(self):
        """
        Test that comments can auto close.
        """
        self.assertTrue(Article().comments_are_open,
                        "article should be open for comments")
        self.assertFalse(
            Article(enable_comments=False).comments_are_open,
            "article comments should close")

        # Test ranges
        self.assertTrue(
            Article(
                publication_date=now() -
                timedelta(days=appsettings.FLUENT_COMMENTS_CLOSE_AFTER_DAYS -
                          1)).comments_are_open)
        self.assertFalse(
            Article(
                publication_date=now() -
                timedelta(days=appsettings.FLUENT_COMMENTS_CLOSE_AFTER_DAYS)).
            comments_are_open)
        self.assertFalse(
            Article(
                publication_date=now() -
                timedelta(days=appsettings.FLUENT_COMMENTS_CLOSE_AFTER_DAYS +
                          1)).comments_are_open)
Beispiel #6
0
def add_article(request):
    status, res = process_post(
        request,
        ['identity', 'title', 'content', 'authors', 'editor', 'department'])
    if not status:
        return res
    identity = res['identity']
    title = res['title']
    content = res['content']
    try:
        authors = [Person.objects.get(pk=author) for author in res['authors']]
        editor = Person.objects.get(pk=res['editor'])
    except Exception as e:
        return gen_response(409, f'No such person: {e}')
    try:
        department = Department.objects.get(pk=res['department'])
    except Exception as e:
        return gen_response(409, f'No such department: {e}')
    if not verify_user(identity):
        return gen_response(401, 'Permission denied.')
    article = Article(title=title,
                      content=content,
                      editor=editor,
                      department=department)
    article.save()
    for author in authors:
        article.authors.add(author)
    return gen_response(200, 'Add article successfully.')
Beispiel #7
0
def createArticleId(request):
    json_req = json.loads(request.body)
    token = json_req['token']
    if token == "123456":
        type_id = json_req['type_id']
        try:
            # 获取登录用户ID
            login_user = User.objects.get(user_id=1001)
            # 先查询是否已经存在articleID
            article = Article.objects.filter(user_id=login_user,
                                             flag=3,
                                             title="")
            # article 已经存在则直接返回
            if article.exists():
                result = {'code': 200, 'article_id': article[0].article_id}
                return HttpResponse(json.dumps(result, ensure_ascii=False),
                                    content_type="application/json")
            # 不存在则创建
            else:
                # 创建article对象
                article = Article(user_id=login_user, type_id=type_id, flag=3)
                # 保存文章
                article.save()
                result = {'code': 200, 'article_id': article.article_id}
                return HttpResponse(json.dumps(result, ensure_ascii=False),
                                    content_type="application/json")
        except:
            return HttpResponse(json.dumps({'code': 405}))
    result = {'code': 401}
    return HttpResponse(json.dumps(result, ensure_ascii=False),
                        content_type="application/json")
Beispiel #8
0
    def post(self,request):
        new_article_form = NewArticleForm(request.POST,request.FILES)
        if new_article_form.is_valid():
            image = new_article_form.cleaned_data['image']
            title = request.POST.get('title', '')
            detail = request.POST.get('detail', '')
            author = request.user

            #结巴分词 TextRank 关键词提取
            data = detail
            desc = ''
            tsum = 0
            if len(detail) >= 280:
                for keyword, weight in textrank(data, topK=10, withWeight=True):
                    desc += (keyword+',')

                s = SnowNLP(detail)
                for sentence in s.sentences:
                    tsum += float(SnowNLP(sentence).sentiments) - 0.5

            new_article = Article()
            new_article.author = author
            new_article.title = title
            new_article.image = image
            new_article.desc = desc
            new_article.detail = detail
            new_article.score = tsum
            new_article.save()
            return render(request, 'success.html')
        else:
            return render(request, 'failed.html')
Beispiel #9
0
def write_article(request):
    if request.method == 'GET':
        # 调用写博客表单
        aform = ArticleForm()
        return render(request, 'article/write.html', context={'form': aform})
    else:
        # 接受用户提交的数据
        aform = ArticleForm(request.POST, request.FILES)
        # 判断数据是否存在
        if aform.is_valid():
            # cleaned_data中保存了用户所有提交了的数据
            # 1对多 直接赋值
            data = aform.cleaned_data
            article = Article()
            article.title = data.get('title')
            article.desc = data.get('desc')
            article.content = data.get('content')

            article.image = data.get('image')
            article.desc = data.get('desc')
            article.user = request.user
            article.save()

            # 多对多 必须添加到文章保存的后面添加
            article.tags.set(data.get('tags'))
            # 保存成功后重定向到首页
            return redirect(reverse('index'))

        # 数据不正确重定向,继续填写
        return render(request, 'article/write.html', context={'form': aform})
Beispiel #10
0
def add_article_views(request):
    if request.method == "GET":
        return render(request, 'addArticle.html')
    else:
        try:
            articleAuthor = request.POST['author']
            articleTitle = request.POST['title']
            articleComment = request.POST['content']
            articleColumn = request.POST['column']
            if articleAuthor and articleTitle and articleComment and articleColumn:
                article = Article(article_author=articleAuthor,
                                  article_title=articleTitle,
                                  article_column=articleColumn,
                                  article_comment=articleComment,
                                  article_views_count=0,
                                  article_update_time=datetime.now())
                # article.switch_collection('article_more') # 切换集合,此用法需谨慎

                article.save()

        # with switch_collection(Article,'article_more') as Article_More:
        #   article = Article_More(name='Thomson', title='Phone Development', comment='python进阶教程')#切换集合
        #   article.save()
            sussOrFail = 200
            return render(request, 'addArticle.html', status=sussOrFail)

        except Exception as e:
            sussOrFail = 404
            printlog.err(e)
            return render(request, 'addArticle.html', status=sussOrFail)
Beispiel #11
0
def compose(request):
    if request.user.is_authenticated:
        if request.method == "POST":
            form = Post(request.POST)
            if form.is_valid():
                name = form.cleaned_data['name']
                content = form.cleaned_data['article']
                time = datetime.datetime.now()
                method = 'article'
                username = request.user.username
                text = "%s has posted an article on %s" % (username, name)
                p = Feed(user=username, time=time, method=method, content=text)
                p.save()
                user = User.objects.get(id=request.user.id)
                profile = Profile.objects.get(user=user)
                a = Article(profile=profile,
                            name=name,
                            time=time,
                            content=content)
                a.save()
                return redirect('/')

        else:
            form = Post()
            return render(request, 'article/post.html', {
                'form': form,
                'title': 'Post'
            })

    else:
        return redirect('/login')
Beispiel #12
0
def index(request):
    article = Article(title='abc', content='1111')
    category = Category(name="最新文章")
    category.save()
    article.category = category
    article.save()
    return HttpResponse("success")
Beispiel #13
0
def write_article(request):
    if request.method == 'GET':
        aform = ArticleForm()
        return render(request, 'article/write.html', context={'form': aform})
    else:
        aform = ArticleForm(request.POST, request.FILES)
        if aform.is_valid():
            # cleaned_data就是读取表单返回的值,返回类型为字典dict型
            data = aform.cleaned_data
            article = Article()
            article.title = data.get('title')
            article.desc = data.get('desc')
            article.content = data.get('content')
            print(type(data.get('image')))

            article.image = data.get('image')
            article.desc = data.get('desc')
            article.user = request.user  # 1对多 直接赋值
            article.save()

            # 多对多 必须添加到文章保存的后面添加
            article.tags.set(data.get('tags'))
            return redirect(reverse('index'))

        return render(request, 'article/write.html', context={'form': aform})
Beispiel #14
0
def editArticle(request, pk=0):
    context = getBaseContext()
    if pk == 0:
        art = Article(author=request.user, title='новая статья')
        art.pk = 0
    else:
        art = Article.objects.get(pk=pk)
        tags = [t.title for t in art.tag.all()]
        art.taglist = ','.join(tags)
    if request.method == 'GET':
        context.update({'pk': art.pk, 'art': art, 'arttags': art.tag.all()})
        return render(request, 'article-edit.html', context)
    if request.method == 'POST':
        if pk == 0:
            art = Article.objects.create(author=request.user,
                                         title='новая статья')
        catname = request.POST.get('category')
        category, _ = Category.objects.get_or_create(title=catname)
        art.tag.clear()
        for tagname in request.POST.get('tag').split(','):
            if len(tagname) > 0:
                tag, _ = Tag.objects.get_or_create(title=tagname)
                art.tag.add(tag)
        art.author = request.user
        art.title = request.POST.get('title')
        art.post = request.POST.get('post')
        art.category = category
        art.save()
        return redirect('kb', pk=art.pk)
Beispiel #15
0
def add(request):
    if request.method == "POST":
        content = request.POST.get('content',None)
        title = request.POST.get('title',None)
        new = Article(content = content, title = title)
        new.save()
    return render_to_response('add.html',{'method_str':request.method})
Beispiel #16
0
 def post(self, request):
     article_form = AddArticleForm(request.POST, request.FILES)
     user = request.user
     if 'cover_img' in request.FILES:
         article = Article()
         tittle = request.POST.get('title', '')
         content = request.POST.get('editor1', '')
         cover_img = request.FILES['cover_img']
         category_id = request.POST.get('category', '')
         label = request.POST.get('tags', '')
         if category_id:
             category = Category.objects.get(pk=category_id)
             article.Article_Category = category
             category.Article_Num = int(category.Article_Num) + 1
             category.save()
         article.Tittle = tittle
         article.Content = content
         article.Cover_img = cover_img
         article.Author = user
         article.Label = label
         article.save()
         articles = Article.objects.filter(Author=user)
         return render(request, 'center/article.html', {'articles': articles})
     else:
         now = datetime.now()
         category = Category.objects.filter(User=user)
         return render(request, 'center/add-article.html', {'now': now, 'category': category})
Beispiel #17
0
def add(request):
    if request.method == "POST":
        content = request.POST.get('content',None)
        title = request.POST.get('title',None)
        new = Article(content = content, title = title)
        new.save()
    return render_to_response('add.html',{'method_str':request.method})
Beispiel #18
0
def add_return(request):
    img = request.FILES["docfile"]
    username = request.session['username']
    tit = request.POST['title']
    cate = request.POST['category']
    cont = request.POST['content']
    #need cookie to identify
    #dt = datetime.datetime.now() default is now!'''
    a = Article(title=tit,
                category=cate,
                content=cont,
                username=username,
                image=img)
    a.save()
    content = {
        'title': tit,
        'category': cate,
        'datetime': datetime.datetime.now(),
        'content': cont,
        'username': username,
        'url': a.image.url,

        #still need to add username here
    }
    return render(request, "add_success.html", content)
Beispiel #19
0
def article_create(request, block_id):
    block_id = int(block_id)
    if request.method == "GET":
        return render(request, 'article_create.html', {
            "b": block,
            "error": error
        })
    else:
        title = request.POST.get("title").strip()
        content = request.POST.get("content").strip()
        if not title or not content:
            return render(
                request, "article_create.html", {
                    "b": block_id,
                    "error": "标题和内容不能为空",
                    "title": title,
                    "content": content
                })
        if len(title) > 100 or not len(content) > 100000:
            return render(request, "article_create.html", {
                "b": block_id,
                "error": "标题和内容太长"
            })
        add_article = Article(block_id=block_id,
                              title=title,
                              owner=request.user,
                              content=content,
                              status=0)
        add_article.save()
        article_infos = Article.objects.filter(block=block_id).order_by("-id")
        return render(request, 'article_list.html', {
            "articles": article_infos,
            "b": block_id
        })
Beispiel #20
0
def write(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        try:
            email = request.session['email']
            # select * from user where email = ?
            user = User.objects.get(email=email)

            #######################################
            upload_file = request.FILES['upload_file']
            # 파일 저장
            # file = open('', '')
            # file.write('내용')
            file_name = upload_file.name
            # 만약 파일명이 중복되었다면.. image.jpg
            idx = file_name.find('.')
            file1 = file_name[0:idx]  # image
            file2 = file_name[idx:]  # .jpg
            sep = time.time()  # unix time 밀리세컨드
            file_name = file1 + str(sep) + file2

            with open('article/static/' + file_name, 'wb') as file:
                for chunk in upload_file.chunks():
                    file.write(chunk)
            #######################################

            # insert into article (title, content, user_id) values (?, ?, ?)
            article = Article(title=title, content=content, user=user)
            article.file_name = '/static/' + file_name
            article.save()
            return render(request, 'write_success.html')
        except:
            return render(request, 'write_fail.html')
    return render(request, 'write.html')
Beispiel #21
0
    def handle(self, *args, **options):
        user = User.objects.get(id=1)
        cate = Category.objects.get(id=1)

        #指定新文章的保存路径
        markdowndir = "/data/PythonBlog/itblog/markdown/"
        mdlist = os.listdir(markdowndir)
        for filename in mdlist:
            #print(filename)
            #print(filename.split(".")[0])

            # 创建一个文章对象
            article = Article()
            article.title = filename.split(".")[0]

            # 文章作者,默认就是cui用户
            article.author = user

            # 文章的分类,如果存在就保存到之前的里面,如果是新的分类就创建一个分类

            article.category = cate
            article.brief = filename
            article.avatar = "article/20190809/150H2092042-1.jpg"

            with open(markdowndir + filename, 'r') as f:
                article.body = f.read()

            article.save()

            self.stdout.write(self.style.SUCCESS('Successfully create article %s' % article.title ))

            move_file(markdowndir,"/data/historymd/",filename)
Beispiel #22
0
    def setUp(self):
        self.login()
        site = Site.objects.get()
        page = Page.get_first_root_node()
        home = HomePage(title='New America')
        self.home_page = page.add_child(instance=home)

        site.root_page = home
        site.save()

        self.our_people_page = self.home_page.add_child(
            instance=OurPeoplePage(title='Our People', depth=3))
        self.program_page = self.home_page.add_child(
            instance=Program(title='OTI',
                             name='OTI',
                             description='OTI',
                             location=False,
                             depth=3))
        self.second_program = self.home_page.add_child(
            instance=Program(title='Education',
                             name='Education',
                             slug='education',
                             description='Education',
                             location=False,
                             depth=3))
        self.subprogram_page = self.program_page.add_child(
            instance=Subprogram(title='OTI Subprogram',
                                name='OTI Subprogram',
                                description='OTI Subprogram',
                                location=False,
                                depth=4))
        self.second_subprogram_page = self.program_page.add_child(
            instance=Subprogram(title='OTI Subprogram 2',
                                name='OTI Subprogram 2',
                                description='OTI Subprogram 2',
                                location=False,
                                depth=4))
        self.program_articles_page = self.program_page.add_child(
            instance=ProgramArticlesPage(title='Program Articles'))
        self.test_person = Person(
            title='Sana Javed',
            slug='sana-javed',
            first_name='Sana',
            last_name='Javed',
            role='Central Staff',
            depth=4,
        )
        self.our_people_page.add_child(instance=self.test_person)
        self.test_person.save()

        self.article = self.program_articles_page.add_child(
            instance=Article(title='Article 1', date='2016-02-02'))
        PostAuthorRelationship(author=self.test_person,
                               post=self.article).save()

        self.article_2 = self.program_articles_page.add_child(
            instance=Article(title='Article 2', date='2016-05-02'))
        PostAuthorRelationship(author=self.test_person,
                               post=self.article_2).save()
Beispiel #23
0
def search_return(request):
    tit = request.GET['title']
    cate = request.GET['category']
    con = request.GET['content']
    a = Article(title=tit, category=cate, content=con)
    a.save()
    content = {"tit": tit, "cate": cate, "con": con, "ret": request.GET['q']}
    return render(request, "search_return.html", content)
Beispiel #24
0
 def clean(self):
     super(ArticleModelForm, self).clean()
     try:
         article = Article(**self.cleaned_data)
         article.save()
     except Exception:
         raise forms.ValidationError(_("Correct the form below"))
     return self.cleaned_data
Beispiel #25
0
def ont_to_many_view(request):
    article = Article(title="钢铁是怎样炼成的",content="士大夫十分后和")
    users = FrontUser(username="******")

    users.save()
    article.author = users
    article.save()
    return HttpResponse()
Beispiel #26
0
 def clean(self):
     super(ArticleModelForm, self).clean()
     try:
         article = Article(**self.cleaned_data)
         article.save()
     except Exception:
         raise forms.ValidationError(_("Correct the form below"))
     return self.cleaned_data
def get_one(article_external_id):
    article = Article.get_by_external_id(article_external_id)
    if not article:
        article = Article(external_id=article_external_id)
        article.save()

    data = article_schema.dump(article).data
    return custom_response(data, 200)
Beispiel #28
0
 def test_was_createdTime_recently_with_future_article(self):
     author = User(username='******', password='******')
     author.save()
     future_article = Article(author=author,
                              title='test1',
                              body='test1',
                              createdTime=timezone.now() +
                              datetime.timedelta(days=30))
     self.assertIs(future_article.was_createdTime_recently(), False)
Beispiel #29
0
 def test_was_createdTime_recently_with_seconds_before_article(self):
     author = User(username='******', password='******')
     author.save()
     seconds_before_article = Article(author=author,
                                      title='test2',
                                      body='test2',
                                      createdTime=timezone.now() -
                                      datetime.timedelta(seconds=45))
     self.assertIs(seconds_before_article.was_createdTime_recently(), True)
Beispiel #30
0
 def test_was_published_recently_with_future_article(self):
     """
     was_published_recently() should return False for articles whose
     pub_date is in the future.
     """
     time = timezone.now() + datetime.timedelta(days=30)
     
     future_article = Article(article_date=time,article_text="Future text", article_title="Future title")
     self.assertEqual(future_article.was_published_recently(), False)
Beispiel #31
0
def add(request):
    if request.method == "POST":
        title = request.POST.get("title", "")
        content = request.POST.get("content", "")
        author = request.POST.get("author", "")
        a = Article(title=title, content=content, author=author)
        a.save()
        return redirect('/article/list')
    else:
        return render(request, 'article/add.html')
Beispiel #32
0
def article_comment_add(self, article_id, number=1):
    """
        文章评论增加
    :param self:
    :param article_id:
    :param number:
    :return:
    """
    Article.article_comment_add(article_id=article_id, number=number)
    return number
Beispiel #33
0
def add(request):
	if request.method == 'POST':
		title = request.POST.get('title', '')	
		author = request.POST.get('author', '')
		description = request.POST.get('description', '')
		content = request.POST.get('content', '')
		new = Article(title=title, author=author, description=description, content=content)		
		new.save()
		return HttpResponseRedirect('/manage')
	return render_to_response('article.add.html')
Beispiel #34
0
def article_comment_reduce(self, article_id, number=1):
    """
        文章评论减少
    :param self:
    :param article_id:
    :param number:
    :return:
    """
    Article.article_comment_reduce(article_id=article_id, number=number)
    return number
Beispiel #35
0
def article_visit_add(self, user_id, article_id: int):
    """
        用户访问文章
    :param user_id: 用户ID
    :param article_id: 文章ID
    :return:
    """
    Article.visited_article(article_id)
    visit_article_log(user_id=user_id, article_id=article_id)
    return 1
def search_return(request):
	tit = request.GET['title']
	cate = request.GET['category']
	con = request.GET['content']
	a = Article(title=tit,category=cate,content=con)
	a.save()
	content = {
	 "tit" : tit,
	 "cate":cate,
	 "con" :con,
	 "ret" : request.GET['q']}
	return render(request,"search_return.html",content)
Beispiel #37
0
def submit(request):

  if request.method == "POST":
    form = forms.Submit(request.POST)
    if form.is_valid():
      article = Article()
      article.title = form.cleaned_data["title"].strip()
      article.author = form.cleaned_data["author"].strip()
      article.email = form.cleaned_data["email"].strip()
      article.content = form.cleaned_data["content"]
      article.coverletter = form.cleaned_data["coverletter"]
      article.save()
      submitted_page = get_object_or_404(Page, title="Article Submitted")
      return HttpResponseRedirect(submitted_page.url())
  else: # "GET"
    form = forms.Submit()

  guidelines = get_object_or_404(Page, title="Submission Guidelines")
  templatearguments = {
    "generic_form" : {
      "title" : "Submit Article",
      "markdown_info" : guidelines.content,
      "form" : form,
      "cancel_url" : "/",
    }
  }
  return render(request, 'common/submit.html', templatearguments)
Beispiel #38
0
 def get_resent_feature(self):
     from article.models import ArticleUnlike, Article
     read_article_logs = UserReadLog.objects(user_id=str(self.id)).order_by('-id')[:25]
     unlike_article_logs = ArticleUnlike.objects(author_id=str(self.id)).order_by('-id')[:5]
     read_article_ids = [log.article_seq_id for log in read_article_logs]
     unlike_article_ids = [log.article_id for log in unlike_article_logs]
     read_articles = Article.objects(seq_id__in=read_article_ids)
     unlike_articles = Article.objects(id__in=unlike_article_ids)
     feature = None
     for article in read_articles:
         feature = article.feature_matrix if feature is None else feature + article.feature_matrix
     for article in unlike_articles:
         feature = -1 * article.feature_matrix if feature is None else feature - article.feature_matrix
     return feature
Beispiel #39
0
def populate():
    print('Populating articles and comments ... ', end='')
    Article.objects.all().delete()
    Comment.objects.all().delete()

    for title in titles:
        article = Article()
        article.title = title
        for j in range(20):
            article.content += title + '\n'
        article.save()
        for comment in comments:
            Comment.objects.create(article=article, content=comment)
    print('done')
Beispiel #40
0
def add_articles(request):
	data={}
	data['articles'] = Article.objects.all() 
	if request.method == 'POST':
		if not request.POST.get('title',False):
			title= ""
		article = Article(title=title,photo=request.FILES['file'])
		article.save()
		result = {"file":article.photo.url}
		response = JSONResponse(result, {}, response_mimetype(request))
		response['Content-Disposition'] = 'inline; filename=files.json'
		return response
		#return HttpResponse(json.dumps(result))
		#return HttpResponseRedirect(reverse('articles'))
	return render_to_response('article/articles.html',data, context_instance=RequestContext(request))
Beispiel #41
0
 def parse(self, response):
     url = response.url
     links = self.extract_urls(response)
     article_urls = []
     subindexes = []
     subindex_urls = SiteRule.get_subindex_urls_by_url(url)
     patterns = Site.get_article_patterns(url)
     for link in links:
         if link.url in subindex_urls:
             subindexes.append(link.url)
         else:
             for pattern in patterns:
                 if re.match(pattern, link.url.strip()):
                     article_urls.append(link.url)
     if subindexes:
         self.server.rpush(SUB_INDEX_WORKER_KEY, *set(subindexes))
     if article_urls:
         articles = Article.objects(source_url__in=article_urls)
         exsited_article_urls = [article.source_url for article in articles]
         new_urls = set(article_urls) - set(exsited_article_urls)
         if new_urls:
             self.server.rpush(TOP_LEVEL_ARTICLES_WORKER_KEY, *set(new_urls))
             name = Site.get_name_by_url(url)
             Article.objects.insert([Article(source_url=article_url, source='Home',
                         site_name=name, site_url=url, category=['Top Stories']) \
                                 for article_url in set(new_urls)])
Beispiel #42
0
def main():
    articles = Article.objects(usable=True)
    for article in articles:
        article.warm()
    users = User.objects.all()
    for u in users:
        u.warm()
Beispiel #43
0
def article_edit(request, article_id):
    """If the user has rights, he will be able to edit and save.
    Otherwise, he will be redirected to need_login page."""

    article = Article.get_by_id(int(article_id))

    if users.get_current_user().email() != article.author:
        return HttpResponseRedirect('/need_login/')

    else:
        if request.method == 'GET':
            c = {}
            c.update(csrf(request))
            # Give user details to template.
            _user_manage(c)
            post_url = '/article/edit/' + article_id + '/'
            # Set post url.
            c['form'] = {'action': post_url}
            # Get the article and populate the form.
            c['article'] = article

            return render_to_response('edit_article.html', c)

        elif request.method == 'POST':
            # Modify the article.
            article.title = request.POST.get('title', 'untitled')
            article.body = request.POST.get('new_content', 'no content')
            # Save it.
            article.put()

            return HttpResponseRedirect('/article/' + article_id + '/')
Beispiel #44
0
def create_article(request, block_id):
    block_id=int(block_id)
    block=Block.objects.get(id=block_id)
    if request.method=="GET":
        return render_to_response("article_create.html", {"b":block}, context_instance=RequestContext(request))
    else: #request.method=="post"
        title=request.POST["title"].strip()
        content=request.POST["content"].strip()
        if not title or not content:
            messages.add_message(request,messages.ERROR,u'标题和内容均不能为空')
            return render_to_response("article_create.html", {"b":block,"title":title,"content":content},context_instance=RequestContext(request))
        owner=User.objects.all()[0]#TODO
        new_article=Article(block=block,owner=request.user,title=title,content=content)
        new_article.save()
        messages.add_message(request,messages.INFO,u'成功发布文章')
        return redirect(reverse("article_list",args=[block.id]))
Beispiel #45
0
def save_article(request):
    error_msg = ''
    articleID = request.POST.get('articleID', '').strip()
    save_type = request.POST.get('type', '').strip()  # save or submit
    col = request.POST.get('col', '').strip()
    title = request.POST.get('title', '').strip()
    content = request.POST.get('content', '').strip()

    if title == '':
        error_msg = u'标题不能为空'
        return HttpResponse(json.dumps({'status': 'fail', 'error_msg': error_msg}))

    try:
        col = Col.objects.get(name=col)
    except Exception as e:
        error_msg = str(e)
        return HttpResponse(json.dumps({'status': 'fail', 'error_msg': error_msg}))

    if articleID:
        try:
            if request.user==Article.objects.get(id=articleID).author:
                article = Article.objects.get(id=articleID)
                article.title = title
                article.content = content
                article.col = col
                article.save()
            else:
                error_msg=u'对不起,你无权修改他人文章'
                return HttpResponse(json.dumps({'status': 'fail', 'error_msg': error_msg}))
        except Exception as e:
            error_msg = str(e)
    else:
        try:
            author = Author.objects.get(email=request.user.email)
            article = Article(
                author=author, col=col, title=title, content=content,num_praise=0,num_comment=0)
            article.save()
        except Exception as e:
            error_msg = str(e)

    if error_msg:
        return HttpResponse(json.dumps({'status': 'fail', 'error_msg': error_msg}))

    articleID = article.id
    return HttpResponse(json.dumps({'status': 'ok', 'articleID': articleID, 'error_msg': error_msg}))
Beispiel #46
0
 def _gen_requests(self, urls):
     for url in urls:
         rss_url = normalize_url(url)
         articles = Article.objects(rss_url=rss_url)
         if articles:
             continue
         ua = random.choice(USER_AGENT_LIST)
         headers = {'User-Agent': ua}
         yield grequests.get(url, headers=headers)
Beispiel #47
0
 def get_user_last_seen(cls, user):
     logs = cls.objects(user_id=str(user.id)).order_by('-id')
     if not logs:
         return None
     from article.models import Article
     articles = Article.objects(seq_id=logs[0].article_seq_id)
     if not articles:
         return None
     return articles[0]
def main():
    try:
        useless_articles = Article.calcualte_useless_articles()
        users = User.objects.only('id', 'seq_id')
        users = [default_key_user] + list(users)
        for u in users:
            u.remove_articles_from_candidateset(useless_articles)
    except:
        sentry_exception_handler()
Beispiel #49
0
def register(request):
    email = request.POST.get('email', '')
    mobile_no = request.POST.get('mobile_no', '')
    confirm_email = request.POST.get('confirm_email', '')
    passwd = request.POST.get('passwd', '')
    confirm_passwd = request.POST.get('confirm_passwd', '')
    country_code = request.POST.get('country_code', '')
    agree = request.POST.get('agree', '')
    p = Article(email = email, confirm_email = confirm_email, passwd = passwd, confirm_passwd = confirm_passwd, country_code = country_code, mobile_no = mobile_no, agree = agree)
    q = Candidate(email=email)
    r = Resume(email=email)
    if Article.objects.filter(email = email).exists():
	return HttpResponseRedirect('/error/')
    else:
	p.save()
	q.save()
	r.save()
        return HttpResponseRedirect('/signup/')
Beispiel #50
0
def article_delete(request, article_id):
    """We check if the user has rights to delete, and we delete."""

    article = Article.get_by_id(int(article_id))
    if users.get_current_user().email() != article.author:
        return HttpResponseRedirect('/need_login/')
    else:
        article.delete()
        return HttpResponseRedirect('/article/all/')
Beispiel #51
0
def md2sql(title, category, tags, content):
    # backup database file
    shutil.copyfile(sfile, sfile + '.bak')

    try:
        a = Article(title=title, category=category, content=content)
        a.save() # 执行下面之前要先保存
        for t in tags:
            try:
                tag = Tag.objects.get(tag__iexact=t)
            except:
                tag = Tag(tag=t)
                tag.save() # 执行下面之前要先保存

            a.tags.add(tag)
        a.save()
    except:
        print '--!Error: Failed write file into db.sqlite3!--'
        shutil.copyfile(sfile + '.bak', sfile)
Beispiel #52
0
def main():
    now = datetime.datetime.utcnow()
    valid_time = now - VALID_DURATION
    mul = 0
    articles = Article.objects(published_at__gt=valid_time, usable=True)
    for pubdate, _articles in groupby(sorted(articles, key=lambda x: x.published_at.date(), reverse=True), lambda x: x.published_at.date()):
        sorted_articles = sorted(_articles, key=calculate, reverse=True)
        count = len(sorted_articles)
        print pubdate, count, int(count * 0.75**mul)
        for article in sorted_articles[:int(count * 0.75**mul)]:
            article.warm()
        mul+=1
Beispiel #53
0
def edit_article(request, article_id=0):
    if request.method == 'POST':
        form = EditArticleForm(request.POST, request.FILES)

        if form.is_valid():

            author = request.user.author
            date = timezone.now()
            title = form.cleaned_data['title']
            is_beta = form.cleaned_data['is_beta']
            text = form.cleaned_data['text']
            category = form.cleaned_data['category']
            image = form.cleaned_data['image']

            if article_id == 0:
            	e = Event(name=title, pub_date=date, category=category, image=None)

            	a = Article(event=e, author=author, is_beta=is_beta, text=text)
            else:
            	a = get_object_or_404(Article, pk=article_id)
            	if image is None:
            		image = a.event.image
            	e = a.event
                if author != a.author and author not in a.modifiers.all():
            	   a.modifiers.add(author)
            	a.is_beta = is_beta
            	a.text = text
            	e.name = title
            	e.pub_date = date
            	e.category = category
            	e.image = image
            	a.event = e

            e.save()
            a.save()



            return HttpResponseRedirect(a.get_absolute_url())
    else:
    	if article_id == 0:
        	form = EditArticleForm()
        else:
        	a = get_object_or_404(Article, pk=article_id)
    		form = EditArticleForm(initial={'title':a.event.name,
    										'image':a.event.image,
    										'category':a.event.category,
    										'is_beta':a.is_beta,
    										'text':a.text})
    if article_id == 0:
    	send_to = '/article/new/'
    else :
    	send_to = '/article/edit/' + article_id + '/'
    
    return render(request, 'article/edit.html', locals())
Beispiel #54
0
def saveArticle( request ):
    imgs = None
    if request.FILES.has_key('imgs'):
        imgs = request.FILES.getlist('imgs')
    article = Article.saveArticle(request.POST.get('id', None)
                              , request.POST['title']
                              , request.POST['desc']
                              , request.POST['tags']
                              , request.POST['content']
                              , imgs )
    if article.id == 0:
        return redirect('/about')
    return redirect('/article/' + str( article.id ))
def add_return(request):
	img = request.FILES["docfile"]
	username = request.COOKIES['name']
	tit = request.POST['title']
	cate = request.POST['category']
	cont = request.POST['content']

	#need cookie to identify 
	#dt = datetime.datetime.now() default is now!'''
	a = Article(title=tit,category=cate,content=cont,username=username,image=img)
	a.save()
	content = {
	  'title':tit,
	  'category':cate,
	  'datetime':datetime.datetime.now(),
	  'content': cont,
	  'username':username,
	  'url':a.image.url,

	  #still need to add username here
	}
	return render(request,"add_success.html",content)
Beispiel #56
0
def ansItem2artical(ansItem):
    article = Article()
    article.title = ansItem.qTitle
    article.author = ansItem.authorWithHeadLine
    article.category = '网页设计'
    article.content = ansItem.content
    article.url = ansItem.url
    return article
Beispiel #57
0
def article_detail(request, article_id):
    """Shows one article."""

    # Get the article.
    article = Article.get_by_id(int(article_id))

    # Fill the context.
    c = {}
    c['article'] = article

    # Deal with login.
    _user_manage(c)

    return render_to_response("article.html", c)
Beispiel #58
0
 def update_candidateset(self):
     full_warm_seq_ids = self.get_full_dataset()
     from article.models import Article
     articles = Article.objects(seq_id__in=full_warm_seq_ids).only('id', 'category', 'seq_id', 'feature', 'published_at', 'quality', 'hot')
     now = datetime.datetime.utcnow()
     update_time = self.candidate_updated_time
     if not update_time:
         update_time = get_global_cal_time()
     seq_id_article_mapping = dict(((a.seq_id, (a, calculate_scores(0, 0, a.published_at, a.quality, a.hot, update_time, now))) for a in articles))
     short_feature = self.get_feature_by_name('recent_feature')
     long_feature = self.feature_matrix
     User.recompute_candidateset(self, short_feature, long_feature, seq_id_article_mapping, subset=full_warm_seq_ids)
     update_time = datetime.datetime.utcnow()
     self.candidate_updated_time = update_time
     self.save()
def main():
    usable_ids = warm_conn.keys('b:s:a*')
    usable_ids = map(lambda _id: int(_id.split(':')[-1]), usable_ids)
    articles = Article.objects(seq_id__in=usable_ids).only('seq_id', 'id', 'category', 'hot', 'quality', 'published_at', 'feature')
    update_time = datetime.datetime.utcnow()
    set_global_cal_time(update_time)
    seq_id_article_mapping = dict(((a.seq_id, (a, calculate_scores(0, 0, a.published_at, a.quality, a.hot, update_time, update_time))) for a in articles))
    User.recompute_common_candidateset(usable_ids, seq_id_article_mapping)
    users = User.objects.only('id', 'seq_id', 'feature', 'recent_feature', 'feature_updated_time', 'candidate_updated_time').all()
    usable_ids_set = set(usable_ids)
    for user in users:
        ids, _ = user.get_seen_article_ids_and_last_datetime()
        _usable_ids = usable_ids_set - set(ids)
        print user, user.seq_id, len(_usable_ids)
        short_feature, long_feature, _ = user.update_warm_feature()
        User.recompute_candidateset(user, short_feature, long_feature, seq_id_article_mapping, subset=_usable_ids)
Beispiel #60
0
	def setUp(self):
		self.OLD_TEMPLATES = settings.TEMPLATES
		settings.TEMPLATES = (('desktop', ('default',),),)
		category = Category(name = "t", slug = "t")
		category.save()
		article = Article()
		article.category = category
		article.published = True
		article.title = "Article title"
		article.slug = "article"
		article.save()
		self.article = article
		self.browser = webdriver.Firefox()
		self.browser.implicitly_wait(5)