Python爬蟲實戰(zhàn)筆記_4-2 Django Paginator

練習(xí)Django Paginator的使用使頁面更整潔。
第一階段

首先要做的是搭建整個框架徘六,包括如何連接數(shù)據(jù)庫戈锻,如何應(yīng)用model 以及Django Template Language的使用锡移。

  1. 命題作文第一步當(dāng)然要研究清楚命題。瀏覽器中打開代碼檢查器查看頁面結(jié)構(gòu)倘潜,提取出需要準(zhǔn)備的信息,到models.py中定義自己的模式:
class ArticleList(Document):
    subject = StringField() # article subject
    author = StringField() # the author
    portrait = StringField() # a pic url of the author
    images = ListField(StringField()) # urls of images used in the article
    categories = ListField(StringField()) # tags of the article
    description = StringField() # the description of the article
    
    meta = {
        'collection': 'artiinfo' 
    }
  1. 準(zhǔn)備數(shù)據(jù)志于。按照第一步中取出的數(shù)據(jù)模式新建數(shù)據(jù)表'artiinfo'涮因。
    例子中第三篇文章的描述信息是兩張圖片,處理與其它文章不同恨憎,先把它放一邊蕊退,只處理純文字的文章。
authorlist = ['Tilo Mitra', 'Eric Ferra', 'Reid Burke', 'Andrew Wooldridge']
portraitlist = ['img/common/tilo-avatar.png', 'img/common/ericf-avatar.png', 'img/common/reid-avatar.png', 'img/common/andrew-avatar.png']
imageslist = [[], [],['http://farm8.staticflickr.com/7382/8907351301_bd7460cffb.jpg', 'http://farm8.staticflickr.com/7448/8915936174_8d54ec76c6.jpg'], []]
categorylist = [['CSS', 'Pure'], ['JavaScript'], [], ['YUI']]
description = ['Yesterday at CSSConf, we launched Pure – a new CSS library. Phew! Here are the slides from the presentation. Although it looks pretty minimalist, we’ve been working on Pure for several months. After many iterations, we have released Pure as a set of small, responsive, CSS modules that you can use in every web project.','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.','','We are happy to announce the release of YUI 3.10.2! You can find it now on the Yahoo! CDN, download it directly, or pull it in via npm. We’ve also updated the YUI Library website with the latest documentation.']
titlelist = ['Introducing Pure', 'Everything You Need to Know About Grunt', 'Photos from CSSConf and JSConf', 'YUI 3.10.2 Released']

將上面準(zhǔn)備好的數(shù)據(jù)插入數(shù)據(jù)表'blog.artiinfo'

  1. 準(zhǔn)備靜態(tài)資源憔恳,css, img等
    將網(wǎng)頁中用到的圖片資源瓤荔,css文件放到static目錄下,并在settings.py中指定引用路徑钥组。
  2. 定義model输硝, 連接mongodb
    settings.py中添加連接mongodb的代碼
from mongoengine import connect
connect('blog', host='127.0.0.1', port=27017)

Tip: model中的變量要與引用的數(shù)據(jù)表中的數(shù)據(jù)一一對應(yīng),名字也要完全相同程梦,且一個不能多也一個不能少点把。切記!切記屿附!

class ArticleList(Document):
    subject = StringField()
    author = StringField()
    portrait = StringField()
    images = ListField(StringField())
    categories = ListField(StringField())
    description = StringField()

    meta = {
        'collection': 'artiinfo'
    }
  1. 在views.py中應(yīng)用定義的model
# Create your views here.
def menublog(request):
    info = ArticleList.objects
    context = {'artiinfo': info}
    return render(request, 'index.html', context)
  1. 編輯templates
{% load static %}
......
                {% for item in artiinfo %}
                <section class="post">
                    <header class="post-header">
                        <img class="post-avatar" alt="Eric Ferraiuolo's avatar" height="48" width="48" src="">

                        <h2 class="post-title">{{ item.subject }}</h2>

                        <p class="post-meta">
                            By <a class="post-author" href="#">{{ item.author }}</a> under
                            {% for ia in item.categories %}
                            <a class="post-category post-category-js" href="#">{{ ia }}</a>
                            {% endfor %}
                        </p>
                    </header>
                    <div class="post-description">
                        <p>
                            {{ item.description }}
                        </p>
                    </div>
                </section>
                {% endfor %}
......

第一階段完成郎逃。
目前為止處理了文字相關(guān)的部分。作者的頭像尚未加載挺份。
除此之外褒翰,還有三個需要優(yōu)化的問題:

  1. 標(biāo)簽的顏色與標(biāo)簽內(nèi)容相關(guān)。
    示例頁面中標(biāo)簽'CSS'的背景色為綠色匀泊,查看網(wǎng)頁源碼發(fā)現(xiàn)其class="post-category post-category-design"优训;標(biāo)簽'Pure'的背景色為藍(lán)色,class="post-category post-category-pure"各聘。'post-category-design'與'post-category-pure'這兩個class在CSS中被定義為不同的背景色揣非。
    數(shù)據(jù)表中保存的標(biāo)簽信息并沒其對應(yīng)的class信息,只有文字:
    categorylist = [['CSS', 'Pure'], ['JavaScript'], [], ['YUI']]
    那么如何做匹配呢躲因? 如何為各個標(biāo)簽指定對應(yīng)的class早敬。

  2. 四篇文章中有一篇的description是兩張圖片,其它都是文字描述大脉。需要在templates中添加代碼做相應(yīng)的判斷搁嗓,是圖片則顯示圖片,只有文字則顯示文字箱靴。

  3. 示例頁面中,文章分為置頂?shù)呐c最近發(fā)布的兩類荷愕,為了簡化在第一階段的學(xué)習(xí)中衡怀,把所有文章都加在最近發(fā)布的類別下面棍矛。 后面會為各文章添加一個字段用于標(biāo)識其類別,并實現(xiàn)在templates中識別此標(biāo)識為文章分類顯示抛杨。

第二階段

準(zhǔn)備更多數(shù)據(jù)够委,實現(xiàn)分頁顯示。

  1. views.py中添加paginator相關(guān)的代碼
from django.shortcuts import render
from myblog.models import ArticleList
from django.core.paginator import Paginator
# Create your views here.
def artilist(request):
      limit = 4
      arti_info = ArticleList.objects[:4]
      paginator = Paginator(arti_info, limit)
      page = request.GET.get('page',1)
      loaded = paginator.page(page)
      context = {
        'artiinfo': loaded
      }
      return render(request, 'index.html', context)
  1. templates模板中添加翻頁按鈕
            <div class="paginator">
            {% if artiinfo.has_previous %}
                <a href="?page={{ artiinfo.previous_page_number }}">Previous</a>
            {% endif %}
            <span>{{ artiinfo.number }} of {{ artiinfo.paginator.num_pages }}</span>
            {% if artiinfo.has_next %}
                <a href="?page={{ artiinfo.next_page_number }}">Next</a>
            {% endif %}
            </div>

分頁顯示效果圖


Screen Shot 2016-07-16 at 6.26.59 PM.png
進階學(xué)習(xí)

變量item.portrait中保存的是各文章作者的頭像路徑怖现,且都是相對路徑茁帽,相對于static。如'img/common/tilo-avatar.jpg'屈嗤。
當(dāng)路徑是一個變量潘拨,且關(guān)聯(lián)static目錄時,引用方法如下
(https://docs.djangoproject.com/en/1.9/ref/templates/builtins/):

src="{% static item.portrait %}
  1. 優(yōu)化問題一
    templates模板中加入了條件判斷語句饶号,實現(xiàn)標(biāo)簽與class的對應(yīng)铁追,從而各個標(biāo)簽顯示各自特定的背景色。
 
                        <p class="post-meta">
                            By <a class="post-author" href="#">{{ item.author }}</a> under
                            {% for tag in item.categories %}
                                {% if tag == 'JavaScript' %}
                                    <a class="post-category post-category-js" href="#">{{ tag }}</a>
                                {% elif tag == 'CSS' %}
                                    <a class="post-category post-category-design" href="#">{{ tag }}</a>
                                {% elif tag == 'Pure' %}
                                    <a class="post-category post-category-pure" href="#">{{ tag }}</a>
                                {% elif tag == 'YUI' %}
                                    <a class="post-category post-category-yui" href="#">{{ tag }}</a>                             
                                {% else %}
                                    <a class="post-category" href="#">{{ tag }}</a>
                                {% endif %}
                            {% endfor %}
                        </p>
  1. 優(yōu)化問題二
    對<div class="post-description">的修改如下:
...
                   <div class="post-description">
                        {% if item.images %}
                        <div class="post-images pure-g">
                            {% for img in item.images %}
                            <div class="pure-u-1 pure-u-md-1-2">
                                <a href="">
                                    ![]({{ img }})
                                </a>
                                <div class="post-image-meta">
                                    <h3></h3>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                        {% endif %}
                        <p>
                            {{ item.description }}
                        </p>
                    </div>
...

效果圖


Screen Shot 2016-07-16 at 5.23.06 PM.png
  1. 優(yōu)化問題三
    為每篇文章添加一個屬性用來標(biāo)識其是否為置頂茫船。
    在templates中添加代碼判斷一篇文章是否是'pinned', 如果是則在'Pinned Post' wrapper中為其生成一個section琅束。
    在'Recent Posts'中做類似的判斷,當(dāng)一篇文章不是'pinned', 則為其創(chuàng)建section算谈。
            <!-- A wrapper for all the blog posts -->
            <div class="posts">
                <h1 class="content-subhead">Pinned Post</h1>
                <!-- A single blog post -->
                {% for item in artiinfo %}
                {% if item.level == 'pinned' %}
                <section class="post">
                     ......
                </section>
                {% endif %}
                {% endfor %}
            </div>
            <div class="posts">
                <h1 class="content-subhead">Recent Posts</h1>
                {% for item in artiinfo %}
                {% if item.level != 'pinned' %}
                <section class="post">
                     ......
                </section>
                {% endif %}
                {% endfor %}
            </div>

思考: 這樣處理帶來一個問題涩禀。作為讀者希望標(biāo)注了'pinned'的文章始終置頂。但用上面的方法然眼,如果'pinned'文章在數(shù)據(jù)庫中id為5, 也就是第五篇文章艾船,paginator以4篇文章為一頁,這篇'pinned'文章就被劃分在第二頁罪治。最終顯示的效果將是瀏覽第一頁時丽声,'pinned post'類別下沒有文章,瀏覽第二頁時觉义,'pinned post'下顯示出了這篇'pinned'文章雁社。
這個效果顯示不夠好。
理想的處理方式考慮下來是將'pinned'單獨篩選出來晒骇。僅對那些沒有'pinned'標(biāo)注的文章應(yīng)用paginator分頁顯示霉撵。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市洪囤,隨后出現(xiàn)的幾起案子徒坡,更是在濱河造成了極大的恐慌,老刑警劉巖瘤缩,帶你破解...
    沈念sama閱讀 222,000評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件喇完,死亡現(xiàn)場離奇詭異,居然都是意外死亡剥啤,警方通過查閱死者的電腦和手機锦溪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評論 3 399
  • 文/潘曉璐 我一進店門不脯,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人刻诊,你說我怎么就攤上這事防楷。” “怎么了则涯?”我有些...
    開封第一講書人閱讀 168,561評論 0 360
  • 文/不壞的土叔 我叫張陵复局,是天一觀的道長。 經(jīng)常有香客問我粟判,道長亿昏,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,782評論 1 298
  • 正文 為了忘掉前任浮入,我火速辦了婚禮龙优,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘事秀。我一直安慰自己彤断,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,798評論 6 397
  • 文/花漫 我一把揭開白布易迹。 她就那樣靜靜地躺著宰衙,像睡著了一般。 火紅的嫁衣襯著肌膚如雪睹欲。 梳的紋絲不亂的頭發(fā)上供炼,一...
    開封第一講書人閱讀 52,394評論 1 310
  • 那天,我揣著相機與錄音窘疮,去河邊找鬼袋哼。 笑死,一個胖子當(dāng)著我的面吹牛闸衫,可吹牛的內(nèi)容都是我干的涛贯。 我是一名探鬼主播,決...
    沈念sama閱讀 40,952評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼蔚出,長吁一口氣:“原來是場噩夢啊……” “哼弟翘!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起骄酗,我...
    開封第一講書人閱讀 39,852評論 0 276
  • 序言:老撾萬榮一對情侶失蹤稀余,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后趋翻,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體睛琳,經(jīng)...
    沈念sama閱讀 46,409評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,483評論 3 341
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了掸掏。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片茁影。...
    茶點故事閱讀 40,615評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖丧凤,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情步脓,我是刑警寧澤愿待,帶...
    沈念sama閱讀 36,303評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站靴患,受9級特大地震影響仍侥,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜鸳君,卻給世界環(huán)境...
    茶點故事閱讀 41,979評論 3 334
  • 文/蒙蒙 一农渊、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧或颊,春花似錦砸紊、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至平挑,卻和暖如春游添,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背通熄。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評論 1 272
  • 我被黑心中介騙來泰國打工唆涝, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人唇辨。 一個月前我還...
    沈念sama閱讀 49,041評論 3 377
  • 正文 我出身青樓廊酣,卻偏偏與公主長得像,于是被迫代替她去往敵國和親助泽。 傳聞我的和親對象是個殘疾皇子啰扛,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,630評論 2 359

推薦閱讀更多精彩內(nèi)容